File: i18n.cpp

package info (click to toggle)
lomiri-ui-toolkit 1.3.5010%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 25,900 kB
  • sloc: cpp: 85,772; python: 5,528; sh: 1,364; javascript: 919; ansic: 573; makefile: 204
file content (369 lines) | stat: -rw-r--r-- 13,999 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/*
 * Copyright 2012-2015 Canonical Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Author: Tim Peeters <tim.peeters@canonical.om>
 */

#include "i18n_p.h"

namespace C {
#include <libintl.h>
#include <glib.h>
#include <glib/gi18n.h>
}
#include <stdlib.h>
#include <locale.h>

#include <QtCore/QDir>

#include "timeutils_p.h"

UT_NAMESPACE_BEGIN
/*!
 * \qmltype i18n
 * \inqmlmodule Lomiri.Components
 * \ingroup lomiri
 * \brief i18n is a context property that provides internationalization support.
 *
 * i18n cannot be instantiated, and is already available as a context property.
 * It is based on \l {https://www.gnu.org/software/gettext/} {gettext}, and thus the standard gettext tools can be used for translating
 * a project. Example:
 * \qml
 * import QtQuick 2.4
 * import Lomiri.Components 0.1
 *
 * Item {
 *      width: units.gu(40)
 *      height: units.gu(50)
 *
 *      Button {
 *          anchors.centerIn: parent
 *          text: i18n.tr("Press me")
 *      }
 * }
 * \endqml
 */
LomiriI18n *LomiriI18n::m_i18 = nullptr;

LomiriI18n::LomiriI18n(QObject* parent) : QObject(parent)
{
    /*
     * setlocale
     * category = LC_ALL: All types of i18n: LC_MESSAGES, LC_NUMERIC, LC_TIME
     * locale = "": Lookup the environment for $LC_ALL, $LC_* and $LANG in that order
     * Returns: for example en_US.utf8, da_DK or POSIX
     *
     * Note: $LANGUAGE is implicitly respected by gettext() calls and
     *   defines the order of multiple locales
     */
    m_language = QString::fromLocal8Bit(setlocale(LC_ALL, ""));
}

LomiriI18n::~LomiriI18n()
{
    m_i18 = nullptr;
}

/*!
 * \qmlproperty string i18n::domain
 * The gettext domain to be used for the translation. The default domain
 * is the applicationName specified in the application's \l MainView, or the empty string "" if
 * no applicationName was given or no \l MainView is used.
 * Use dtr() functions instead of tr() to use a different domain for a single translation
 * that ignores i18n.domain.
 */
QString LomiriI18n::domain() const {
    return m_domain;
}

/*!
 * \qmlproperty string i18n::language
 * The language that is used for the translation. The default value is
 * the user's locale dending on $LC_ALL, $LC_MESSAGES and $LANG at the time
 * of running the application. See the gettext manual for details.
 */
QString LomiriI18n::language() const {
    return m_language;
}

/**
 * \qmlmethod void i18n::bindtextdomain(string domain_name, string dir_name)
 * Specify that the domain_name message catalog can be found
 * in dir_name rather than in the system locale data base.
 */
void LomiriI18n::bindtextdomain(const QString& domain_name, const QString& dir_name) {
    C::bindtextdomain(domain_name.toUtf8(), dir_name.toUtf8());
    Q_EMIT domainChanged();
}

void LomiriI18n::setDomain(const QString &domain) {
    if (m_domain == domain)
        return;

    m_domain = domain;
    C::textdomain(domain.toUtf8());
    /*
     The default is /usr/share/locale if we don't set a folder
     For click we use APP_DIR/share/locale
     e.g. /usr/share/click/preinstalled/com.example.foo/current/share/locale
     */
    QString appDir = QString::fromLocal8Bit(getenv("APP_DIR"));
    if (!QDir::isAbsolutePath (appDir)) {
        appDir = QStringLiteral("/usr");
    }
    QString localePath(QDir(appDir).filePath(QStringLiteral("share/locale")));
    C::bindtextdomain(domain.toUtf8(), localePath.toUtf8());
    Q_EMIT domainChanged();
}

