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