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
qtimezoneprivate_icu.cpp
Go to the documentation of this file.
1// Copyright (C) 2013 John Layt <jlayt@kde.org>
2// Copyright (C) 2022 The Qt Company Ltd.
3// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
4// Qt-Security score:significant reason:default
5
6#include "qtimezone.h"
9
10#include <unicode/ucal.h>
11
12#include <qdebug.h>
13#include <qlist.h>
14
15#include <algorithm>
16
17#ifdef Q_OS_HARMONY
18#include <QtCore/private/qohossystemtimezone_p.h>
19#endif
20
21QT_BEGIN_NAMESPACE
22
23/*
24 Private
25
26 ICU implementation
27*/
28
29// ICU utilities
30
31// Qt wrapper around ucal_getDefaultTimeZone()
32static QByteArray ucalDefaultTimeZoneId()
33{
34#ifdef Q_OS_HARMONY
35 if (const auto ohosTimeZoneId = qOhosSystemTimeZoneId(); !ohosTimeZoneId.isEmpty())
36 return ohosTimeZoneId;
37#endif
38 int32_t size = 30;
39 QString result(size, Qt::Uninitialized);
40 UErrorCode status = U_ZERO_ERROR;
41
42 // size = ucal_getDefaultTimeZone(result, resultLength, status)
43 size = ucal_getDefaultTimeZone(reinterpret_cast<UChar *>(result.data()), size, &status);
44
45 // If overflow, then resize and retry
46 if (status == U_BUFFER_OVERFLOW_ERROR) {
47 result.resize(size);
48 status = U_ZERO_ERROR;
49 size = ucal_getDefaultTimeZone(reinterpret_cast<UChar *>(result.data()), size, &status);
50 }
51
52 // If successful on first or second go, resize and return
53 if (U_SUCCESS(status)) {
54 result.resize(size);
55 return std::move(result).toUtf8();
56 }
57
58 return QByteArray();
59}
60
61// Qt wrapper around ucal_get() for offsets
62static bool ucalOffsetsAtTime(UCalendar *m_ucal, qint64 atMSecsSinceEpoch,
63 int *utcOffset, int *dstOffset)
64{
65 *utcOffset = 0;
66 *dstOffset = 0;
67
68 // Clone the ucal so we don't change the shared object
69 UErrorCode status = U_ZERO_ERROR;
70 UCalendar *ucal = ucal_clone(m_ucal, &status);
71 if (!U_SUCCESS(status))
72 return false;
73
74 // Set the date to find the offset for
75 status = U_ZERO_ERROR;
76 ucal_setMillis(ucal, atMSecsSinceEpoch, &status);
77
78 int32_t utc = 0;
79 if (U_SUCCESS(status)) {
80 status = U_ZERO_ERROR;
81 // Returns msecs
82 utc = ucal_get(ucal, UCAL_ZONE_OFFSET, &status) / 1000;
83 }
84
85 int32_t dst = 0;
86 if (U_SUCCESS(status)) {
87 status = U_ZERO_ERROR;
88 // Returns msecs
89 dst = ucal_get(ucal, UCAL_DST_OFFSET, &status) / 1000;
90 }
91
92 ucal_close(ucal);
93 if (U_SUCCESS(status)) {
94 *utcOffset = utc;
95 *dstOffset = dst;
96 return true;
97 }
98 return false;
99}
100
101#if U_ICU_VERSION_MAJOR_NUM >= 50
102// Qt wrapper around qt_ucal_getTimeZoneTransitionDate & ucal_get
103static QTimeZonePrivate::Data ucalTimeZoneTransition(UCalendar *m_ucal,
104 UTimeZoneTransitionType type,
105 qint64 atMSecsSinceEpoch)
106{
107 QTimeZonePrivate::Data tran;
108
109 // Clone the ucal so we don't change the shared object
110 UErrorCode status = U_ZERO_ERROR;
111 UCalendar *ucal = ucal_clone(m_ucal, &status);
112 if (!U_SUCCESS(status))
113 return tran;
114
115 // Set the date to find the transition for
116 status = U_ZERO_ERROR;
117 const UDate when = UDate(atMSecsSinceEpoch);
118 ucal_setMillis(ucal, when, &status);
119
120 // Find the transition time
121 UDate tranMSecs = 0;
122 status = U_ZERO_ERROR;
123 bool ok = ucal_getTimeZoneTransitionDate(ucal, type, &tranMSecs, &status);
124
125 // Catch a known violation (in ICU 67) of the specified behavior:
126 if (U_SUCCESS(status) && ok && type == UCAL_TZ_TRANSITION_NEXT) {
127 // At the end of time, that can "succeed" with tranMSecs ==
128 // atMSecsSinceEpoch, which should be treated as a failure.
129 // (At the start of time, previous correctly fails.)
130 ok = tranMSecs > when;
131 }
132
133 // Set the transition time to find the offsets for
134 if (U_SUCCESS(status) && ok) {
135 status = U_ZERO_ERROR;
136 ucal_setMillis(ucal, tranMSecs, &status);
137 }
138
139 int32_t utc = 0;
140 if (U_SUCCESS(status) && ok) {
141 status = U_ZERO_ERROR;
142 utc = ucal_get(ucal, UCAL_ZONE_OFFSET, &status) / 1000;
143 }
144
145 int32_t dst = 0;
146 if (U_SUCCESS(status) && ok) {
147 status = U_ZERO_ERROR;
148 dst = ucal_get(ucal, UCAL_DST_OFFSET, &status) / 1000;
149 }
150
151 ucal_close(ucal);
152 if (!U_SUCCESS(status) || !ok)
153 return tran;
154 tran.atMSecsSinceEpoch = qint64(tranMSecs);
155 tran.offsetFromUtc = utc + dst;
156 tran.standardTimeOffset = utc;
157 tran.daylightTimeOffset = dst;
158 // TODO No ICU API, use short name as abbreviation.
159 QTimeZone::TimeType timeType = dst == 0 ? QTimeZone::StandardTime : QTimeZone::DaylightTime;
160 using namespace QtTimeZoneLocale;
161 tran.abbreviation = ucalTimeZoneDisplayName(m_ucal, timeType,
162 QTimeZone::ShortName, QLocale().name().toUtf8());
163 return tran;
164}
165#endif // U_ICU_VERSION_SHORT
166
167// Convert a uenum (listing zone names) to a QList<QByteArray>
168static QList<QByteArray> uenumToIdList(UEnumeration *uenum)
169{
170 QList<QByteArray> list;
171 int32_t size = 0;
172 UErrorCode status = U_ZERO_ERROR;
173 // TODO Perhaps use uenum_unext instead?
174 QByteArray result = uenum_next(uenum, &size, &status);
175 while (U_SUCCESS(status) && !result.isEmpty()) {
176 list << result;
177 // Include the CLDR-canonical name, as well
178 const QByteArrayView zone = QTimeZonePrivate::aliasToIana(result);
179 if (!zone.isEmpty()) {
180 list << zone.toByteArray();
181 Q_ASSERT(QTimeZonePrivate::aliasToIana(zone).isEmpty());
182 }
183 status = U_ZERO_ERROR;
184 result = uenum_next(uenum, &size, &status);
185 }
186
187 std::sort(list.begin(), list.end());
188 list.erase(std::unique(list.begin(), list.end()), list.end());
189 return list;
190}
191
192// Qt wrapper around ucal_getDSTSavings()
193static int ucalDaylightOffset(const QByteArray &id)
194{
195 UErrorCode status = U_ZERO_ERROR;
196 const QString utf16 = QString::fromLatin1(id);
197 const int32_t dstMSecs = ucal_getDSTSavings(
198 reinterpret_cast<const UChar *>(utf16.data()), &status);
199 return U_SUCCESS(status) ? dstMSecs / 1000 : 0;
200}
201
202// Create the system default time zone
203QIcuTimeZonePrivate::QIcuTimeZonePrivate()
204 : m_ucal(nullptr)
205{
206 // TODO No ICU C API to obtain system tz, assume default hasn't been changed
207 init(ucalDefaultTimeZoneId());
208}
209
210// Create a named time zone
211QIcuTimeZonePrivate::QIcuTimeZonePrivate(const QByteArray &ianaId)
212 : m_ucal(nullptr)
213{
214 // ICU misleadingly maps invalid IDs to GMT.
215 if (isTimeZoneIdAvailable(ianaId))
216 init(ianaId);
217}
218
219QIcuTimeZonePrivate::QIcuTimeZonePrivate(const QIcuTimeZonePrivate &other)
220 : QTimeZonePrivate(other), m_ucal(nullptr)
221{
222 // Clone the ucal so we don't close the shared object
223 UErrorCode status = U_ZERO_ERROR;
224 m_ucal = ucal_clone(other.m_ucal, &status);
225 if (!U_SUCCESS(status)) {
226 m_id.clear();
227 m_ucal = nullptr;
228 }
229}
230
231QIcuTimeZonePrivate::~QIcuTimeZonePrivate()
232{
233 ucal_close(m_ucal);
234}
235
236QIcuTimeZonePrivate *QIcuTimeZonePrivate::clone() const
237{
238 return new QIcuTimeZonePrivate(*this);
239}
240
241void QIcuTimeZonePrivate::init(const QByteArray &ianaId)
242{
243 m_id = ianaId;
244
245 const QString id = QString::fromUtf8(m_id);
246 UErrorCode status = U_ZERO_ERROR;
247 //TODO Use UCAL_GREGORIAN for now to match QLocale, change to UCAL_DEFAULT once full ICU support
248 m_ucal = ucal_open(reinterpret_cast<const UChar *>(id.data()), id.size(),
249 QLocale().name().toUtf8(), UCAL_GREGORIAN, &status);
250
251 if (!U_SUCCESS(status)) {
252 m_id.clear();
253 m_ucal = nullptr;
254 }
255}
256
257QString QIcuTimeZonePrivate::displayName(QTimeZone::TimeType timeType,
258 QTimeZone::NameType nameType,
259 const QLocale &locale) const
260{
261 // Base class has handled OffsetName if we came via the other overload.
262 if (nameType == QTimeZone::OffsetName) {
263 int offset = standardTimeOffset(QDateTime::currentMSecsSinceEpoch());
264 // We can't use transitions reliably to find out right DST offset.
265 // Instead use DST offset API to try to get it, when needed:
266 if (timeType == QTimeZone::DaylightTime)
267 offset += ucalDaylightOffset(m_id);
268 // This is only valid for times since the most recent standard offset
269 // change; for earlier times, caller must use the other overload.
270
271 // Use our own formating for offset names (ICU C API doesn't support it
272 // and we may as well be self-consistent anyway).
273 return isoOffsetFormat(offset);
274 }
275 // Technically this may be suspect, if locale isn't QLocale(), since that's
276 // what we used when constructing m_ucal; does ICU cope with inconsistency ?
277 using namespace QtTimeZoneLocale;
278 return ucalTimeZoneDisplayName(m_ucal, timeType, nameType, locale.name().toUtf8());
279}
280
281int QIcuTimeZonePrivate::offsetFromUtc(qint64 atMSecsSinceEpoch) const
282{
283 int stdOffset = 0;
284 int dstOffset = 0;
285 ucalOffsetsAtTime(m_ucal, atMSecsSinceEpoch, &stdOffset, & dstOffset);
286 return stdOffset + dstOffset;
287}
288
289int QIcuTimeZonePrivate::standardTimeOffset(qint64 atMSecsSinceEpoch) const
290{
291 int stdOffset = 0;
292 int dstOffset = 0;
293 ucalOffsetsAtTime(m_ucal, atMSecsSinceEpoch, &stdOffset, & dstOffset);
294 return stdOffset;
295}
296
297int QIcuTimeZonePrivate::daylightTimeOffset(qint64 atMSecsSinceEpoch) const
298{
299 int stdOffset = 0;
300 int dstOffset = 0;
301 ucalOffsetsAtTime(m_ucal, atMSecsSinceEpoch, &stdOffset, & dstOffset);
302 return dstOffset;
303}
304
305bool QIcuTimeZonePrivate::hasDaylightTime() const
306{
307 if (ucalDaylightOffset(m_id) != 0)
308 return true;
309#if U_ICU_VERSION_MAJOR_NUM >= 50
310 for (qint64 when = minMSecs(); when != invalidMSecs(); ) {
311 auto data = nextTransition(when);
312 if (data.daylightTimeOffset && data.daylightTimeOffset != invalidSeconds())
313 return true;
314 when = data.atMSecsSinceEpoch;
315 }
316#endif
317 return false;
318}
319
320bool QIcuTimeZonePrivate::isDaylightTime(qint64 atMSecsSinceEpoch) const
321{
322 // Clone the ucal so we don't change the shared object
323 UErrorCode status = U_ZERO_ERROR;
324 UCalendar *ucal = ucal_clone(m_ucal, &status);
325 if (!U_SUCCESS(status))
326 return false;
327
328 // Set the date to find the offset for
329 status = U_ZERO_ERROR;
330 ucal_setMillis(ucal, atMSecsSinceEpoch, &status);
331
332 bool result = false;
333 if (U_SUCCESS(status)) {
334 status = U_ZERO_ERROR;
335 result = ucal_inDaylightTime(ucal, &status);
336 }
337
338 ucal_close(ucal);
339 return result;
340}
341
342QTimeZonePrivate::Data QIcuTimeZonePrivate::data(qint64 forMSecsSinceEpoch) const
343{
344 // Available in ICU C++ api, and draft C api in v50
345 Data data;
346#if U_ICU_VERSION_MAJOR_NUM >= 50
347 data = ucalTimeZoneTransition(m_ucal, UCAL_TZ_TRANSITION_PREVIOUS_INCLUSIVE,
348 forMSecsSinceEpoch);
349 if (data.atMSecsSinceEpoch == invalidMSecs()) // before first transition
350#endif
351 {
352 ucalOffsetsAtTime(m_ucal, forMSecsSinceEpoch, &data.standardTimeOffset,
353 &data.daylightTimeOffset);
354 data.offsetFromUtc = data.standardTimeOffset + data.daylightTimeOffset;
355 // TODO No ICU API for abbreviation, use short name for it:
356 using namespace QtTimeZoneLocale;
357 QTimeZone::TimeType timeType
358 = data.daylightTimeOffset ? QTimeZone::DaylightTime : QTimeZone::StandardTime;
359 data.abbreviation = ucalTimeZoneDisplayName(m_ucal, timeType, QTimeZone::ShortName,
360 QLocale().name().toUtf8());
361 }
362 data.atMSecsSinceEpoch = forMSecsSinceEpoch;
363 return data;
364}
365
366bool QIcuTimeZonePrivate::hasTransitions() const
367{
368 // Available in ICU C++ api, and draft C api in v50
369#if U_ICU_VERSION_MAJOR_NUM >= 50
370 return true;
371#else
372 return false;
373#endif
374}
375
376QTimeZonePrivate::Data QIcuTimeZonePrivate::nextTransition(qint64 afterMSecsSinceEpoch) const
377{
378 // Available in ICU C++ api, and draft C api in v50
379#if U_ICU_VERSION_MAJOR_NUM >= 50
380 return ucalTimeZoneTransition(m_ucal, UCAL_TZ_TRANSITION_NEXT, afterMSecsSinceEpoch);
381#else
382 Q_UNUSED(afterMSecsSinceEpoch);
383 return {};
384#endif
385}
386
387QTimeZonePrivate::Data QIcuTimeZonePrivate::previousTransition(qint64 beforeMSecsSinceEpoch) const
388{
389 // Available in ICU C++ api, and draft C api in v50
390#if U_ICU_VERSION_MAJOR_NUM >= 50
391 return ucalTimeZoneTransition(m_ucal, UCAL_TZ_TRANSITION_PREVIOUS, beforeMSecsSinceEpoch);
392#else
393 Q_UNUSED(beforeMSecsSinceEpoch);
394 return {};
395#endif
396}
397
398QByteArray QIcuTimeZonePrivate::systemTimeZoneId() const
399{
400 // No ICU C API to obtain system tz
401 // TODO Assume default hasn't been changed and is the latests system
402 return ucalDefaultTimeZoneId();
403}
404
405bool QIcuTimeZonePrivate::isTimeZoneIdAvailable(QByteArrayView ianaId) const
406{
407 return QtTimeZoneLocale::ucalKnownTimeZoneId(QString::fromUtf8(ianaId));
408}
409
410QList<QByteArray> QIcuTimeZonePrivate::availableTimeZoneIds() const
411{
412 UErrorCode status = U_ZERO_ERROR;
413 UEnumeration *uenum = ucal_openTimeZones(&status);
414 // Does not document order of entries.
415 QList<QByteArray> result;
416 if (U_SUCCESS(status))
417 result = uenumToIdList(uenum); // Ensures sorted, unique.
418 uenum_close(uenum);
419 return result;
420}
421
422QList<QByteArray> QIcuTimeZonePrivate::availableTimeZoneIds(QLocale::Territory territory) const
423{
424 const QLatin1StringView regionCode = QLocalePrivate::territoryToCode(territory);
425 const QByteArray regionCodeUtf8 = QString(regionCode).toUtf8();
426 UErrorCode status = U_ZERO_ERROR;
427 UEnumeration *uenum = ucal_openCountryTimeZones(regionCodeUtf8.data(), &status);
428 QList<QByteArray> result;
429 if (U_SUCCESS(status))
430 result = uenumToIdList(uenum);
431 uenum_close(uenum);
432 // We could merge in what matchingTimeZoneIds(territory) gives us, but
433 // hopefully that's redundant, as ICU packages CLDR.
434 return result;
435}
436
437QList<QByteArray> QIcuTimeZonePrivate::availableTimeZoneIds(int offsetFromUtc) const
438{
439// TODO Available directly in C++ api but not C api, from 4.8 onwards new filter method works
440#if U_ICU_VERSION_MAJOR_NUM >= 49 || (U_ICU_VERSION_MAJOR_NUM == 4 && U_ICU_VERSION_MINOR_NUM == 8)
441 UErrorCode status = U_ZERO_ERROR;
442 UEnumeration *uenum = ucal_openTimeZoneIDEnumeration(UCAL_ZONE_TYPE_ANY, nullptr,
443 &offsetFromUtc, &status);
444 QList<QByteArray> result;
445 if (U_SUCCESS(status))
446 result = uenumToIdList(uenum);
447 uenum_close(uenum);
448 // We could merge in what matchingTimeZoneIds(offsetFromUtc) gives us, but
449 // hopefully that's redundant, as ICU packages CLDR.
450 return result;
451#else
452 return QTimeZonePrivate::availableTimeZoneIds(offsetFromUtc);
453#endif
454}
455
456QT_END_NAMESPACE
static bool ucalOffsetsAtTime(UCalendar *m_ucal, qint64 atMSecsSinceEpoch, int *utcOffset, int *dstOffset)
static int ucalDaylightOffset(const QByteArray &id)
static QList< QByteArray > uenumToIdList(UEnumeration *uenum)