File indexing completed on 2024-05-12 04:42:18

0001 /*
0002     SPDX-FileCopyrightText: 2023 Volker Krause <vkrause@kde.org>
0003     SPDX-License-Identifier: LGPL-2.0-or-later
0004 */
0005 
0006 #include "languages.h"
0007 
0008 #include <QLocale>
0009 
0010 static bool cmpLang(const std::string &lhs, QStringView rhs)
0011 {
0012     return QAnyStringView::compare(QAnyStringView(lhs.c_str(), lhs.size()), rhs) == 0;
0013 }
0014 
0015 static void addLanguage(OSM::Languages &langs, QStringView langWithScript, QStringView lang)
0016 {
0017     if (!langWithScript.isEmpty()) {
0018         for (auto &it : langs.languages) {
0019             if (cmpLang(it, langWithScript)) {
0020                 langWithScript = {};
0021                 break;
0022             }
0023             if (cmpLang(it, lang)) {
0024                 it = langWithScript.toUtf8().constData();
0025                 langWithScript = {};
0026                 break;
0027             }
0028         }
0029     }
0030     if (!langWithScript.isEmpty()) {
0031         langs.languages.emplace_back(langWithScript.toUtf8().constData());
0032     }
0033 
0034     const auto it = std::find_if(langs.languages.begin(), langs.languages.end(), [lang](const auto &l) { return cmpLang(l, lang); });
0035     if (it == langs.languages.end()) {
0036         langs.languages.emplace_back(lang.toUtf8().constData());
0037     }
0038 }
0039 
0040 OSM::Languages OSM::Languages::fromQLocale(const QLocale &locale)
0041 {
0042     Languages langs;
0043 
0044     const auto uiLangs = locale.uiLanguages();
0045     langs.languages.reserve(uiLangs.size());
0046     for (const auto &uiLang : uiLangs) {
0047         QStringView s(uiLang);
0048         const auto dashCount = s.count(QLatin1Char('-'));
0049         if (dashCount == 0) {
0050             addLanguage(langs, {}, s);
0051             continue;
0052         }
0053         if (dashCount > 1) {
0054             const auto idx = s.lastIndexOf(QLatin1Char('-'));
0055             s = s.left(idx);
0056         }
0057 
0058         const auto idx = s.indexOf(QLatin1Char('-'));
0059         if (s.mid(idx + 1).size() == 2) {
0060             // second part is a country code, that does not occur in OSM language keys
0061             addLanguage(langs, {}, s.left(idx));
0062         } else {
0063             // second part is a script
0064             addLanguage(langs, s, s.left(idx));
0065         }
0066     }
0067 
0068     return langs;
0069 }