void LomiriI18n::setLanguage(const QString &lang) {
    if (m_language == lang)
        return;

    m_language = lang;

    /*
     This is needed for LP: #1263163.

     LANGUAGE may be set to one or more languages for example "fi" or
     "sv:de". gettext prioritizes LANGUAGE over LC_ALL, LC_*, and
     LANG, so if the session has already set LANGUAGE, calls to
     gettext will only use that.  We must override it here so that
     future calls to gettext are done in the new language.

     This only affects the current process. It does not override the
     user's session LANGUAGE.
     */
    setenv("LANGUAGE", lang.toUtf8().constData(), 1);

    /*
     The inverse form of setlocale as used in the constructor, passing
     a valid locale string updates all category type defaults.
     */
    setlocale(LC_ALL, lang.toUtf8());
    Q_EMIT languageChanged();
}

/*!
 * \qmlmethod string i18n::tr(string text)
 * Translate \a text using gettext and return the translation.
 */
QString LomiriI18n::tr(const QString& text)
{
    return QString::fromUtf8(C::gettext(text.toUtf8()));
}

/*!
 * \qmlmethod string i18n::tr(string singular, string plural, int n)
 * Translate the given input string \a singular or \a plural (depending on the number of items \a n)
 * using gettext.
 * Note that tr() does not automatically insert the values in the QString,
 * so it should be called like this:
 *          tr("%1 file", "%1 files", count).arg(count)
 */
QString LomiriI18n::tr(const QString &singular, const QString &plural, int n)
{
    return QString::fromUtf8(C::ngettext(singular.toUtf8(), plural.toUtf8(), n));
}

/*!
 * \qmlmethod string i18n::dtr(string domain, string text)
 * Translate \a text using gettext. Uses the specified domain \a domain instead of i18n.domain.
 */
QString LomiriI18n::dtr(const QString& domain, const QString& text)
{
    if (domain.isNull()) {
        return QString::fromUtf8(C::dgettext(NULL, text.toUtf8()));
    } else {
        return QString::fromUtf8(C::dgettext(domain.toUtf8(), text.toUtf8()));
    }
}

/*!
 * \qmlmethod string i18n::dtr(string domain, string singular, string plural, int n)
 * Translate the given text using gettext. Should be called like this:
 *          tr(domain, "%1 file", "%1 files", count).arg(count)
 * Uses \a domain for the domain instead of i18n.domain, and \a singular or \a plural
 * as input for the translation depending on the number of items \a n.
 */
QString LomiriI18n::dtr(const QString& domain, const QString& singular, const QString& plural, int n)
{
    if (domain.isNull()) {
        return QString::fromUtf8(C::dngettext(NULL, singular.toUtf8(), plural.toUtf8(), n));
    } else {
        return QString::fromUtf8(C::dngettext(domain.toUtf8(), singular.toUtf8(), plural.toUtf8(), n));
    }
}

/*!
 * \qmlmethod string i18n::ctr(string context, string text)
 * Translate \a text using gettext and return the translation.
 * \a context is only visible to the translator and helps disambiguating for very short texts
 */
QString LomiriI18n::ctr(const QString& context, const QString& text)
{
    return dctr(QString(), context, text);
}

/*!
 * \qmlmethod string i18n::dctr(string domain, string context, string text)
 * Translate \a text using gettext. Uses the specified domain \a domain instead of i18n.domain.
 * \a context is only visible to the translator and helps disambiguating for very short texts
 */
QString LomiriI18n::dctr(const QString& domain, const QString& context, const QString& text)
{
    if (domain.isNull()) {
        return QString::fromUtf8(C::g_dpgettext2(NULL, context.toUtf8(), text.toUtf8()));
    } else {
        return QString::fromUtf8(C::g_dpgettext2(domain.toUtf8(), context.toUtf8(), text.toUtf8()));
    }
}

/*!
 * \qmlmethod string i18n::tag(string text)
 * Mark \a text for translation at a later point. Typically this allows an API
 * to take the original string and pass it to dtr (or dgettext).
 *
 * \qml
 * import QtQuick 2.4
 * import UserMetrics 0.1
 *
 * Metric {
 *     name: "distance"
 *     format: i18n.tag("Distance covered today: %1 km")
 *     emptyFormat: i18n.tag("No running today")
 *     domain: "runner.forest"
 * }
 * \endqml
 *
 * The strings tagged for localzation above are passed to the implementation
 * of UserMetrics verbatim, as well as the domain of the app. Display and
 * translation of the strings will happen in the lockscreen, where the same
 * strings will be passed to i18n.tr.
 */
