The Battle for Wesnoth  1.15.3+dev
language.cpp
Go to the documentation of this file.
1 /*
2  Copyright (C) 2003 - 2018 by David White <dave@whitevine.net>
3  Part of the Battle for Wesnoth Project https://www.wesnoth.org/
4 
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9  This program is distributed in the hope that it will be useful,
10  but WITHOUT ANY WARRANTY.
11 
12  See the COPYING file for more details.
13 */
14 
15 #include "filesystem.hpp"
16 #include "gettext.hpp"
17 #include "language.hpp"
18 #include "log.hpp"
19 #include "preferences/general.hpp"
20 #include "serialization/parser.hpp"
22 
23 #include <stdexcept>
24 #include <clocale>
25 
26 #ifdef _WIN32
27 #include <windows.h>
28 #if !defined(_MSC_VER) && !defined(__MINGW32__)
29 extern "C" int _putenv(const char*);
30 #endif
31 #endif
32 
33 #ifdef __APPLE__
34 #include <cerrno>
35 #endif
36 
37 #define DBG_G LOG_STREAM(debug, lg::general())
38 #define LOG_G LOG_STREAM(info, lg::general())
39 #define WRN_G LOG_STREAM(warn, lg::general())
40 #define ERR_G LOG_STREAM(err, lg::general())
41 
42 namespace {
43  language_def current_language;
44  std::vector<config> languages_;
45  utils::string_map strings_;
46  int min_translation_percent = 80;
47 }
48 
50 
51 bool load_strings(bool complain);
52 
54 {
55  return get_language().rtl;
56 }
57 
59 {
60  return ((language == a.language) /* && (localename == a.localename) */ );
61 }
62 
64 
66 {
67  static bool result = true;
68  return result;
69 }
70 
71 const t_string& symbol_table::operator[](const std::string& key) const
72 {
73  const utils::string_map::const_iterator i = strings_.find(key);
74  if(i != strings_.end()) {
75  return i->second;
76  } else {
77  static t_string empty_string;
78  // Let's do it the painful way (untlb means untranslatABLE).
79  // It will cause problem if somebody stores more than one reference at once
80  // but I don't really care since this path is an error path and it should
81  // not have been taken in the first place. -- silene
82  empty_string = "UNTLB " + key;
83  return empty_string;
84  }
85 }
86 
87 const t_string& symbol_table::operator[](const char* key) const
88 {
89  return (*this)[std::string(key)];
90 }
91 
93 {
94  config cfg;
95  try {
97  read(cfg, *stream);
98  } catch(const config::error &) {
99  return false;
100  }
101 
102  known_languages.clear();
103  known_languages.emplace_back("", t_string(N_("System default language"), "wesnoth"), "ltr", "", "A", "100");
104 
105  for (const config &lang : cfg.child_range("locale"))
106  {
107  known_languages.emplace_back(
108  lang["locale"], lang["name"], lang["dir"],
109  lang["alternates"], lang["sort_name"], lang["percent"]);
110  }
111 
112  return true;
113 }
114 
116 {
117  // We sort every time, the local might have changed which can modify the
118  // sort order.
119  std::sort(known_languages.begin(), known_languages.end());
120 
121  if(min_translation_percent == 0) {
122  return known_languages;
123  }
124 
125  language_list result;
126  std::copy_if(known_languages.begin(), known_languages.end(), std::back_inserter(result),
127  [](const language_def& lang) { return lang.percent >= min_translation_percent; });
128 
129  return result;
130 }
131 
133  min_translation_percent = percent;
134 }
135 
136 #ifdef _WIN32
137 // Simplified translation table from unix locale symbols to win32 locale strings
138 static const std::map<std::string, std::string> win32_locales_map = {
139  { "af", "Afrikaans" },
140  { "ang", "C" },
141  { "ar", "Arabic" },
142  { "bg", "Bulgarian" },
143  { "ca", "Catalan" },
144  { "cs", "Czech" },
145  { "da", "Danish" },
146  { "de", "German" },
147  { "el", "Greek" },
148  { "en", "English" },
149  { "eo", "C" },
150  { "es", "Spanish" },
151  { "et", "Estonian" },
152  { "eu", "Basque" },
153  { "fi", "Finnish" },
154  { "fr", "French" },
155  { "fur", "C" },
156  { "ga", "Irish_Ireland" }, // Yes, "Irish" alone does not work
157  { "gl", "Galician" },
158  { "he", "Hebrew" },
159  { "hr", "Croatian" },
160  { "hu", "Hungarian" },
161  { "id", "Indonesian" },
162  { "is", "Icelandic" },
163  { "it", "Italian" },
164  { "ja", "Japanese" },
165  { "ko", "Korean" },
166  { "la", "C" },
167  { "lt", "Lithuanian" },
168  { "lv", "Latvian" },
169  { "mk", "Macedonian" },
170  { "mr", "C" },
171  { "nb", "Norwegian" },
172  { "nl", "Dutch" },
173  { "pl", "Polish" },
174  { "pt", "Portuguese" },
175  { "racv", "C" },
176  { "ro", "Romanian" },
177  { "ru", "Russian" },
178  { "sk", "Slovak" },
179  { "sl", "Slovenian" },
180  { "sr", "Serbian" },
181  { "sv", "Swedish" },
182  { "tl", "Filipino" },
183  { "tr", "Turkish" },
184  { "uk", "Ukrainian" },
185  { "vi", "Vietnamese" },
186  { "zh", "Chinese" },
187 };
188 
189 static const std::string& posix_locale_to_win32(const std::string& posix)
190 {
191  auto it = win32_locales_map.find(posix);
192  return it != win32_locales_map.end() ? it->second : posix;
193 }
194 
195 #endif
196 
197 static void wesnoth_setlocale(int category, const std::string& slocale,
198  std::vector<std::string> const *alternates)
199 {
200  std::string locale = slocale;
201  // FIXME: ideally we should check LANGUAGE and on first invocation
202  // use that value, so someone with es would get the game in Spanish
203  // instead of en_US the first time round
204  // LANGUAGE overrides other settings, so for now just get rid of it
205  // FIXME: add configure check for unsetenv
206 
207  //category is never LC_MESSAGES since that case was moved to gettext.cpp to remove the dependency to libintl.h in this file
208  //that's why code like if (category == LC_MESSAGES) is outcommented here.
209 #ifndef _WIN32
210  unsetenv ("LANGUAGE"); // void so no return value to check
211 #endif
212 #ifdef __APPLE__
213  //if (category == LC_MESSAGES && setenv("LANG", locale.c_str(), 1) == -1) {
214  // ERR_G << "setenv LANG failed: " << strerror(errno);
215  //}
216 #endif
217 
218 #ifdef _WIN32
219  std::string lang_code{locale, 0, locale.find_first_of("_@.")};
220  locale = posix_locale_to_win32(lang_code);
221 #endif
222 
223  char *res = nullptr;
224  std::vector<std::string>::const_iterator i;
225  if (alternates) i = alternates->begin();
226 
227  for (;;)
228  {
229  std::string lang = locale, extra;
230  std::string::size_type pos = locale.find('@');
231  if (pos != std::string::npos) {
232  lang.erase(pos);
233  extra = locale.substr(pos);
234  }
235 
236  /*
237  * The "" is the last item to work-around a problem in glibc picking
238  * the non utf8 locale instead an utf8 version if available.
239  */
240  char const *encoding[] { ".utf-8", ".UTF-8", "" };
241  for (int j = 0; j != 3; ++j)
242  {
243  locale = lang + encoding[j] + extra;
244  res = std::setlocale(category, locale.c_str());
245  if (res) {
246  LOG_G << "Set locale to '" << locale << "' result: '" << res << "'.\n";
247  goto done;
248  }
249  }
250 
251  if (!alternates || i == alternates->end()) break;
252  locale = *i;
253  ++i;
254  }
255 
256  WRN_G << "setlocale() failed for '" << slocale << "'." << std::endl;
257 
258  if (category == LC_TIME) {
259  time_locale_correct() = false;
260  }
261 
262 #ifndef _WIN32
263  //if(category == LC_MESSAGES) {
264  // WRN_G << "Setting LANGUAGE to '" << slocale << "'." << std::endl;
265  // setenv("LANGUAGE", slocale.c_str(), 1);
266  // std::setlocale(LC_MESSAGES, "");
267  //}
268 #endif
269 
270  done:
271  DBG_G << "Numeric locale: " << std::setlocale(LC_NUMERIC, nullptr) << '\n';
272  DBG_G << "Full locale: " << std::setlocale(LC_ALL, nullptr) << '\n';
273 }
274 
275 void set_language(const language_def& locale)
276 {
277  strings_.clear();
278 
279  std::string locale_lc;
280  locale_lc.resize(locale.localename.size());
281  std::transform(locale.localename.begin(),locale.localename.end(),locale_lc.begin(),tolower);
282 
283  current_language = locale;
284  time_locale_correct() = true;
285 
286  wesnoth_setlocale(LC_COLLATE, locale.localename, &locale.alternates);
287  wesnoth_setlocale(LC_TIME, locale.localename, &locale.alternates);
289  load_strings(false);
290 }
291 
292 bool load_strings(bool complain)
293 {
294  DBG_G << "Loading strings\n";
295  config cfg;
296 
297  LOG_G << "There are " << languages_.size() << " [language] blocks\n";
298  if (complain && languages_.empty()) {
299  std::cerr << "No [language] block found\n";
300  return false;
301  }
302  for (const config &lang : languages_) {
303  DBG_G << "[language]\n";
304  for (const config::attribute &j : lang.attribute_range()) {
305  DBG_G << j.first << "=\"" << j.second << "\"\n";
306  strings_[j.first] = j.second;
307  }
308  DBG_G << "[/language]\n";
309  }
310  DBG_G << "done\n";
311 
312  return true;
313 }
314 
315 const language_def& get_language() { return current_language; }
316 
318 {
319  //TODO: Add in support for querying the locale on Windows
320 
321  assert(!known_languages.empty());
322 
323  const std::string& prefs_locale = preferences::language();
324  if(prefs_locale.empty() == false) {
325  translation::set_language(prefs_locale, nullptr);
326  for(language_list::const_iterator i = known_languages.begin();
327  i != known_languages.end(); ++i) {
328  if (prefs_locale == i->localename)
329  return *i;
330  }
331  LOG_G << "'" << prefs_locale << "' locale not found in known array; defaulting to system locale\n";
332  return known_languages[0];
333  }
334 
335 #if 0
336  const char* const locale = getenv("LANG");
337  #ifdef _WIN32
338  return posix_locale_to_win32(locale);
339  #endif
340  if(locale != nullptr && strlen(locale) >= 2) {
341  //we can't pass pointers into the string to the std::string
342  //constructor because some STL implementations don't support
343  //it (*cough* MSVC++6)
344  std::string res(2,'z');
345  res[0] = tolower(locale[0]);
346  res[1] = tolower(locale[1]);
347  return res;
348  }
349 #endif
350 
351  LOG_G << "locale could not be determined; defaulting to system locale\n";
352  return known_languages[0];
353 }
354 
355 void init_textdomains(const config& cfg)
356 {
357  for (const config &t : cfg.child_range("textdomain"))
358  {
359  const std::string &name = t["name"];
360  const std::string &path = t["path"];
361 
362  if(path.empty()) {
364  } else {
365  std::string location = filesystem::get_binary_dir_location("", path);
366 
367  if (location.empty()) {
368  //if location is empty, this causes a crash on Windows, so we
369  //disallow adding empty domains
370  WRN_G << "no location found for '" << path << "', skipping textdomain" << std::endl;
371  } else {
372  t_string::add_textdomain(name, location);
373  }
374  }
375  }
376 }
377 
378 bool init_strings(const config& cfg)
379 {
380  languages_.clear();
381  for (const config &l : cfg.child_range("language")) {
382  languages_.push_back(l);
383  }
384  return load_strings(true);
385 }
386 
387 /* vim:set encoding=utf-8: */
bool & time_locale_correct()
Definition: language.cpp:65
std::string get_binary_dir_location(const std::string &type, const std::string &filename)
Returns a complete path to the actual directory of a given type or an empty string if the directory i...
#define WRN_G
Definition: language.cpp:39
std::map< std::string, t_string > string_map
#define a
child_itors child_range(config_key_type key)
Definition: config.cpp:362
attribute_map::value_type attribute
Definition: config.hpp:226
const language_def & get_locale()
Definition: language.cpp:317
void set_language(const std::string &language, const std::vector< std::string > *)
Definition: gettext.cpp:449
void set_min_translation_percent(int percent)
Definition: language.cpp:132
bool operator==(const language_def &) const
Definition: language.cpp:58
static language_list known_languages
Definition: language.cpp:49
#define LOG_G
Definition: language.cpp:38
bool current_language_rtl()
Definition: language.cpp:53
static void add_textdomain(const std::string &name, const std::string &path)
Definition: tstring.cpp:646
void read(config &cfg, std::istream &in, abstract_validator *validator)
Definition: parser.cpp:625
std::string get_intl_dir()
std::string localename
Definition: language.hpp:52
std::unique_ptr< std::istream > scoped_istream
Definition: filesystem.hpp:39
std::string path
Definition: game_config.cpp:39
static void wesnoth_setlocale(int category, const std::string &slocale, std::vector< std::string > const *alternates)
Definition: language.cpp:197
void init_textdomains(const config &cfg)
Initializes the list of textdomains from a configuration object.
Definition: language.cpp:355
std::size_t i
Definition: function.cpp:933
std::string get_wml_location(const std::string &filename, const std::string &current_dir)
Returns a complete path to the actual WML file or directory or an empty string if the file isn&#39;t pres...
const language_def & get_language()
Definition: language.cpp:315
bool load_language_list()
Definition: language.cpp:92
std::vector< language_def > language_list
Definition: language.hpp:64
language_list get_languages()
Definition: language.cpp:115
std::string language()
Definition: general.cpp:475
Declarations for File-IO.
#define N_(String)
Definition: gettext.hpp:99
static int sort(lua_State *L)
Definition: ltablib.cpp:411
t_string language
Definition: language.hpp:54
int percent
% of translated text in core po-s
Definition: language.hpp:58
void set_language(const language_def &locale)
Definition: language.cpp:275
#define DBG_G
Definition: language.cpp:37
double t
Definition: astarsearch.cpp:64
symbol_table string_table
Definition: language.cpp:63
const t_string & operator[](const std::string &key) const
Definition: language.cpp:71
Standard logging facilities (interface).
bool init_strings(const config &cfg)
Initializes certain English strings.
Definition: language.cpp:378
A config object defines a single node in a WML file, with access to child nodes.
Definition: config.hpp:68
filesystem::scoped_istream preprocess_file(const std::string &fname, preproc_map *defines)
bool load_strings(bool complain)
Definition: language.cpp:292
std::vector< std::string > alternates
Definition: language.hpp:53