File indexing completed on 2025-01-26 05:07:37

0001 /*
0002     SPDX-FileCopyrightText: 2014 Martin Klapetek <mklapetek@kde.org>
0003 
0004     SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL
0005 */
0006 
0007 #include "timezonesi18n.h"
0008 
0009 #include <KCountry>
0010 #include <KLocalizedString>
0011 
0012 #include <unicode/localebuilder.h>
0013 
0014 #include "timezonesi18n_generated.h"
0015 
0016 TimezonesI18n::TimezonesI18n(QObject *parent)
0017     : QObject(parent)
0018     , m_isInitialized(false)
0019 {
0020 }
0021 
0022 QString TimezonesI18n::i18nContinents(const QString &continent)
0023 {
0024     if (!m_isInitialized) {
0025         init();
0026     }
0027     return m_i18nContinents.value(continent, continent);
0028 }
0029 
0030 QString TimezonesI18n::i18nCountry(QLocale::Country country)
0031 {
0032     if (!m_isInitialized) {
0033         init();
0034     }
0035 
0036     QString countryName = KCountry::fromQLocale(country).name();
0037 
0038     if (countryName.isEmpty()) {
0039         return QLocale::countryToString(country);
0040     }
0041 
0042     return countryName;
0043 }
0044 
0045 QString TimezonesI18n::i18nCity(const QString &timezoneId)
0046 {
0047     if (!m_isInitialized) {
0048         init();
0049     }
0050 
0051     if (!m_tzNames) {
0052         return timezoneId;
0053     }
0054 
0055     icu::UnicodeString result;
0056     const auto &cityName = m_tzNames->getExemplarLocationName(icu::UnicodeString::fromUTF8(icu::StringPiece(timezoneId.toStdString())), result);
0057 
0058     return cityName.isBogus() ? timezoneId : QString::fromUtf16(cityName.getBuffer(), cityName.length());
0059 }
0060 
0061 void TimezonesI18n::init()
0062 {
0063     m_i18nContinents = TimezonesI18nData::timezoneContinentToL10nMap();
0064 
0065     const auto locale = icu::Locale(QLocale::system().name().toLatin1());
0066     UErrorCode error = U_ZERO_ERROR;
0067     m_tzNames.reset(icu::TimeZoneNames::createInstance(locale, error));
0068     if (!U_SUCCESS(error)) {
0069         qWarning() << "failed to create timezone names:" << u_errorName(error);
0070     }
0071 
0072     m_isInitialized = true;
0073 }