Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qtimezonelocale.cpp
Go to the documentation of this file.
1// Copyright (C) 2024 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5#include <private/qtimezonelocale_p.h>
6#include <private/qtimezoneprivate_p.h>
7
8#if !QT_CONFIG(icu)
9# include <QtCore/qspan.h>
10# include <private/qdatetime_p.h>
11# include <private/qtools_p.h>
12// Use data generated from CLDR:
13# include "qtimezonelocale_data_p.h"
14# include "qtimezoneprivate_data_p.h"
15# ifdef QT_CLDR_ZONE_DEBUG
16# include "../text/qlocale_data_p.h"
17QT_BEGIN_NAMESPACE
18static_assert(std::size(locale_data) == std::size(QtTimeZoneLocale::localeZoneData));
19// Size includes terminal rows: for now, they do match in tag IDs, but they needn't.
20static_assert([]() {
21 for (std::size_t i = 0; i < std::size(locale_data); ++i) {
22 const auto &loc = locale_data[i];
23 const auto &zone = QtTimeZoneLocale::localeZoneData[i];
24 if (loc.m_language_id != zone.m_language_id
25 || loc.m_script_id != zone.m_script_id
26 || loc.m_territory_id != zone.m_territory_id) {
27 return false;
28 }
29 }
30 return true;
31}());
32QT_END_NAMESPACE
33# endif
34#endif
35
36#include <algorithm>
37
38QT_BEGIN_NAMESPACE
39
40using namespace Qt::StringLiterals;
41
42#if QT_CONFIG(icu) // Get data from ICU:
43namespace {
44
45// Convert TimeType and NameType into ICU UCalendarDisplayNameType
46UCalendarDisplayNameType ucalDisplayNameType(QTimeZone::TimeType timeType,
47 QTimeZone::NameType nameType)
48{
49 // TODO ICU C UCalendarDisplayNameType does not support full set of C++ TimeZone::EDisplayType
50 // For now, treat Generic as Standard
51 switch (nameType) {
52 case QTimeZone::ShortName:
53 return timeType == QTimeZone::DaylightTime ? UCAL_SHORT_DST : UCAL_SHORT_STANDARD;
54 case QTimeZone::DefaultName:
55 case QTimeZone::LongName:
56 return timeType == QTimeZone::DaylightTime ? UCAL_DST : UCAL_STANDARD;
57 case QTimeZone::OffsetName:
58 Q_UNREACHABLE(); // Callers of ucalTimeZoneDisplayName() should take care of OffsetName.
59 }
60 Q_UNREACHABLE_RETURN(UCAL_STANDARD);
61}
62
63} // nameless namespace
64
65namespace QtTimeZoneLocale {
66
67// Qt wrapper around ucal_getTimeZoneDisplayName()
68// Used directly by ICU backend; indirectly by TZ (see below).
69QString ucalTimeZoneDisplayName(UCalendar *ucal,
70 QTimeZone::TimeType timeType,
71 QTimeZone::NameType nameType,
72 const QByteArray &localeCode)
73{
74 constexpr int32_t BigNameLength = 50;
75 int32_t size = BigNameLength;
76 QString result(size, Qt::Uninitialized);
77 auto dst = [&result]() { return reinterpret_cast<UChar *>(result.data()); };
78 UErrorCode status = U_ZERO_ERROR;
79 const UCalendarDisplayNameType utype = ucalDisplayNameType(timeType, nameType);
80
81 // size = ucal_getTimeZoneDisplayName(cal, type, locale, result, resultLength, status)
82 size = ucal_getTimeZoneDisplayName(ucal, utype, localeCode.constData(),
83 dst(), size, &status);
84
85 // If overflow, then resize and retry
86 if (size > BigNameLength || status == U_BUFFER_OVERFLOW_ERROR) {
87 result.resize(size);
88 status = U_ZERO_ERROR;
89 size = ucal_getTimeZoneDisplayName(ucal, utype, localeCode.constData(),
90 dst(), size, &status);
91 }
92
93 if (!U_SUCCESS(status))
94 return QString();
95
96 // Resize and return:
97 result.resize(size);
98 return result;
99}
100
101bool ucalKnownTimeZoneId(const QString &ianaStr)
102{
103 const UChar *const name = reinterpret_cast<const UChar *>(ianaStr.constData());
104 // We are not interested in the value, but we have to pass something.
105 // No known IANA zone name is (up to 2023) longer than 30 characters.
106 constexpr size_t size = 64;
107 UChar buffer[size];
108
109 // TODO: convert to ucal_getIanaTimeZoneID(), new draft in ICU 74, once we
110 // can rely on its availability, assuming it works the same once not draft.
111 UErrorCode status = U_ZERO_ERROR;
112 UBool isSys = false;
113 // Returns the length of the IANA zone name (but we don't care):
114 ucal_getCanonicalTimeZoneID(name, ianaStr.size(), buffer, size, &isSys, &status);
115 // We're only interested if the result is a "system" (i.e. IANA) ID:
116 return isSys;
117}
118
119} // QtTimeZoneLocale
120
121// Used by TZ backends when ICU is available:
122QString QTimeZonePrivate::localeName(qint64 atMSecsSinceEpoch, int offsetFromUtc,
123 QTimeZone::TimeType timeType,
124 QTimeZone::NameType nameType,
125 const QLocale &locale) const
126{
127 Q_UNUSED(atMSecsSinceEpoch);
128 // TODO: use CLDR data for the offset name.
129 // No ICU API for offset formats, so fall back to our ISO one, even if
130 // locale isn't C:
131 if (nameType == QTimeZone::OffsetName)
132 return isoOffsetFormat(offsetFromUtc);
133
134 const QString id = QString::fromUtf8(m_id);
135 // Need to check id is known to ICU, since ucal_open() will return a
136 // misleading "valid" GMT ucal when it doesn't recognise id.
137 if (!QtTimeZoneLocale::ucalKnownTimeZoneId(id))
138 return QString();
139
140 const QByteArray loc = locale.name().toUtf8();
141 UErrorCode status = U_ZERO_ERROR;
142 // TODO: QTBUG-124271 can we cache any of this ?
143 UCalendar *ucal = ucal_open(reinterpret_cast<const UChar *>(id.data()), id.size(),
144 loc.constData(), UCAL_DEFAULT, &status);
145 if (ucal && U_SUCCESS(status)) {
146 auto tidier = qScopeGuard([ucal]() { ucal_close(ucal); });
147 return QtTimeZoneLocale::ucalTimeZoneDisplayName(ucal, timeType, nameType, loc);
148 }
149 return QString();
150}
151#else // No ICU, use QTZ[LP]_data_p.h data for feature timezone_locale.
153// Inline methods promised in QTZL_p.h
154using namespace QtTimeZoneCldr; // QTZP_data_p.h
157} // QtTimeZoneLocale
158
159namespace {
160using namespace QtTimeZoneLocale; // QTZL_p.h QTZL_data_p.h
161using namespace QtTimeZoneCldr; // QTZP_data_p.h
162// Accessors for the QTZL_data_p.h
163
164template <typename Row, typename Sought, typename Condition>
165const Row *findTableEntryFor(const QSpan<Row> data, Sought value, Condition test)
166{
167 // We have the present locale's data (if any). Its rows are sorted on
168 // (localeIndex and) a field for which we want the Sought value. The test()
169 // compares that field.
170 auto begin = data.begin(), end = data.end();
171 Q_ASSERT(begin == end || end->localeIndex > begin->localeIndex);
172 Q_ASSERT(begin == end || end[-1].localeIndex == begin->localeIndex);
173 auto row = std::lower_bound(begin, end, value, test);
174 return row == end ? nullptr : row;
175}
176
177QString exemplarCityFor(const LocaleZoneData &locale, const LocaleZoneData &next,
178 QByteArrayView iana)
179{
180 auto xct = findTableEntryFor(
181 QSpan(localeZoneExemplarTable).first(next.m_exemplarTableStart
182 ).sliced(locale.m_exemplarTableStart),
183 iana, [](auto &row, QByteArrayView key) { return row.ianaId() < key; });
184 if (xct && xct->ianaId() == iana)
185 return xct->exemplarCity().getData(exemplarCityTable);
186 return {};
187}
188
189// Accessors for the QTZP_data_p.h
190quint32 clipEpochMinute(qint64 epochMinute)
191{
192 // ZoneMetaHistory's quint32 UTC epoch minutes.
193 // Dates from 1970-01-01 to 10136-02-16 (at 04:14) are representable.
194 constexpr quint32 epoch = 0;
195 // Since the .end value of an interval that does end is the first epoch
196 // minutes *after* the interval, intervalEndsBefore() uses a <= test. The
197 // value ~epoch (0xffffffff) is used as a sentinel value to mean "there is
198 // no end", so we need a value strictly less than it for "epoch minutes too
199 // big to represent" so that this value is less than "no end". So the value
200 // 1 ^ ~epoch (0xfffffffe) is reserved as this "unrepresentably late time"
201 // and the scripts to generate data assert that no actual interval ends then
202 // or later.
203 constexpr quint32 ragnarok = 1 ^ ~epoch;
204 return epochMinute + 1 >= ragnarok ? ragnarok : quint32(epochMinute);
205}
206
207constexpr bool intervalEndsBefore(const ZoneMetaHistory &record, quint32 dt) noexcept
208{
209 // See clipEpochMinute()'s explanation of ragnarok for why this is <=
210 return record.end <= dt;
211}
212
213/* The metaZoneKey of the ZoneMetaHistory entry whose ianaId() is equal to the
214 given zoneId, for which atMSecsSinceEpoch refers to an instant between its
215 begin and end. Returns zero if there is no such ZoneMetaHistory entry.
216*/
217quint16 metaZoneAt(QByteArrayView zoneId, qint64 atMSecsSinceEpoch)
218{
219 using namespace QtPrivate::DateTimeConstants;
220 auto it = std::lower_bound(std::begin(zoneHistoryTable), std::end(zoneHistoryTable), zoneId,
221 [](const ZoneMetaHistory &record, QByteArrayView id) {
222 return record.ianaId().compare(id, Qt::CaseInsensitive) < 0;
223 });
224 if (it == std::end(zoneHistoryTable) || it->ianaId().compare(zoneId, Qt::CaseInsensitive) > 0)
225 return 0;
226 const auto stop =
227 std::upper_bound(it, std::end(zoneHistoryTable), zoneId,
228 [](QByteArrayView id, const ZoneMetaHistory &record) {
229 return id.compare(record.ianaId(), Qt::CaseInsensitive) < 0;
230 });
231 const quint32 dt = clipEpochMinute(atMSecsSinceEpoch / MSECS_PER_MIN);
232 it = std::lower_bound(it, stop, dt, intervalEndsBefore);
233 return it != stop && it->begin <= dt ? it->metaZoneKey : 0;
234}
235
236// True if the named zone is ever part of the specified metazone:
237bool zoneEverInMeta(QByteArrayView zoneId, quint16 metaKey)
238{
239 for (auto it = std::lower_bound(std::begin(zoneHistoryTable), std::end(zoneHistoryTable),
240 zoneId,
241 [](const ZoneMetaHistory &record, QByteArrayView id) {
242 return record.ianaId().compare(id, Qt::CaseInsensitive) < 0;
243 });
244 it != std::end(zoneHistoryTable) && it->ianaId().compare(zoneId, Qt::CaseInsensitive) == 0;
245 ++it) {
246 if (it->metaZoneKey == metaKey)
247 return true;
248 }
249 return false;
250}
251
252constexpr bool dataBeforeMeta(const MetaZoneData &row, quint16 metaKey) noexcept
253{
254 return row.metaZoneKey < metaKey;
255}
256
257constexpr bool metaDataBeforeTerritory(const MetaZoneData &row, qint16 territory) noexcept
258{
259 return row.territory < territory;
260}
261
262const MetaZoneData *metaZoneStart(quint16 metaKey)
263{
264 const MetaZoneData *const from =
265 std::lower_bound(std::begin(metaZoneTable), std::end(metaZoneTable),
266 metaKey, dataBeforeMeta);
267 if (from == std::end(metaZoneTable) || from->metaZoneKey != metaKey) {
268 qWarning("No metazone data found for metazone key %d", metaKey);
269 return nullptr;
270 }
271 return from;
272}
273
274const MetaZoneData *metaZoneDataFor(const MetaZoneData *from, QLocale::Territory territory)
275{
276 const quint16 metaKey = from->metaZoneKey;
277 const MetaZoneData *const end =
278 std::lower_bound(from, std::end(metaZoneTable), metaKey + 1, dataBeforeMeta);
279 Q_ASSERT(end != from && end[-1].metaZoneKey == metaKey);
280 QLocale::Territory land = territory;
281 do {
282 const MetaZoneData *row =
283 std::lower_bound(from, end, qint16(land), metaDataBeforeTerritory);
284 if (row != end && QLocale::Territory(row->territory) == land) {
285 Q_ASSERT(row->metaZoneKey == metaKey);
286 return row;
287 }
288 // Fall back to World (if territory itself isn't World).
289 } while (std::exchange(land, QLocale::World) != QLocale::World);
290
291 qWarning("Metazone %s lacks World data for %ls",
292 from->metaZoneId().constData(),
293 qUtf16Printable(QLocale::territoryToString(territory)));
294 return nullptr;
295}
296
297QString addPadded(qsizetype width, const QString &zero, const QString &number, QString &&onto)
298{
299 // TODO (QTBUG-122834): QLocale::toString() should support zero-padding directly.
300 width -= number.size() / zero.size();
301 while (width > 0) {
302 onto += zero;
303 --width;
304 }
305 return std::move(onto) + number;
306}
307
308QString formatOffset(QStringView format, int offsetMinutes, const QLocale &locale,
309 QtTemporalPattern::TemporalFieldFlags flags)
310{
311 using Flag = QtTemporalPattern::TemporalFieldFlag;
312 Q_ASSERT(offsetMinutes >= 0);
313 const QString hour = locale.toString(offsetMinutes / 60);
314 const QString mins = locale.toString(offsetMinutes % 60);
315 // If zero.size() > 1, digits are surrogate pairs; each only counts one
316 // towards width of the field, even if it contributes more to result.size().
317 const QString zero = locale.zeroDigit();
318 QStringView tail = format;
319 QString result;
320 while (!tail.isEmpty()) {
321 if (tail.startsWith(u'\'')) {
322 qsizetype end = tail.indexOf(u'\'', 1);
323 if (end < 0) {
324 qWarning("Unbalanced quote in offset format string: %s",
325 format.toUtf8().constData());
326 return result + tail; // Include the quote; format is bogus.
327 } else if (end == 1) {
328 // Special case: adjacent quotes signify a simple quote.
329 result += u'\'';
330 tail = tail.sliced(2);
331 } else {
332 Q_ASSERT(end > 1); // We searched from index 1.
333 while (end + 1 < tail.size() && tail[end + 1] == u'\'') {
334 // Special case: adjacent quotes inside a quoted string also
335 // signify a simple quote.
336 result += tail.sliced(1, end); // Include a quote at the end
337 tail = tail.sliced(end + 1); // Still starts with a quote
338 end = tail.indexOf(u'\'', 1); // Where's the next ?
339 if (end < 0) {
340 qWarning("Unbalanced quoted quote in offset format string: %s",
341 format.toUtf8().constData());
342 return result + tail;
343 }
344 Q_ASSERT(end > 0);
345 }
346 // Skip leading and trailng quotes:
347 result += tail.sliced(1, end - 1);
348 tail = tail.sliced(end + 1);
349 }
350 } else if (tail.startsWith(u'H')) {
351 qsizetype width = 1;
352 while (width < tail.size() && tail[width] == u'H')
353 ++width;
354 tail = tail.sliced(width);
355 if (flags.testFlag(Flag::ZeroPad))
356 result = addPadded(width, zero, hour, std::move(result));
357 else
358 result += hour;
359 } else if (tail.startsWith(u'm')) {
360 qsizetype width = 1;
361 while (width < tail.size() && tail[width] == u'm')
362 ++width;
363 // (At CLDR v45, all locales use two-digit minutes.)
364 // (No known zone has single-digit non-zero minutes.)
365 tail = tail.sliced(width);
366 if (flags.testFlag(Flag::ZeroPad))
367 result = addPadded(width, zero, mins, std::move(result));
368 else if (offsetMinutes % 60)
369 result += mins;
370 else if (result.endsWith(u':') || result.endsWith(u'.'))
371 result.chop(1);
372 // (At CLDR v45, mm follows H either immediately or after a colon or dot.)
373 } else if (tail[0].isHighSurrogate() && tail.size() > 1
374 && tail[1].isLowSurrogate()) {
375 result += tail.first(2);
376 tail = tail.sliced(2);
377 } else {
378 result += tail.front();
379 tail = tail.sliced(1);
380 }
381 }
382 return result;
383}
384
385struct OffsetFormatMatch
386{
387 qsizetype size = 0;
388 int offset = 0;
389 operator bool() const { return size > 0; }
390};
391
392OffsetFormatMatch matchOffsetText(QStringView text, QStringView format, const QLocale &locale,
393 QtTemporalPattern::TemporalFieldFlags flags)
394{
395 using namespace QtTemporalPattern;
396 using namespace FieldGroup;
397 using Flag = TemporalFieldFlag;
398 const bool zeroPad = flags.testFlag(Flag::ZeroPad);
399 OffsetFormatMatch res;
400
401 // At least at CLDR v48:
402 // Amharic in Ethiopia has ±HHmm formats; all others use separators.
403 // None have single m. All have H or HH before mm. None has anything after mm.
404 // (If a user has configured a system locale to violate that, they get to
405 // endure the resulting failure to parse.)
406 // Some Balkan states have a space before the minus sign of the negative format.
407 // Sign is taken care of by caller; it's part of the format's text, before
408 // H, but here we just match it as a literal.
409 // TODO: flexible matching of space, when present in format; ignoring Unicode
410 // invisibles; matching variations on U+2212, dash and other forms of minus sign.
411
412 qsizetype cut = format.indexOf(u'H');
413 if (cut < 0 || !text.startsWith(format.first(cut)) || !format.endsWith(u"mm"))
414 return res;
415 QStringView sep = format.sliced(cut).chopped(2); // Prune prefix and "mm".
416 int hlen = 1; // We already know we have one 'H' at the start of sep.
417 while (hlen < sep.size() && sep[hlen] == u'H')
418 ++hlen;
419 Q_ASSERT(hlen <= 2);
420 sep = sep.sliced(hlen);
421
422 const QLocaleData *const locDat = QLocalePrivate::get(locale)->m_data;
423 using Digits = QLocaleData::DigitSequence;
424 // We can be interested in no more than four digits, two per field.
425 const Digits early = locDat->digitSequence(text, {}, cut, 4);
426 Q_ASSERT(!early.sign);
427
428 Digits hrs = early;
429 if (qsizetype maxLen = std::max(2, hlen); maxLen < hrs.digits.size())
430 hrs = hrs.first(maxLen);
431 if (hrs.digits.size() < 1) // There must be an hour field.
432 return res;
433 if (zeroPad && hrs.digits.size() < hlen) // ZeroPad requires full width
434 return res;
435
436 Digits mins = early.sliced(hrs.digits.size()); // Initial guess.
437 if (!sep.isEmpty()) {
438 const qsizetype sepAt = text.indexOf(sep, cut);
439 if (sepAt == hrs.endIndex()) // Separator must immediately follow hour field:
440 mins = locDat->digitSequence(text, {}, sepAt + sep.size(), 2);
441 else // If missing or misplaced, we only have an hour field:
442 mins = mins.first(0);
443 }
444 Q_ASSERT(!mins.sign);
445 if (mins.digits.size() > 2)
446 mins = mins.first(2);
447 else if (!mins.isEmpty() && mins.digits.size() < 2) // Not long enough: ignore
448 mins = mins.first(0);
449
450 constexpr int MaxOffsetHours
451 = (std::max)(-QTimeZone::MinUtcOffsetSecs, QTimeZone::MaxUtcOffsetSecs) / 3600;
452
453 bool ok = true;
454 uint hour = hrs.digits.toUInt(&ok);
455 if (!ok || hour > MaxOffsetHours || (zeroPad && mins.isEmpty())) {
456 // MaxOffsetHours > 10, so hrs.digits().size() > 1.
457 if (zeroPad) // Hour field must have full width.
458 return res;
459 // Truncated hour field at first digit and exclude minutes:
460 hrs = hrs.first(1);
461 mins = mins.first(0);
462 hour = hrs.digits.toUInt(&ok);
463 }
464 if (ok) {
465 if (!mins.isEmpty()
466 && (!zeroPad || matchesFlagWithin(flags, Flag::Abbreviated, WidthMask))) {
467 uint minute = mins.digits.toUInt(&ok);
468 if (ok && minute < 60) {
469 res.offset = (hour * 60 + minute) * 60;
470 res.size = mins.endIndex();
471 return res;
472 }
473 }
474 if (!zeroPad || matchesFlagWithin(flags, Flag::Narrow, WidthMask)) {
475 res.offset = hour * 60 * 60;
476 res.size = hrs.endIndex();
477 }
478 }
479 return res;
480}
481
482OffsetFormatMatch matchOffsetFormat(QStringView text, const QLocale &locale, qsizetype locInd,
483 QtTemporalPattern::TemporalFieldFlags flags)
484{
485 OffsetFormatMatch best;
486 using Flag = QtTemporalPattern::TemporalFieldFlag;
487 using namespace QtTemporalPattern::FieldGroup;
488 const LocaleZoneData &locData = localeZoneData[locInd];
489 const QStringView posHourForm = locData.posHourFormat().viewData(hourFormatTable);
490 const QStringView negHourForm = locData.negHourFormat().viewData(hourFormatTable);
491 // For the negative format, allow U+002d to match U+2212 or locale.negativeSign();
492 const bool mapNeg = text.contains(u'-')
493 && (negHourForm.contains(u'\u2212') || negHourForm.contains(locale.negativeSign()));
494 if (QtTemporalPattern::matchesFlagWithin(flags, Flag::NeedNoUtcPrefix, UtcPrefixMask)) {
495 if (auto match = matchOffsetText(text, posHourForm, locale, flags))
496 best = match;
497 if (auto match = matchOffsetText(text, negHourForm, locale, flags); match.size > best.size)
498 best = { match.size, -match.offset };
499 if (mapNeg) {
500 const QString mapped = negHourForm.toString()
501 .replace(u'\u2212', u'-').replace(locale.negativeSign(), "-"_L1);
502 if (auto match = matchOffsetText(text, mapped, locale, flags); match.size > best.size)
503 best = { match.size, -match.offset };
504 }
505 }
506 if (QtTemporalPattern::matchesFlagWithin(flags, Flag::AcceptUtcPrefix, UtcPrefixMask)) {
507 const QStringView offsetFormat = locData.offsetGmtFormat().viewData(gmtFormatTable);
508 if (const qsizetype cut = offsetFormat.indexOf(u"%0"); cut >= 0) { // Should be present
509 const QStringView gmtPrefix = offsetFormat.first(cut);
510 const QStringView gmtSuffix = offsetFormat.sliced(cut + 2); // After %0
511 const qsizetype gmtSize = cut + gmtSuffix.size();
512 const auto crossMatch = [gmtPrefix, text]
513 (QLatin1StringView lhs, QLatin1StringView rhs) {
514 const qsizetype len = lhs.size();
515 Q_ASSERT(len == rhs.size());
516 if (!gmtPrefix.startsWith(lhs) || !text.startsWith(rhs))
517 return false;
518 if (gmtPrefix.size() == len)
519 return true;
520 return text.sliced(len).startsWith(gmtPrefix.sliced(len));
521 };
522 // Cheap pre-test: check suffix does appear after prefix, albeit we must
523 // later check it actually appears right after the offset text:
524 if ((gmtPrefix.isEmpty() || text.startsWith(gmtPrefix)
525 // Treat GMT and UTC as matches for one another to match
526 // QUtcTimeZonePrivate::displayName()'s kludges:
527 || crossMatch("GMT"_L1, "UTC"_L1) || crossMatch("UTC"_L1, "GMT"_L1))
528 && (gmtSuffix.isEmpty() || text.sliced(cut).indexOf(gmtSuffix) >= 0)) {
529 if (auto match = matchOffsetText(text.sliced(cut), posHourForm, locale, flags);
530 gmtSize + match.size > best.size) {
531 if (text.sliced(cut + match.size).startsWith(gmtSuffix)) // too sliced ?
532 best = { gmtSize + match.size, match.offset };
533 }
534 if (auto match = matchOffsetText(text.sliced(cut), negHourForm, locale, flags)) {
535 if (gmtSize + match.size > best.size
536 && text.sliced(cut + match.size).startsWith(gmtSuffix)) {
537 best = { gmtSize + match.size, -match.offset };
538 }
539 } else if (mapNeg) {
540 const QString mapped = negHourForm.toString()
541 .replace(u'\u2212', u'-').replace(locale.negativeSign(), "-"_L1);
542 if (auto match = matchOffsetText(text.sliced(cut), mapped, locale, flags);
543 gmtSize + match.size > best.size) {
544 if (text.sliced(cut + match.size).startsWith(gmtSuffix))
545 best = { gmtSize + match.size, -match.offset };
546 }
547 }
548 // Match empty offset as UTC (unless that'd be an empty match):
549 if (gmtSize > best.size && text.sliced(cut).startsWith(gmtSuffix))
550 return { gmtSize, 0 };
551 }
552 }
553 }
554 return best;
555}
556
557} // nameless namespace
558
559namespace QtTimeZoneLocale {
560
561QList<QByteArrayView> ianaIdsForTerritory(QLocale::Territory territory)
562{
563 QList<QByteArrayView> result;
564 {
565 const TerritoryZone *row =
566 std::lower_bound(std::begin(territoryZoneMap), std::end(territoryZoneMap),
567 qint16(territory),
568 [](const TerritoryZone &row, qint16 territory) {
569 return row.territory < territory;
570 });
571 if (row != std::end(territoryZoneMap) && QLocale::Territory(row->territory) == territory)
572 result << row->ianaId();
573 }
574 for (const MetaZoneData &row : metaZoneTable) {
575 if (QLocale::Territory(row.territory) == territory)
576 result << row.ianaId();
577 }
578 return result;
579}
580
581#if QT_CONFIG(datestring)
582// The QDateTime is only needed by the fall-back implementation in qlocale.cpp;
583// the calls below don't need to pass a valid QDateTime (based on its
584// atMSecsSinceEpoch); an invalid QDateTime() will suffice and be ignored.
587 const QDateTime &, int offsetSeconds)
588{
589 // See the final "zone" section of the table
590 // https://www.unicode.org/reports/tr35/tr35-dates.html#table-date-field-symbol-table
591 // for the full range of LDML-specified formats.
594 using namespace QtTemporalPattern::FieldGroup;
595
599 // Sign is already handled by choice of the hourFormat:
601 // Offsets are only displayed in minutes - round seconds (if any) to nearest
602 // minute (rounding halves away from zero offset):
603 const int offsetMinutes = (offsetSeconds + 30) / 60;
604
607 return hourOffset;
608
612}
613#endif // datestring
614
615} // QtTimeZoneLocale
616
617QString QTimeZonePrivate::localeName(qint64 atMSecsSinceEpoch, int offsetFromUtc,
618 QTimeZone::TimeType timeType,
619 QTimeZone::NameType nameType,
620 const QLocale &locale) const
621{
622#if QT_CONFIG(datestring)
623 if (nameType == QTimeZone::OffsetName
624 // Use offset forms for QUtcTimeZonePrivate instances:
625 || QUtcTimeZonePrivate::offsetFromUtcString(m_id) != invalidSeconds()) {
626 using Flag = QtTemporalPattern::TemporalFieldFlag;
627 constexpr QtTemporalPattern::TemporalFieldFlags flags
628 = Flag::Numeric | Flag::Abbreviated | Flag::AcceptUtcPrefix | Flag::ZeroPad;
629 // Doesn't need fallbacks, since every locale has hour and offset formats.
630 return QtTimeZoneLocale::zoneOffsetFormat(locale, locale.d->m_index, flags,
631 QDateTime(), offsetFromUtc);
632 }
633#endif // datestring
634 // Handling of long names must stay in sync with findLongNamePrefix(), below.
635
636 // An IANA ID may give clues to fall back on for abbreviation or exemplar city:
637 QByteArray ianaAbbrev, ianaTail;
638 const auto scanIana = [&](QByteArrayView iana) {
639 // Scan the name of each zone whose data we consider using and, if the
640 // name gives us a clue to a fallback for which we have nothing better
641 // yet, remember it (and ignore later clues for that fallback).
642 if (!ianaAbbrev.isEmpty() && !ianaTail.isEmpty())
643 return;
644 qsizetype cut = iana.lastIndexOf('/');
645 QByteArrayView tail = cut < 0 ? iana : iana.sliced(cut + 1);
646 // Deal with a couple of special cases
647 if (tail == "McMurdo") { // Exceptional lowercase-uppercase sequence without space
648 if (ianaTail.isEmpty())
649 ianaTail = "McMurdo"_ba;
650 return;
651 } else if (tail == "DumontDUrville") { // Chopped to fit into IANA's 14-char limit
652 if (ianaTail.isEmpty())
653 ianaTail = "Dumont d'Urville"_ba;
654 return;
655 } else if (tail.isEmpty()) {
656 // Custom zone with perverse m_id ?
657 return;
658 }
659 const auto isMixedCaseAbbrev = [tail](char ch) {
660 // cv-RU and en-GU abbreviate Chamorro as ChST
661 // scn-IT abbreviates Cuba as CuT/CuST/CuDT
662 // blo-BJ abbreviates GMT as Gk
663 switch (tail.size()) {
664 case 2: return tail == "Gk";
665 case 3: return tail == "CuT";
666 case 4:
667 if (tail[0] == 'C' && tail[1] == ch && tail[3] == 'T') {
668 switch (ch) {
669 case 'h': return tail[2] == 'S';
670 case 'u': return tail[2] == 'S' || tail[2] == 'D';
671 default: break;
672 }
673 }
674 return false;
675 default:
676 break;
677 }
678 return false;
679 };
680
681 // Even if it is abbr or city name, we don't care if we've found one before.
682 bool maybeAbbr = ianaAbbrev.isEmpty(), maybeCityName = ianaTail.isEmpty(), inword = false;
683 char sign = '\0';
684 for (char ch : tail) {
685 if (ch == '+' || ch == '-') {
686 if (ch == '+' || !inword)
687 maybeCityName = false;
688 inword = false;
689 if (maybeAbbr) {
690 if (sign)
691 maybeAbbr = false; // two signs: no
692 else
693 sign = ch;
694 }
695 } else if (ch == '_') {
696 maybeAbbr = false;
697 if (!inword) // No double-underscore, or leading underscore
698 maybeCityName = false;
699 inword = false;
700 } else if (QChar::isLower(ch)) {
701 maybeAbbr = isMixedCaseAbbrev(ch);
702 // Dar_es_Salaam shows both cases as word starts
703 inword = true;
704 } else if (QChar::isUpper(ch)) {
705 if (sign)
706 maybeAbbr = false;
707 if (inword)
708 maybeCityName = false;
709 inword = true;
710 } else if (QChar::isDigit(ch)) {
711 if (!sign)
712 maybeAbbr = false;
713 maybeCityName = false;
714 inword = false;
715 }
716
717 if (!maybeAbbr && !maybeCityName)
718 break;
719 }
720 if (maybeAbbr && maybeCityName) // No real IANA ID matches both
721 return;
722
723 if (maybeAbbr) {
724 if (tail.endsWith("-0") || tail.endsWith("+0"))
725 tail = tail.chopped(2);
726 ianaAbbrev = tail.toByteArray();
727 if (sign && iana.startsWith("Etc/")) { // Reverse convention for offsets
728 if (sign == '-')
729 ianaAbbrev = ianaAbbrev.replace('-', '+');
730 else if (sign == '+')
731 ianaAbbrev = ianaAbbrev.replace('+', '-');
732 }
733 }
734 // See https://www.unicode.org/reports/tr35/tr35-dates.html#Time_Zone_Goals
735 // under "Composition", point 3:
736 if (maybeCityName)
737 ianaTail = tail.toByteArray().replace('_', ' ');
738 }; // end scanIana
739
740 scanIana(m_id);
741 if (QByteArrayView iana = aliasToIana(m_id); !iana.isEmpty() && iana != m_id)
742 scanIana(iana);
743
744 // Requires locData, nextData set suitably - save repetition of member:
745#define tableLookup(table, member, sought, test)
746 findTableEntryFor(QSpan(table).first(nextData.member).sliced(locData.member), sought, test)
747 // Note: any commas in test need to be within parentheses; but the only
748 // comma a comparison should need is in its (parenthesised) parameter list.
749
750 const QList<qsizetype> indices = fallbackLocalesFor(locale.d->m_index);
751 QString exemplarCity; // In case we need it.
752 const auto metaIdBefore = [](auto &row, quint16 key) { return row.metaIdIndex < key; };
753
754 // First try for an actual name:
755 for (const qsizetype locInd : indices) {
756 const LocaleZoneData &locData = localeZoneData[locInd];
757 // After the row for the last actual locale, there's a terminal row:
758 Q_ASSERT(std::size_t(locInd) < std::size(localeZoneData) - 1);
759 const LocaleZoneData &nextData = localeZoneData[locInd + 1];
760
761 QByteArrayView iana{m_id};
762 if (quint16 metaKey = metaZoneAt(iana, atMSecsSinceEpoch)) {
763 if (const MetaZoneData *metaFrom = metaZoneStart(metaKey)) {
764 quint16 metaIdIndex = metaFrom->metaIdIndex;
765 QLocaleData::DataRange range{0, 0};
766 const char16_t *strings = nullptr;
767 if (nameType == QTimeZone::ShortName) {
768 auto row = tableLookup(localeMetaZoneShortNameTable, m_metaShortTableStart,
769 metaIdIndex, metaIdBefore);
770 if (row && row->metaIdIndex == metaIdIndex) {
771 range = row->shortName(timeType);
772 strings = shortMetaZoneNameTable;
773 }
774 } else { // LongName or DefaultName
775 auto row = tableLookup(localeMetaZoneLongNameTable, m_metaLongTableStart,
776 metaIdIndex, metaIdBefore);
777 if (row && row->metaIdIndex == metaIdIndex) {
778 range = row->longName(timeType);
779 strings = longMetaZoneNameTable;
780 }
781 }
782 Q_ASSERT(strings || !range.size);
783
784 if (range.size)
785 return range.getData(strings);
786
787 if (const auto *metaRow = metaZoneDataFor(metaFrom, locale.territory()))
788 iana = metaRow->ianaId(); // Use IANA ID of zone in use at that time
789 }
790 }
791
792 // Use exemplar city from closest match to locale, m_id:
793 if (exemplarCity.isEmpty()) {
794 exemplarCity = exemplarCityFor(locData, nextData, m_id);
795 if (exemplarCity.isEmpty())
796 exemplarCity = exemplarCityFor(locData, nextData, iana);
797 }
798 if (iana != m_id) // Check for hints to abbreviation and exemplar city:
799 scanIana(iana);
800
801 // That may give us a revised IANA ID; if the first search fails, fall back
802 // to m_id, if different.
803 do {
804 auto row = tableLookup(
805 localeZoneNameTable, m_zoneTableStart,
806 iana, [](auto &row, QByteArrayView key) { return row.ianaId() < key; });
807 if (row && row->ianaId() == iana) {
808 QLocaleData::DataRange range = row->name(nameType, timeType);
809 if (range.size) {
810 auto table = nameType == QTimeZone::ShortName
811 ? shortZoneNameTable
812 : longZoneNameTable;
813 return range.getData(table);
814 }
815 }
816 } while (std::exchange(iana, QByteArrayView{m_id}) != m_id);
817 }
818 // Most zones should now have ianaAbbrev or ianaTail set, maybe even both.
819 // We've now tried all the candidates we'll see for those.
820 // If an IANA ID's last component looked like a city name, use it.
821 if (exemplarCity.isEmpty() && !ianaTail.isEmpty())
822 exemplarCity = QString::fromLatin1(ianaTail); // It's ASCII
823
824 switch (nameType) {
825 case QTimeZone::DefaultName:
826 case QTimeZone::LongName:
827 for (const qsizetype locInd : indices) {
828 const LocaleZoneData &locData = localeZoneData[locInd];
829 QStringView regionFormat
830 = locData.regionFormatRange(timeType).viewData(regionFormatTable);
831 if (!regionFormat.isEmpty()) {
832 QString where = exemplarCity;
833 // TODO: if empty, use territory name
834 if (!where.isEmpty())
835 return regionFormat.arg(where);
836 }
837 }
838#if 0 // See comment within.
839 for (const qsizetype locInd : indices) {
840 const LocaleZoneData &locData = localeZoneData[locInd];
841 QStringView fallbackFormat = locData.fallbackFormat().viewData(fallbackFormatTable);
842 // Use fallbackFormat - probably never needed, as regionFormat is
843 // never empty, and this also needs city or territory name (along
844 // with metazone name).
845 }
846#endif
847 break;
848
849 case QTimeZone::ShortName:
850 // If an IANA ID's last component looked like an abbreviation (UTC, EST, ...) use it.
851 if (!ianaAbbrev.isEmpty())
852 return QString::fromLatin1(ianaAbbrev); // It's ASCII
853 break;
854
855 case QTimeZone::OffsetName:
856 Q_UNREACHABLE_RETURN(QString());
857 }
858
859#undef tableLookup
860
861 // Final fall-back: ICU seems to use a compact form of offset time for
862 // short-forms it doesn't know. This seems to correspond to the short form
863 // of LDML's Localized GMT format.
864#if QT_CONFIG(datestring)
865 using Flag = QtTemporalPattern::TemporalFieldFlag;
866 constexpr QtTemporalPattern::TemporalFieldFlags compact
867 = Flag::Numeric | Flag::Abbreviated | Flag::AcceptUtcPrefix;
868 return QtTimeZoneLocale::zoneOffsetFormat(locale, locale.d->m_index, compact,
869 QDateTime(), offsetFromUtc);
870#else
871 return {};
872#endif // datestring
873}
874
875// Match what the above might return at the start of a text (usually a tail of a
876// datetime string).
877QTimeZonePrivate::NamePrefixMatch
878QTimeZonePrivate::findLongNamePrefix(QStringView text, const QLocale &locale,
879 std::optional<qint64> atEpochMillis)
880{
881 constexpr std::size_t invalidMetaId = std::size(metaIdData);
882 constexpr std::size_t invalidIanaId = std::size(ianaIdData);
883 constexpr QTimeZone::TimeType timeTypes[] = {
884 // In preference order, should more than one match:
885 QTimeZone::GenericTime,
886 QTimeZone::StandardTime,
887 QTimeZone::DaylightTime,
888 };
889 struct {
890 qsizetype nameLength = 0;
891 QTimeZone::TimeType timeType = QTimeZone::GenericTime;
892 quint16 ianaIdIndex = invalidIanaId;
893 quint16 metaIdIndex = invalidMetaId;
894 QLocale::Territory where = QLocale::AnyTerritory;
895 } best;
896#define localeRows(table, member) QSpan(table).first(nextData.member).sliced(locData.member)
897
898 const QList<qsizetype> indices = fallbackLocalesFor(locale.d->m_index);
899 for (const qsizetype locInd : indices) {
900 const LocaleZoneData &locData = localeZoneData[locInd];
901 // After the row for the last actual locale, there's a terminal row:
902 Q_ASSERT(std::size_t(locInd) < std::size(localeZoneData) - 1);
903 const LocaleZoneData &nextData = localeZoneData[locInd + 1];
904
905 // TODO: support for FlexSpace, IgnoreCase and maybe others.
906 const auto metaRows = localeRows(localeMetaZoneLongNameTable, m_metaLongTableStart);
907 for (const LocaleMetaZoneLongNames &row : metaRows) {
908 for (const QTimeZone::TimeType type : timeTypes) {
909 QLocaleData::DataRange range = row.longName(type);
910 if (range.size > best.nameLength) {
911 QStringView name = range.viewData(longMetaZoneNameTable);
912 if (text.startsWith(name)) {
913 best = { static_cast<qsizetype>(range.size), type,
914 invalidIanaId, row.metaIdIndex };
915 if (best.nameLength >= text.size())
916 break;
917 }
918 }
919 }
920 if (best.nameLength >= text.size())
921 break;
922 }
923
924 const auto ianaRows = localeRows(localeZoneNameTable, m_zoneTableStart);
925 for (const LocaleZoneNames &row : ianaRows) {
926 for (const QTimeZone::TimeType type : timeTypes) {
927 QLocaleData::DataRange range = row.longName(type);
928 if (range.size > best.nameLength) {
929 QStringView name = range.viewData(longZoneNameTable);
930 // Save potentially expensive "zone is supported" check when possible:
931 bool gotZone = row.ianaIdIndex == best.ianaIdIndex
932 || QTimeZone::isTimeZoneIdAvailable(row.ianaId());
933 if (text.startsWith(name) && gotZone)
934 best = { static_cast<qsizetype>(range.size), type, row.ianaIdIndex };
935 }
936 }
937 }
938 }
939 // That's found us our best match, possibly as a meta-zone
940 if (best.metaIdIndex != invalidMetaId) {
941 const auto metaIdBefore = [](auto &row, quint16 key) { return row.metaIdIndex < key; };
942 // Find the standard IANA ID for this meta-zone (or one for another
943 // supported zone using the meta-zone at the specified time).
944 const MetaZoneData *metaRow =
945 std::lower_bound(std::begin(metaZoneTable), std::end(metaZoneTable),
946 best.metaIdIndex, metaIdBefore);
947 // Table is sorted by metazone, then territory.
948 for (; metaRow < std::end(metaZoneTable)
949 && metaRow->metaIdIndex == best.metaIdIndex; ++metaRow) {
950 auto metaLand = QLocale::Territory(metaRow->territory);
951 // World entry is the "standard" zone for this metazone, so always
952 // prefer it over any territory-specific one (from an earlier row):
953 if ((best.where == QLocale::AnyTerritory || metaLand == QLocale::World)
954 && (atEpochMillis
955 ? metaRow->metaZoneKey == metaZoneAt(metaRow->ianaId(), *atEpochMillis)
956 : zoneEverInMeta(metaRow->ianaId(), metaRow->metaZoneKey))) {
957 if (metaRow->ianaIdIndex == best.ianaIdIndex
958 || QTimeZone::isTimeZoneIdAvailable(metaRow->ianaId())) {
959 best.ianaIdIndex = metaRow->ianaIdIndex;
960 best.where = metaLand;
961 if (best.where == QLocale::World)
962 break;
963 }
964 }
965 }
966 }
967 if (best.ianaIdIndex != invalidIanaId)
968 return { QByteArray(ianaIdData + best.ianaIdIndex), best.nameLength, best.timeType };
969
970 // Now try for a region format.
971 // Since we may get the IANA ID directly from a zone, we may not need an
972 // ianaIdIndex from CLDR-derived tables: and the active backend may know
973 // some zones newer than our latest CLDR.
974 NamePrefixMatch found;
975 const QList<QByteArray> allZones = getCanonicalZonesThenAliases();
976 for (const qsizetype locInd : indices) {
977 const LocaleZoneData &locData = localeZoneData[locInd];
978 const LocaleZoneData &nextData = localeZoneData[locInd + 1];
979 for (const QTimeZone::TimeType timeType : timeTypes) {
980 QStringView regionFormat
981 = locData.regionFormatRange(timeType).viewData(regionFormatTable);
982 // "%0 [Season] Time", "Time in %0 [during Season]" &c.
983 const qsizetype cut = regionFormat.indexOf(u"%0");
984 if (cut < 0) // Shouldn't happen unless empty.
985 continue;
986
987 QStringView prefix = regionFormat.first(cut);
988 // Any text before %0 must appear verbatim at the start of our text:
989 if (cut > 0 && !text.startsWith(prefix))
990 continue;
991 QStringView suffix = regionFormat.sliced(cut + 2); // after %0
992 // This must start with an exemplar city or territory, followed by suffix:
993 QStringView tail = text.sliced(cut);
994
995 // Cheap pretest - any text after %0 must appear *somewhere* in our text:
996 if (suffix.size() && tail.indexOf(suffix) < 0)
997 continue; // No match possible
998
999 // Of course, particularly if just punctuation, a copy of our suffix
1000 // might appear within the city or territory name.
1001 const auto textMatches = [tail, suffix](QStringView where) {
1002 return (where.isEmpty() || tail.startsWith(where))
1003 && (suffix.isEmpty() || tail.sliced(where.size()).startsWith(suffix));
1004 };
1005
1006 const auto cityRows = localeRows(localeZoneExemplarTable, m_exemplarTableStart);
1007 for (const LocaleZoneExemplar &row : cityRows) {
1008 QStringView city = row.exemplarCity().viewData(exemplarCityTable);
1009 if (textMatches(city)) {
1010 qsizetype length = cut + city.size() + suffix.size();
1011 if (length > found.nameLength) {
1012 bool gotZone = row.ianaId() == found.ianaId // (cheap pre-test)
1013 || QTimeZone::isTimeZoneIdAvailable(row.ianaId());
1014 if (gotZone)
1015 found = { row.ianaId().toByteArray(), length, timeType };
1016 }
1017 }
1018 }
1019 // In localeName() we fall back to the last part of the IANA ID:
1020 for (const auto &iana : allZones) {
1021 Q_ASSERT(!iana.isEmpty());
1022 qsizetype slash = iana.lastIndexOf('/');
1023 QByteArray local = slash > 0 ? iana.sliced(slash + 1) : iana;
1024 QString city = QString::fromLatin1(local.replace('_', ' '));
1025 if (textMatches(city)) {
1026 qsizetype length = cut + city.size() + suffix.size();
1027 if (length > found.nameLength)
1028 found = { iana, length, timeType };
1029 }
1030 }
1031 // TODO: similar for territories, at least once localeName() does so.
1032 }
1033 }
1034#undef localeRows
1035
1036 return found;
1037}
1038
1039QTimeZonePrivate::NamePrefixMatch
1040QTimeZonePrivate::findNarrowOffsetPrefix(QStringView text, const QLocale &locale)
1041{
1042 using Flag = QtTemporalPattern::TemporalFieldFlag;
1043 constexpr auto narrowOffset = Flag::Numeric | Flag::Abbreviated | Flag::AcceptUtcPrefix;
1044 if (const auto match = matchOffsetFormat(text, locale, locale.d->m_index, narrowOffset)) {
1045 // Check offset is sane:
1046 if (QTimeZone::MinUtcOffsetSecs <= match.offset
1047 && match.offset <= QTimeZone::MaxUtcOffsetSecs) {
1048
1049 // Although we don't have an IANA ID, the ISO offset format text
1050 // should match what the QLocale(ianaId) constructor accepts, which
1051 // is good enough for our purposes.
1052 return { isoOffsetFormat(match.offset, QTimeZone::OffsetName).toLatin1(),
1053 match.size, QTimeZone::GenericTime, match.offset };
1054 }
1055 }
1056 return {};
1057}
1058
1059QTimeZonePrivate::NamePrefixMatch
1060QTimeZonePrivate::findOffsetPrefix(QStringView text, const QLocale &locale,
1061 QtTemporalPattern::TemporalFieldFlags flags)
1062{
1063 NamePrefixMatch best;
1064 if (text.isEmpty())
1065 return best;
1066
1067 const auto idForOffset = [](int offsetSeconds) -> QByteArray {
1068 if (!offsetSeconds)
1069 return "UTC";
1070 return isoOffsetFormat(offsetSeconds, QTimeZone::OffsetName).toLatin1();
1071 };
1072
1073 const auto match = matchOffsetFormat(text, locale, locale.d->m_index, flags);
1074 if (match && match.size > best.nameLength
1075 && QTimeZone::MinUtcOffsetSecs <= match.offset
1076 && match.offset <= QTimeZone::MaxUtcOffsetSecs) {
1077 best = { idForOffset(match.offset), match.size, QTimeZone::GenericTime, match.offset };
1078 }
1079
1080 return best;
1081}
1082#endif // ICU or not
1083
1084QT_END_NAMESPACE
QList< QByteArrayView > ianaIdsForTerritory(QLocale::Territory territory)
#define tableLookup(table, member, sought, test)
#define localeRows(table, member)