1 | /* |
2 | SPDX-FileCopyrightText: 2014 Alex Richardson <arichardson.kde@gmail.com> |
3 | SPDX-FileCopyrightText: 2021 Alexander Lohnau <alexander.lohnau@gmx.de> |
4 | |
5 | SPDX-License-Identifier: LGPL-2.0-or-later |
6 | */ |
7 | |
8 | #include "kjsonutils.h" |
9 | |
10 | #include <QJsonObject> |
11 | |
12 | static QString getDefaultLocaleName() |
13 | { |
14 | #if defined(Q_OS_WIN) || defined(Q_OS_MAC) |
15 | if (QLocale() == QLocale::system()) { |
16 | // If the default locale hasn't been changed then |
17 | // On Windows and Apple OSs, we cannot use QLocale::system() if an application-specific |
18 | // language was set by kxmlgui because Qt ignores LANGUAGE on Windows and Apple OSs. |
19 | if (const auto firstLanguage = qEnvironmentVariable("LANGUAGE" ).section(u':', 0, 0, QString::SectionSkipEmpty); !firstLanguage.isEmpty()) { |
20 | return firstLanguage; |
21 | } |
22 | // Also prefer the configured display language over the system language |
23 | if (const auto languages = QLocale::system().uiLanguages(); !languages.isEmpty()) { |
24 | // uiLanguages() uses dashes as separator, but KConfig assumes underscores |
25 | return languages.value(0).replace(u'-', u'_'); |
26 | } |
27 | } |
28 | #endif |
29 | return QLocale().name(); |
30 | } |
31 | |
32 | QJsonValue KJsonUtils::readTranslatedValue(const QJsonObject &jo, const QString &key, const QJsonValue &defaultValue) |
33 | { |
34 | QString languageWithCountry = getDefaultLocaleName(); |
35 | auto it = jo.constFind(key: key + QLatin1Char('[') + languageWithCountry + QLatin1Char(']')); |
36 | if (it != jo.constEnd()) { |
37 | return it.value(); |
38 | } |
39 | const QStringView language = QStringView(languageWithCountry).mid(pos: 0, n: languageWithCountry.indexOf(ch: QLatin1Char('_'))); |
40 | it = jo.constFind(key: key + QLatin1Char('[') + language + QLatin1Char(']')); |
41 | if (it != jo.constEnd()) { |
42 | return it.value(); |
43 | } |
44 | // no translated value found -> check key |
45 | it = jo.constFind(key); |
46 | if (it != jo.constEnd()) { |
47 | return jo.value(key); |
48 | } |
49 | return defaultValue; |
50 | } |
51 | |
52 | QString KJsonUtils::readTranslatedString(const QJsonObject &jo, const QString &key, const QString &defaultValue) |
53 | { |
54 | return KJsonUtils::readTranslatedValue(jo, key, defaultValue).toString(defaultValue); |
55 | } |
56 | |