File indexing completed on 2024-12-08 12:55:20
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 #include <QDebug> 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(locale.name().split('_').first()); 0017 } 0018 } 0019 0020 for (const auto &language : QLocale().uiLanguages()) { 0021 if (!language.contains('-')) { 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 return QLocale::languageToString(m_languages[index.row()]); 0032 case CustomRoles::CodeRole: 0033 return m_iso639codes[index.row()]; 0034 case CustomRoles::PreferredRole: 0035 return m_preferredLanguages.contains(m_iso639codes[index.row()]); 0036 default: 0037 return {}; 0038 } 0039 } 0040 0041 int RawLanguageModel::rowCount(const QModelIndex &parent) const 0042 { 0043 Q_UNUSED(parent); 0044 0045 return m_languages.count(); 0046 } 0047 0048 QHash<int, QByteArray> RawLanguageModel::roleNames() const 0049 { 0050 return {{CustomRoles::NameRole, "name"}, {CustomRoles::CodeRole, "code"}, {CustomRoles::PreferredRole, "preferred"}}; 0051 } 0052 0053 QString RawLanguageModel::getCode(const int index) const 0054 { 0055 return m_iso639codes[index]; 0056 } 0057 0058 LanguageModel::LanguageModel(QObject *parent) 0059 : QSortFilterProxyModel(parent) 0060 { 0061 m_model = new RawLanguageModel(this); 0062 0063 setSourceModel(m_model); 0064 sort(0, Qt::AscendingOrder); 0065 } 0066 0067 bool LanguageModel::lessThan(const QModelIndex &left, const QModelIndex &right) const 0068 { 0069 const bool preferred = sourceModel()->data(left, RawLanguageModel::CustomRoles::PreferredRole).toBool(); 0070 0071 if (preferred) { 0072 return true; 0073 } else { 0074 return QSortFilterProxyModel::lessThan(left, right); 0075 } 0076 } 0077 0078 QString LanguageModel::getCode(const int row) const 0079 { 0080 return m_model->getCode(mapToSource(index(row, 0)).row()); 0081 }