Debian Codegraph @

src/Gui/Language/Translator.cpp

raw
1 /***************************************************************************
2 * Copyright (c) 2004 Werner Mayer <wmayer[at]users.sourceforge.net> *
3 * *
4 * This file is part of the FreeCAD CAx development system. *
5 * *
6 * This library is free software; you can redistribute it and/or *
7 * modify it under the terms of the GNU Library General Public *
8 * License as published by the Free Software Foundation; either *
9 * version 2 of the License, or (at your option) any later version. *
10 * *
11 * This library is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU Library General Public License for more details. *
15 * *
16 * You should have received a copy of the GNU Library General Public *
17 * License along with this library; see the file COPYING.LIB. If not, *
18 * write to the Free Software Foundation, Inc., 59 Temple Place, *
19 * Suite 330, Boston, MA 02111-1307, USA *
20 * *
21 ***************************************************************************/
22
23 #include <algorithm>
24 #include <QApplication>
25 #include <QDir>
26 #include <QKeyEvent>
27 #include <QRegularExpression>
28 #include <QStringList>
29 #include <QTranslator>
30 #include <QWidget>
31
32
33 #include <App/Application.h>
34 #include <Gui/TextEdit.h>
35 #include "Translator.h"
36
37
38 using namespace Gui;
39
40 /** \defgroup i18n Internationalization with FreeCAD
41 * \ingroup GUI
42 *
43 * The internationalization of FreeCAD makes heavy use of the internationalization
44 * support of Qt. For more details refer to your Qt documentation.
45 *
46 * \section stepbystep_language Step by step
47 * To integrate a new language into FreeCAD or one of its application modules
48 * you have to perform the following steps:
49 *
50 * \subsection tsfile Creation of a .ts file
51 * First you have to generate a .ts file for the language to be translated. You can do this
52 * by running the \a lupdate tool in the \a bin path of your Qt installation. As argument
53 * you can specify either all related source files and the .ts output file or a Qt project
54 * file (.pro) which contains all relevant source files.
55 *
56 * \subsection translate Translation into your language
57 * To translate the english string literals into the language you want to support you can open your
58 * .ts file with \a QtLinguist and translate all literals by hand. Another way
59 * for translation is to use the tool \a tsauto from Sebastien Fricker.This tool uses the
60 * engine from Google web page (www.google.com). tsauto supports the languages
61 * \li english
62 * \li french
63 * \li german
64 * \li italian
65 * \li portuguese and
66 * \li spanish
67 *
68 * \remark To get most of the literals translated you should have removed all
69 * special characters (like &, !, ?, ...). Otherwise the translation could fail.
70 * After having translated all literals you can load the .ts file into QtLinguist and
71 * invoke the menu item \a Release which generates the binary .qm file.
72 *
73 * \subsection usets Integration of the .qm file
74 * The .qm file should now be integrated into the GUI library (either of FreeCAD
75 * itself or its application module). The .qm file will be embedded into the
76 * resulting binary file. So, at runtime you don't need any .qm files any
77 * more. Indeed you will have a bigger binary file but you haven't any troubles
78 * concerning missing .qm files.
79 *
80 * To integrate the .qm file into the executable you have to create a resource file (.qrc), first.
81 * This is an XML file where you can append the .qm file. For the .qrc file you have to define the
82 * following curstom build step inside the Visual Studio project file:
83 *
84 * Command Line: rcc.exe -name $(InputName) $(InputPath) -o "$(InputDir)qrc_$(InputName).cpp"
85 * Outputs: $(InputDir)qrc_$(InputName).cpp
86 *
87 * For the gcc build system you just have to add the line \<resourcefile\>.qrc to the BUILT_SOURCES
88 * sources section of the Makefile.am, run automake and configure (or ./confog.status) afterwards.
89 *
90 * Finally, you have to add a the line
91 * \code
92 *
93 * Q_INIT_RESOURCE(resource);
94 *
95 * \endcode
96 *
97 * where \a resource is the name of the .qrc file. That's all!
98 */
99
100 /* TRANSLATOR Gui::Translator */
101
102 Translator* Translator::_pcSingleton = nullptr;
103
104 namespace Gui
105 {
106 class TranslatorP
107 {
108 public:
109 std::string activatedLanguage; /**< Active language */
110 std::map<std::string, std::string> mapLanguageTopLevelDomain;
111 TStringMap mapSupportedLocales;
112 std::list<QTranslator*> translators; /**< A list of all created translators */
113 QStringList paths;
114 };
115 } // namespace Gui
116
117 class Translator::ParameterObserver: public ParameterGrp::ObserverType
118 {
119 public:
120 ParameterObserver(Translator* client)
121 : client(client)
122 {
123 hGrp = App::GetApplication().GetParameterGroupByPath(
124 "User parameter:BaseApp/Preferences/General"
125 );
126 hGrp->Attach(this);
127 }
128
129 void OnChange(Base::Subject<const char*>& caller, const char* creason) override
130 {
131 (void)caller;
132
133 std::string_view reason = creason;
134 if (reason == "UseLocaleFormatting") {
135 int format = hGrp->GetInt("UseLocaleFormatting");
136 if (format == 0) {
137 client->setLocale(); // Defaults to system locale
138 }
139 else if (format == 1) {
140 // Language must need to be set before locale. How do we ensure this?
141 std::string language = hGrp->GetASCII("Language");
142 client->setLocale(language);
143 }
144 else if (format == 2) {
145 client->setLocale("C");
146 }
147 else {
148 throw Base::ValueError("Parameter \"UseLocaleFormatting\" value out of bounds for Translator::formattingOptions");
149 }
150 }
151 else if (reason == "SubstituteDecimalSeparator") {
152 bool value = hGrp->GetBool("SubstituteDecimalSeparator");
153 client->enableDecimalPointConversion(value);
154 }
155 }
156
157 Translator* client;
158 static ParameterGrp::handle hGrp;
159 };
160 ParameterGrp::handle Translator::ParameterObserver::hGrp; // definition for export
161
162 Translator* Translator::instance()
163 {
164 if (!_pcSingleton) {
165 _pcSingleton = new Translator;
166 }
167 return _pcSingleton;
168 }
169
170 void Translator::destruct()
171 {
172 if (_pcSingleton) {
173 delete _pcSingleton;
174 }
175 _pcSingleton = nullptr;
176 }
177
178 Translator::Translator()
179 {
180 observer = std::make_unique<Translator::ParameterObserver>(this);
181
182 // This is needed for Qt's lupdate
183 // clang-format off
184 d = new TranslatorP;
185 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Afrikaans" )] = "af";
186 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Arabic" )] = "ar";
187 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Basque" )] = "eu";
188 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Belarusian" )] = "be";
189 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Bulgarian" )] = "bg";
190 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Catalan" )] = "ca";
191 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Chinese (Simplified)" )] = "zh-CN";
192 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Chinese (Traditional)" )] = "zh-TW";
193 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Croatian" )] = "hr";
194 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Czech" )] = "cs";
195 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Danish" )] = "da";
196 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Dutch" )] = "nl";
197 d->mapLanguageTopLevelDomain[QT_TR_NOOP("English" )] = "en";
198 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Filipino" )] = "fil";
199 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Finnish" )] = "fi";
200 d->mapLanguageTopLevelDomain[QT_TR_NOOP("French" )] = "fr";
201 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Galician" )] = "gl";
202 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Georgian" )] = "ka";
203 d->mapLanguageTopLevelDomain[QT_TR_NOOP("German" )] = "de";
204 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Greek" )] = "el";
205 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Hungarian" )] = "hu";
206 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Indonesian" )] = "id";
207 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Italian" )] = "it";
208 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Japanese" )] = "ja";
209 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Kabyle" )] = "kab";
210 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Korean" )] = "ko";
211 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Lithuanian" )] = "lt";
212 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Norwegian" )] = "no";
213 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Polish" )] = "pl";
214 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Portuguese (Brazilian)")] = "pt-BR";
215 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Portuguese" )] = "pt-PT";
216 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Romanian" )] = "ro";
217 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Russian" )] = "ru";
218 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Serbian" )] = "sr";
219 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Serbian (Latin)" )] = "sr-CS";
220 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Slovak" )] = "sk";
221 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Slovenian" )] = "sl";
222 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Spanish" )] = "es-ES";
223 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Spanish (Argentina)" )] = "es-AR";
224 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Swedish" )] = "sv-SE";
225 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Turkish" )] = "tr";
226 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Ukrainian" )] = "uk";
227 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Valencian" )] = "val-ES";
228 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Vietnamese" )] = "vi";
229 d->mapLanguageTopLevelDomain[QT_TR_NOOP("Malay")] = "ms";
230
231 auto hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/General");
232 auto entries = hGrp->GetASCII("AdditionalLanguageDomainEntries", "");
233 // The format of the entries is "Language Name 1"="code1";"Language Name 2"="code2";...
234 // Example: <FCText Name="AdditionalLanguageDomainEntries">"Romanian"="ro";"Polish"="pl";</FCText>
235 QRegularExpression matchingRE(QStringLiteral("\"(.*[^\\s]+.*)\"\\s*=\\s*\"([^\\s]+)\";?"));
236 auto matches = matchingRE.globalMatch(QString::fromStdString(entries));
237 while (matches.hasNext()) {
238 QRegularExpressionMatch match = matches.next();
239 QString language = match.captured(1);
240 QString tld = match.captured(2);
241 d->mapLanguageTopLevelDomain[language.toStdString()] = tld.toStdString();
242 }
243 // clang-format on
244
245 d->activatedLanguage = "English";
246
247 d->paths = directories();
248
249 enableDecimalPointConversion(hGrp->GetBool("SubstituteDecimalSeparator", false));
250 }
251
252 Translator::~Translator()
253 {
254 removeTranslators();
255 delete d;
256 }
257
258 TStringList Translator::supportedLanguages() const
259 {
260 TStringList languages;
261 TStringMap locales = supportedLocales();
262 for (const auto& it : locales) {
263 languages.push_back(it.first);
264 }
265
266 return languages;
267 }
268
269 TStringMap Translator::supportedLocales() const
270 {
271 if (!d->mapSupportedLocales.empty()) {
272 return d->mapSupportedLocales;
273 }
274
275 // List all .qm files
276 for (const auto& domainMap : d->mapLanguageTopLevelDomain) {
277 for (const auto& directoryName : std::as_const(d->paths)) {
278 QDir dir(directoryName);
279 QString filter = QStringLiteral("*_%1.qm").arg(QString::fromStdString(domainMap.second));
280 QStringList fileNames = dir.entryList(QStringList(filter), QDir::Files, QDir::Name);
281 if (!fileNames.isEmpty()) {
282 d->mapSupportedLocales[domainMap.first] = domainMap.second;
283 break;
284 }
285 }
286 }
287
288 return d->mapSupportedLocales;
289 }
290
291 void Translator::activateLanguage(const char* lang)
292 {
293 removeTranslators(); // remove the currently installed translators
294 d->activatedLanguage = lang;
295 TStringList languages = supportedLanguages();
296 if (std::ranges::find(languages, lang) != languages.end()) {
297 refresh();
298 }
299 }
300
301 std::string Translator::activeLanguage() const
302 {
303 return d->activatedLanguage;
304 }
305
306 std::string Translator::locale(const std::string& lang) const
307 {
308 std::string loc;
309 std::map<std::string, std::string>::const_iterator tld = d->mapLanguageTopLevelDomain.find(lang);
310 if (tld != d->mapLanguageTopLevelDomain.end()) {
311 loc = tld->second;
312 }
313
314 return loc;
315 }
316
317 void Translator::setLocale(const std::string& language) const
318 {
319 auto loc = QLocale::system(); // Defaulting to OS locale
320 if (language == "C" || language == "c") {
321 loc = QLocale::c();
322 }
323 else {
324 auto bcp47 = locale(language);
325 if (!bcp47.empty()) {
326 loc = QLocale(QString::fromStdString(bcp47));
327 }
328 }
329 QLocale::setDefault(loc);
330 updateLocaleChange();
331
332 #ifdef FC_DEBUG
333 Base::Console()
334 .log("Locale changed to %s => %s\n", qPrintable(loc.bcp47Name()), qPrintable(loc.name()));
335 #endif
336 }
337
338 void Translator::updateLocaleChange() const
339 {
340 for (auto& topLevelWidget : qApp->topLevelWidgets()) {
341 topLevelWidget->setLocale(QLocale());
342 }
343 }
344
345 QStringList Translator::directories() const
346 {
347 QStringList list;
348 auto dir = App::GetApplication()
349 .GetParameterGroupByPath("User parameter:BaseApp/Preferences/General")
350 ->GetASCII("AdditionalTranslationsDirectory", "");
351 if (!dir.empty()) {
352 list.push_back(QString::fromStdString(dir));
353 }
354 QDir home(QString::fromUtf8(App::Application::getUserAppDataDir().c_str()));
355 list.push_back(home.absoluteFilePath(QLatin1String("translations")));
356 QDir resc(QString::fromUtf8(App::Application::getResourceDir().c_str()));
357 list.push_back(resc.absoluteFilePath(QLatin1String("translations")));
358 list.push_back(QLatin1String(":/translations"));
359
360 return list;
361 }
362
363 void Translator::addPath(const QString& path)
364 {
365 d->paths.push_back(path);
366 }
367
368 void Translator::installQMFiles(const QDir& dir, const char* locale)
369 {
370 QString filter = QStringLiteral("*_%1.qm").arg(QLatin1String(locale));
371 QStringList fileNames = dir.entryList(QStringList(filter), QDir::Files, QDir::Name);
372 for (const auto& it : fileNames) {
373 bool ok = false;
374 for (std::list<QTranslator*>::const_iterator tt = d->translators.begin();
375 tt != d->translators.end();
376 ++tt) {
377 if ((*tt)->objectName() == it) {
378 ok = true; // this file is already installed
379 break;
380 }
381 }
382
383 // okay, we need to install this file
384 if (!ok) {
385 auto translator = new QTranslator;
386 translator->setObjectName(it);
387 if (translator->load(dir.filePath(it))) {
388 qApp->installTranslator(translator);
389 d->translators.push_back(translator);
390 }
391 else {
392 delete translator;
393 }
394 }
395 }
396 }
397
398 /**
399 * This method checks for newly added (internal) .qm files which might be added at runtime. This
400 * e.g. happens if a plugin gets loaded at runtime. For each newly added files that supports the
401 * currently set language a new translator object is created to load the file.
402 */
403 void Translator::refresh()
404 {
405 std::map<std::string, std::string>::iterator tld = d->mapLanguageTopLevelDomain.find(
406 d->activatedLanguage
407 );
408 if (tld == d->mapLanguageTopLevelDomain.end()) {
409 return; // no language activated
410 }
411 for (const QString& it : d->paths) {
412 QDir dir(it);
413 installQMFiles(dir, tld->second.c_str());
414 }
415 }
416
417 /**
418 * Uninstalls all translators.
419 */
420 void Translator::removeTranslators()
421 {
422 for (QTranslator* it : d->translators) {
423 qApp->removeTranslator(it);
424 delete it;
425 }
426
427 d->translators.clear();
428 }
429
430 bool Translator::eventFilter(QObject* obj, QEvent* ev)
431 {
432 if (ev->type() == QEvent::KeyPress || ev->type() == QEvent::KeyRelease) {
433 QKeyEvent* kev = static_cast<QKeyEvent*>(ev);
434 Qt::KeyboardModifiers mod = kev->modifiers();
435 int key = kev->key();
436 if ((mod & Qt::KeypadModifier) && (key == Qt::Key_Period || key == Qt::Key_Comma)) {
437 if (ev->spontaneous()) {
438 auto dp = QString(QLocale().decimalPoint());
439 #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
440 int dpcode = QKeySequence(dp)[0];
441 #else
442 int dpcode = QKeySequence(dp)[0].key();
443 #endif
444 if (kev->text() != dp) {
445 QKeyEvent modifiedKeyEvent(
446 kev->type(),
447 dpcode,
448 mod,
449 dp,
450 kev->isAutoRepeat(),
451 kev->count()
452 );
453 qApp->sendEvent(obj, &modifiedKeyEvent);
454 return true;
455 }
456 }
457 if (dynamic_cast<Gui::TextEdit*>(obj) && key != Qt::Key_Period) {
458 QKeyEvent modifiedKeyEvent(
459 kev->type(),
460 Qt::Key_Period,
461 mod,
462 QChar::fromLatin1('.'),
463 kev->isAutoRepeat(),
464 kev->count()
465 );
466 qApp->sendEvent(obj, &modifiedKeyEvent);
467 return true;
468 }
469 }
470 }
471 return false;
472 }
473
474 void Translator::enableDecimalPointConversion(bool on)
475 {
476 if (!qApp) {
477 return;
478 }
479
480 if (!on) {
481 decimalPointConverter.reset();
482 return;
483 }
484 #if FC_DEBUG
485 if (on && decimalPointConverter) {
486 Base::Console().instance().warning(
487 "Translator: decimal point converter is already installed\n"
488 );
489 }
490 #endif
491 if (on && !decimalPointConverter) {
492 decimalPointConverter = std::unique_ptr<Translator, std::function<void(Translator*)>>(
493 this,
494 [](Translator* evFilter) { qApp->removeEventFilter(evFilter); }
495 );
496 qApp->installEventFilter(decimalPointConverter.get());
497 }
498 }
499
500 bool Translator::isEnabledDecimalPointConversion() const
501 {
502 return static_cast<bool>(decimalPointConverter);
503 }
504
505 #include "moc_Translator.cpp"