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 (listing zone names) 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 // Include the CLDR-canonical name, as well
169 const QByteArrayView zone = QTimeZonePrivate::aliasToIana(result);
170 if (!zone.isEmpty()) {
171 list << zone.toByteArray();
172 Q_ASSERT(QTimeZonePrivate::aliasToIana(zone).isEmpty());
173 }
174 status = U_ZERO_ERROR;
175 result = uenum_next(uenum, &size, &status);
176 }
177
178 std::sort(list.begin(), list.end());
179 list.erase(std::unique(list.begin(), list.end()), list.end());
180 return list;
181}
182
183// Qt wrapper around ucal_getDSTSavings()
184static int ucalDaylightOffset(const QByteArray &id)
185{
186 UErrorCode status = U_ZERO_ERROR;
187 const QString utf16 = QString::fromLatin1(id);
188 const int32_t dstMSecs = ucal_getDSTSavings(
189 reinterpret_cast<const UChar *>(utf16.data()), &status);
190 return U_SUCCESS(status) ? dstMSecs / 1000 : 0;
191}
192
193// Create the system default time zone
194QIcuTimeZonePrivate::QIcuTimeZonePrivate()
195 : m_ucal(nullptr)
196{
197 // TODO No ICU C API to obtain system tz, assume default hasn't been changed
198 init(ucalDefaultTimeZoneId());
199}
200
201// Create a named time zone
202QIcuTimeZonePrivate::QIcuTimeZonePrivate(const QByteArray &ianaId)
203 : m_ucal(nullptr)
204{
205 // ICU misleadingly maps invalid IDs to GMT.
206 if (isTimeZoneIdAvailable(ianaId))
207 init(ianaId);
208}
209
210QIcuTimeZonePrivate::QIcuTimeZonePrivate(const QIcuTimeZonePrivate &other)
211 : QTimeZonePrivate(other), m_ucal(nullptr)
212{
213 // Clone the ucal so we don't close the shared object
214 UErrorCode status = U_ZERO_ERROR;
215 m_ucal = ucal_clone(other.m_ucal, &status);
216 if (!U_SUCCESS(status)) {
217 m_id.clear();
218 m_ucal = nullptr;
219 }
220}
221
222QIcuTimeZonePrivate::~QIcuTimeZonePrivate()
223{
224 ucal_close(m_ucal);
225}
226
227QIcuTimeZonePrivate *QIcuTimeZonePrivate::clone() const
228{
229 return new QIcuTimeZonePrivate(*this);
230}
231
232void QIcuTimeZonePrivate::init(const QByteArray &ianaId)
233{
234 m_id = ianaId;
235
236 const QString id = QString::fromUtf8(m_id);
237 UErrorCode status = U_ZERO_ERROR;
238 //TODO Use UCAL_GREGORIAN for now to match QLocale, change to UCAL_DEFAULT once full ICU support
239 m_ucal = ucal_open(reinterpret_cast<const UChar *>(id.data()), id.size(),
240 QLocale().name().toUtf8(), UCAL_GREGORIAN, &status);
241
242 if (!U_SUCCESS(status)) {
243 m_id.clear();
244 m_ucal = nullptr;
245 }
246}
247
248QString QIcuTimeZonePrivate::displayName(QTimeZone::TimeType timeType,
249 QTimeZone::NameType nameType,
250 const QLocale &locale) const
251{
252 // Base class has handled OffsetName if we came via the other overload.
253 if (nameType == QTimeZone::OffsetName) {
254 int offset = standardTimeOffset(QDateTime::currentMSecsSinceEpoch());
255 // We can't use transitions reliably to find out right DST offset.
256 // Instead use DST offset API to try to get it, when needed:
257 if (timeType == QTimeZone::DaylightTime)
258 offset += ucalDaylightOffset(m_id);
259 // This is only valid for times since the most recent standard offset
260 // change; for earlier times, caller must use the other overload.
261
262 // Use our own formating for offset names (ICU C API doesn't support it
263 // and we may as well be self-consistent anyway).
264 return isoOffsetFormat(offset);
265 }
266 // Technically this may be suspect, if locale isn't QLocale(), since that's
267 // what we used when constructing m_ucal; does ICU cope with inconsistency ?
268 using namespace QtTimeZoneLocale;
269 return ucalTimeZoneDisplayName(m_ucal, timeType, nameType, locale.name().toUtf8());
270}
271
272int QIcuTimeZonePrivate::offsetFromUtc(qint64 atMSecsSinceEpoch) const
273{
274 int stdOffset = 0;
275 int dstOffset = 0;
276 ucalOffsetsAtTime(m_ucal, atMSecsSinceEpoch, &stdOffset, & dstOffset);
277 return stdOffset + dstOffset;
278}
279
280int QIcuTimeZonePrivate::standardTimeOffset(qint64 atMSecsSinceEpoch) const
281{
282 int stdOffset = 0;
283 int dstOffset = 0;
284 ucalOffsetsAtTime(m_ucal, atMSecsSinceEpoch, &stdOffset, & dstOffset);
285 return stdOffset;
286}
287
288int QIcuTimeZonePrivate::daylightTimeOffset(qint64 atMSecsSinceEpoch) const
289{
290 int stdOffset = 0;
291 int dstOffset = 0;
292 ucalOffsetsAtTime(m_ucal, atMSecsSinceEpoch, &stdOffset, & dstOffset);
293 return dstOffset;
294}
295
296bool QIcuTimeZonePrivate::hasDaylightTime() const
297{
298 if (ucalDaylightOffset(m_id) != 0)
299 return true;
300#if U_ICU_VERSION_MAJOR_NUM >= 50
301 for (qint64 when = minMSecs(); when != invalidMSecs(); ) {
302 auto data = nextTransition(when);
303 if (data.daylightTimeOffset && data.daylightTimeOffset != invalidSeconds())
304 return true;
305 when = data.atMSecsSinceEpoch;
306 }
307#endif
308 return false;
309}
310
311bool QIcuTimeZonePrivate::isDaylightTime(qint64 atMSecsSinceEpoch) const
312{
313 // Clone the ucal so we don't change the shared object
314 UErrorCode status = U_ZERO_ERROR;
315 UCalendar *ucal = ucal_clone(m_ucal, &status);
316 if (!U_SUCCESS(status))
317 return false;
318
319 // Set the date to find the offset for
320 status = U_ZERO_ERROR;
321 ucal_setMillis(ucal, atMSecsSinceEpoch, &status);
322
323 bool result = false;
324 if (U_SUCCESS(status)) {
325 status = U_ZERO_ERROR;
326 result = ucal_inDaylightTime(ucal, &status);
327 }
328
329 ucal_close(ucal);
330 return result;
331}
332
333QTimeZonePrivate::Data QIcuTimeZonePrivate::data(qint64 forMSecsSinceEpoch) const
334{
335 // Available in ICU C++ api, and draft C api in v50
336 Data data;
337#if U_ICU_VERSION_MAJOR_NUM >= 50
338 data = ucalTimeZoneTransition(m_ucal, UCAL_TZ_TRANSITION_PREVIOUS_INCLUSIVE,
339 forMSecsSinceEpoch);
340 if (data.atMSecsSinceEpoch == invalidMSecs()) // before first transition
341#endif
342 {
343 ucalOffsetsAtTime(m_ucal, forMSecsSinceEpoch, &data.standardTimeOffset,
344 &data.daylightTimeOffset);
345 data.offsetFromUtc = data.standardTimeOffset + data.daylightTimeOffset;
346 // TODO No ICU API for abbreviation, use short name for it:
347 using namespace QtTimeZoneLocale;
348 QTimeZone::TimeType timeType
349 = data.daylightTimeOffset ? QTimeZone::DaylightTime : QTimeZone::StandardTime;
350 data.abbreviation = ucalTimeZoneDisplayName(m_ucal, timeType, QTimeZone::ShortName,
351 QLocale().name().toUtf8());
352 }
353 data.atMSecsSinceEpoch = forMSecsSinceEpoch;
354 return data;
355}
356
357bool QIcuTimeZonePrivate::hasTransitions() const
358{
359 // Available in ICU C++ api, and draft C api in v50
360#if U_ICU_VERSION_MAJOR_NUM >= 50
361 return true;
362#else
363 return false;
364#endif
365}
366
367QTimeZonePrivate::Data QIcuTimeZonePrivate::nextTransition(qint64 afterMSecsSinceEpoch) const
368{
369 // Available in ICU C++ api, and draft C api in v50
370#if U_ICU_VERSION_MAJOR_NUM >= 50
371 return ucalTimeZoneTransition(m_ucal, UCAL_TZ_TRANSITION_NEXT, afterMSecsSinceEpoch);
372#else
373 Q_UNUSED(afterMSecsSinceEpoch);
374 return {};
375#endif
376}
377
378QTimeZonePrivate::Data QIcuTimeZonePrivate::previousTransition(qint64 beforeMSecsSinceEpoch) const
379{
380 // Available in ICU C++ api, and draft C api in v50
381#if U_ICU_VERSION_MAJOR_NUM >= 50
382 return ucalTimeZoneTransition(m_ucal, UCAL_TZ_TRANSITION_PREVIOUS, beforeMSecsSinceEpoch);
383#else
384 Q_UNUSED(beforeMSecsSinceEpoch);
385 return {};
386#endif
387}
388
389QByteArray QIcuTimeZonePrivate::systemTimeZoneId() const
390{
391 // No ICU C API to obtain system tz
392 // TODO Assume default hasn't been changed and is the latests system
393 return ucalDefaultTimeZoneId();
394}
395
396bool QIcuTimeZonePrivate::isTimeZoneIdAvailable(QByteArrayView ianaId) const
397{
398 return QtTimeZoneLocale::ucalKnownTimeZoneId(QString::fromUtf8(ianaId));
399}
400
401QList<QByteArray> QIcuTimeZonePrivate::availableTimeZoneIds() const
402{
403 UErrorCode status = U_ZERO_ERROR;
404 UEnumeration *uenum = ucal_openTimeZones(&status);
405 // Does not document order of entries.
406 QList<QByteArray> result;
407 if (U_SUCCESS(status))
408 result = uenumToIdList(uenum); // Ensures sorted, unique.
409 uenum_close(uenum);
410 return result;
411}
412
413QList<QByteArray> QIcuTimeZonePrivate::availableTimeZoneIds(QLocale::Territory territory) const
414{
415 const QLatin1StringView regionCode = QLocalePrivate::territoryToCode(territory);
416 const QByteArray regionCodeUtf8 = QString(regionCode).toUtf8();
417 UErrorCode status = U_ZERO_ERROR;
418 UEnumeration *uenum = ucal_openCountryTimeZones(regionCodeUtf8.data(), &status);
419 QList<QByteArray> result;
420 if (U_SUCCESS(status))
421 result = uenumToIdList(uenum);
422 uenum_close(uenum);
423 // We could merge in what matchingTimeZoneIds(territory) gives us, but
424 // hopefully that's redundant, as ICU packages CLDR.
425 return result;
426}
427
428QList<QByteArray> QIcuTimeZonePrivate::availableTimeZoneIds(int offsetFromUtc) const
429{
430// TODO Available directly in C++ api but not C api, from 4.8 onwards new filter method works
431#if U_ICU_VERSION_MAJOR_NUM >= 49 || (U_ICU_VERSION_MAJOR_NUM == 4 && U_ICU_VERSION_MINOR_NUM == 8)
432 UErrorCode status = U_ZERO_ERROR;
433 UEnumeration *uenum = ucal_openTimeZoneIDEnumeration(UCAL_ZONE_TYPE_ANY, nullptr,
434 &offsetFromUtc, &status);
435 QList<QByteArray> result;
436 if (U_SUCCESS(status))
437 result = uenumToIdList(uenum);
438 uenum_close(uenum);
439 // We could merge in what matchingTimeZoneIds(offsetFromUtc) gives us, but
440 // hopefully that's redundant, as ICU packages CLDR.
441 return result;
442#else
443 return QTimeZonePrivate::availableTimeZoneIds(offsetFromUtc);
444#endif
445}
446
447QT_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)