QString LomiriI18n::tag(const QString& text)
{
    return text;
}

/*!
 * \qmlmethod string i18n::tag(string context, string text)
 * Mark \a text for translation at a later point. Typically this allows an API
 * to take the original string and pass it to dctr (or g_dpgettext2).
 * \a context is only visible to the translator and helps disambiguating for very short texts
 */
QString LomiriI18n::tag(const QString& context, const QString& text)
{
    Q_UNUSED(context);
    return text;
}
/*!
 * \qmlmethod string i18n::relativeDateTime(datetime dateTime)
 * Translate a datetime based on proximity to current time.
 */
QString LomiriI18n::relativeDateTime(const QDateTime& datetime)
{
    static const QString lomiriUiToolkit = QStringLiteral("lomiri-ui-toolkit");

    QDateTime relativeTo(QDateTime::currentDateTime());
    const date_proximity_t prox = getDateProximity(relativeTo, datetime);

    switch (prox)  {
        case DATE_PROXIMITY_NOW:
            /* TRANSLATORS: Time based "this is happening/happened now" */
            return dtr(lomiriUiToolkit, QStringLiteral("Now"));

        case DATE_PROXIMITY_HOUR:
        {
            qint64 diff = datetime.toMSecsSinceEpoch() - relativeTo.toMSecsSinceEpoch();
            qint64 minutes = qRound(float(diff) / 60000);
            if (minutes < 0) {
                return dtr(lomiriUiToolkit, QStringLiteral("%1 minute ago"),
                           QStringLiteral("%1 minutes ago"), qAbs(minutes)).arg(qAbs(minutes));
            }
            return dtr(lomiriUiToolkit, QStringLiteral("%1 minute"),
                       QStringLiteral("%1 minutes"), minutes).arg(minutes);
        }

        case DATE_PROXIMITY_TODAY:
            /* en_US example: "1:00 PM" */
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
            return datetime.toString(isLocale12h()
                ? dtr(lomiriUiToolkit, QStringLiteral("h:mm ap"))
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
                : dtr(lomiriUiToolkit, QStringLiteral("HH:mm")));

        case DATE_PROXIMITY_YESTERDAY:
            /* en_US example: "Yesterday  13:00" */
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
            return datetime.toString(isLocale12h()
                ? dtr(lomiriUiToolkit, QStringLiteral("'Yesterday\u2003'h:mm ap"))
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
                : dtr(lomiriUiToolkit, QStringLiteral("'Yesterday\u2003'HH:mm")));

        case DATE_PROXIMITY_TOMORROW:
            /* en_US example: "Tomorrow  1:00 PM" */
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
            return datetime.toString(isLocale12h()
                ? dtr(lomiriUiToolkit, QStringLiteral("'Tomorrow\u2003'h:mm ap"))
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
                : dtr(lomiriUiToolkit, QStringLiteral("'Tomorrow\u2003'HH:mm")));

        case DATE_PROXIMITY_LAST_WEEK:
        case DATE_PROXIMITY_NEXT_WEEK:
            /* en_US example: "Fri  1:00 PM" */
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
            return datetime.toString(isLocale12h()
                ? dtr(lomiriUiToolkit, QStringLiteral("ddd'\u2003'h:mm ap"))
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
                : dtr(lomiriUiToolkit, QStringLiteral("ddd'\u2003'HH:mm")));

        case DATE_PROXIMITY_FAR_BACK:
        case DATE_PROXIMITY_FAR_FORWARD:
        default:
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
            return datetime.toString(isLocale12h()
                ? dtr(lomiriUiToolkit, QStringLiteral("ddd d MMM'\u2003'h:mm ap"))
            /* TRANSLATORS: Please translate these to your locale datetime
               format using the format specified by
               https://qt-project.org/doc/qt-5-snapshot/qdatetime.html#fromString-2 */
                : dtr(lomiriUiToolkit, QStringLiteral("ddd d MMM'\u2003'HH:mm")));
    }
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
    return datetime.toString(Qt::DefaultLocaleShortDate);
#else
    return datetime.toString(QLocale().dateFormat(QLocale::ShortFormat));
#endif
}

UT_NAMESPACE_END