File indexing completed on 2024-07-21 04:35:04

0001 // SPDX-FileCopyrightText: 2023 Joshua Goins <josh@redstrate.com>
0002 // SPDX-License-Identifier: GPL-3.0-or-later
0003 
0004 #include "languagemodel.h"
0005 
0006 using namespace Qt::Literals::StringLiterals;
0007 
0008 RawLanguageModel::RawLanguageModel(QObject *parent)
0009     : QAbstractListModel(parent)
0010 {
0011     auto locales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry);
0012 
0013     for (const auto &locale : locales) {
0014         if (!m_languages.contains(locale.language()) && locale != QLocale::c()) {
0015             m_languages.push_back(locale.language());
0016             m_iso639codes.push_back(QLocale::languageToCode(locale.language(), QLocale::ISO639));
0017         }
0018     }
0019 
0020     for (const auto &language : QLocale().uiLanguages()) {
0021         if (!language.contains('-'_L1)) {
0022             m_preferredLanguages.push_back(language);
0023         }
0024     }
0025 }
0026 
0027 QVariant RawLanguageModel::data(const QModelIndex &index, int role) const
0028 {
0029     switch (role) {
0030     case CustomRoles::NameRole: {
0031         // Use the native language name if it exists
0032         if (const QString nativeName = QLocale(m_languages[index.row()]).nativeLanguageName(); !nativeName.isEmpty()) {
0033             return nativeName;
0034         } else if (const QString languageString = QLocale::languageToString(m_languages[index.row()]); !languageString.isEmpty()) {
0035             return languageString;
0036         } else {
0037             return m_iso639codes[index.row()];
0038         }
0039     }
0040     case CustomRoles::CodeRole:
0041         return m_iso639codes[index.row()];
0042     case CustomRoles::PreferredRole:
0043         return m_preferredLanguages.contains(m_iso639codes[index.row()]);
0044     default:
0045         return {};
0046     }
0047 }
0048 
0049 int RawLanguageModel::rowCount(const QModelIndex &parent) const
0050 {
0051     Q_UNUSED(parent);
0052 
0053     return m_languages.count();
0054 }
0055 
0056 QHash<int, QByteArray> RawLanguageModel::roleNames() const
0057 {
0058     return {{CustomRoles::NameRole, "name"}, {CustomRoles::CodeRole, "code"}, {CustomRoles::PreferredRole, "preferred"}};
0059 }
0060 
0061 QString RawLanguageModel::getCode(const int index) const
0062 {
0063     return m_iso639codes[index];
0064 }
0065 
0066 QModelIndex RawLanguageModel::indexOfValue(const QString &code)
0067 {
0068     const auto it = std::find(m_iso639codes.cbegin(), m_iso639codes.cend(), code);
0069     if (it != m_iso639codes.cend()) {
0070         return index(std::distance(m_iso639codes.cbegin(), it), 0);
0071     } else {
0072         return {};
0073     }
0074 }
0075 
0076 #include "moc_languagemodel.cpp"