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