1 // © 2016 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 /*
4 ********************************************************************************
5 * Copyright (C) 2005-2016, International Business Machines
6 * Corporation and others. All Rights Reserved.
7 ********************************************************************************
8 *
9 * File WINDTFMT.CPP
10 *
11 ********************************************************************************
12 */
13
14 #include "unicode/utypes.h"
15
16 #if U_PLATFORM_USES_ONLY_WIN32_API
17
18 #if !UCONFIG_NO_FORMATTING
19
20 #include "unicode/ures.h"
21 #include "unicode/format.h"
22 #include "unicode/fmtable.h"
23 #include "unicode/datefmt.h"
24 #include "unicode/simpleformatter.h"
25 #include "unicode/calendar.h"
26 #include "unicode/gregocal.h"
27 #include "unicode/locid.h"
28 #include "unicode/unistr.h"
29 #include "unicode/ustring.h"
30 #include "unicode/timezone.h"
31 #include "unicode/utmscale.h"
32
33 #include "charstr.h"
34 #include "cmemory.h"
35 #include "ulocimp.h"
36 #include "uresimp.h"
37 #include "windtfmt.h"
38 #include "wintzimpl.h"
39
40 #ifndef WIN32_LEAN_AND_MEAN
41 # define WIN32_LEAN_AND_MEAN
42 #endif
43 # define VC_EXTRALEAN
44 # define NOUSER
45 # define NOSERVICE
46 # define NOIME
47 # define NOMCX
48 #include <windows.h>
49
50 U_NAMESPACE_BEGIN
51
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Win32DateFormat)52 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Win32DateFormat)
53
54 #define NEW_ARRAY(type,count) (type *) uprv_malloc((count) * sizeof(type))
55 #define DELETE_ARRAY(array) uprv_free((void *) (array))
56
57 #define STACK_BUFFER_SIZE 64
58
59 UnicodeString* Win32DateFormat::getTimeDateFormat(const Calendar *cal, const Locale *locale, UErrorCode &status) const
60 {
61 UnicodeString *result = nullptr;
62 const char *type = cal->getType();
63 const char *base = locale->getBaseName();
64 UResourceBundle *topBundle = ures_open((char *) 0, base, &status);
65 UResourceBundle *calBundle = ures_getByKey(topBundle, "calendar", nullptr, &status);
66 UResourceBundle *typBundle = ures_getByKeyWithFallback(calBundle, type, nullptr, &status);
67 UResourceBundle *patBundle = ures_getByKeyWithFallback(typBundle, "DateTimePatterns", nullptr, &status);
68
69 if (status == U_MISSING_RESOURCE_ERROR) {
70 status = U_ZERO_ERROR;
71 typBundle = ures_getByKeyWithFallback(calBundle, "gregorian", typBundle, &status);
72 patBundle = ures_getByKeyWithFallback(typBundle, "DateTimePatterns", patBundle, &status);
73 }
74
75 if (U_FAILURE(status)) {
76 static const char16_t defaultPattern[] = {0x007B, 0x0031, 0x007D, 0x0020, 0x007B, 0x0030, 0x007D, 0x0000}; // "{1} {0}"
77 return new UnicodeString(defaultPattern, UPRV_LENGTHOF(defaultPattern));
78 }
79
80 int32_t resStrLen = 0;
81 int32_t glueIndex = DateFormat::kDateTime;
82 int32_t patSize = ures_getSize(patBundle);
83 if (patSize >= (DateFormat::kDateTimeOffset + DateFormat::kShort + 1)) {
84 // Get proper date time format
85 glueIndex = (int32_t)(DateFormat::kDateTimeOffset + (fDateStyle - DateFormat::kDateOffset));
86 }
87 const char16_t *resStr = ures_getStringByIndex(patBundle, glueIndex, &resStrLen, &status);
88
89 result = new UnicodeString(true, resStr, resStrLen);
90
91 ures_close(patBundle);
92 ures_close(typBundle);
93 ures_close(calBundle);
94 ures_close(topBundle);
95
96 return result;
97 }
98
99 // TODO: This is copied in both winnmfmt.cpp and windtfmt.cpp, but really should
100 // be factored out into a common helper for both.
GetEquivalentWindowsLocaleName(const Locale & locale,UnicodeString ** buffer)101 static UErrorCode GetEquivalentWindowsLocaleName(const Locale& locale, UnicodeString** buffer)
102 {
103 UErrorCode status = U_ZERO_ERROR;
104
105 // Convert from names like "en_CA" and "de_DE@collation=phonebook" to "en-CA" and "de-DE-u-co-phonebk".
106 CharString asciiBCP47Tag = ulocimp_toLanguageTag(locale.getName(), false, status);
107
108 if (U_SUCCESS(status))
109 {
110 // Need it to be UTF-16, not 8-bit
111 // TODO: This seems like a good thing for a helper
112 wchar_t bcp47Tag[LOCALE_NAME_MAX_LENGTH] = {};
113 int32_t i;
114 for (i = 0; i < UPRV_LENGTHOF(bcp47Tag); i++)
115 {
116 if (asciiBCP47Tag[i] == '\0')
117 {
118 break;
119 }
120 else
121 {
122 // normally just copy the character
123 bcp47Tag[i] = static_cast<wchar_t>(asciiBCP47Tag[i]);
124 }
125 }
126
127 // Ensure it's null terminated
128 if (i < (UPRV_LENGTHOF(bcp47Tag) - 1))
129 {
130 bcp47Tag[i] = L'\0';
131 }
132 else
133 {
134 // Ran out of room.
135 bcp47Tag[UPRV_LENGTHOF(bcp47Tag) - 1] = L'\0';
136 }
137
138
139 wchar_t windowsLocaleName[LOCALE_NAME_MAX_LENGTH] = {};
140
141 // Note: On Windows versions below 10, there is no support for locale name aliases.
142 // This means that it will fail for locales where ICU has a completely different
143 // name (like ku vs ckb), and it will also not work for alternate sort locale
144 // names like "de-DE-u-co-phonebk".
145
146 // TODO: We could add some sort of exception table for cases like ku vs ckb.
147
148 int length = ResolveLocaleName(bcp47Tag, windowsLocaleName, UPRV_LENGTHOF(windowsLocaleName));
149
150 if (length > 0)
151 {
152 *buffer = new UnicodeString(windowsLocaleName);
153 }
154 else
155 {
156 status = U_UNSUPPORTED_ERROR;
157 }
158 }
159 return status;
160 }
161
162 // TODO: Range-check timeStyle, dateStyle
Win32DateFormat(DateFormat::EStyle timeStyle,DateFormat::EStyle dateStyle,const Locale & locale,UErrorCode & status)163 Win32DateFormat::Win32DateFormat(DateFormat::EStyle timeStyle, DateFormat::EStyle dateStyle, const Locale &locale, UErrorCode &status)
164 : DateFormat(), fDateTimeMsg(nullptr), fTimeStyle(timeStyle), fDateStyle(dateStyle), fLocale(locale), fZoneID(), fWindowsLocaleName(nullptr)
165 {
166 if (U_SUCCESS(status)) {
167 GetEquivalentWindowsLocaleName(locale, &fWindowsLocaleName);
168 // Note: In the previous code, it would look up the LCID for the locale, and if
169 // the locale was not recognized then it would get an LCID of 0, which is a
170 // synonym for LOCALE_USER_DEFAULT on Windows.
171 // If the above method fails, then fWindowsLocaleName will remain as nullptr, and
172 // then we will pass nullptr to API GetLocaleInfoEx, which is the same as passing
173 // LOCALE_USER_DEFAULT.
174
175 fTZI = NEW_ARRAY(TIME_ZONE_INFORMATION, 1);
176 uprv_memset(fTZI, 0, sizeof(TIME_ZONE_INFORMATION));
177 adoptCalendar(Calendar::createInstance(locale, status));
178 }
179 }
180
Win32DateFormat(const Win32DateFormat & other)181 Win32DateFormat::Win32DateFormat(const Win32DateFormat &other)
182 : DateFormat(other)
183 {
184 *this = other;
185 }
186
~Win32DateFormat()187 Win32DateFormat::~Win32DateFormat()
188 {
189 // delete fCalendar;
190 uprv_free(fTZI);
191 delete fDateTimeMsg;
192 delete fWindowsLocaleName;
193 }
194
operator =(const Win32DateFormat & other)195 Win32DateFormat &Win32DateFormat::operator=(const Win32DateFormat &other)
196 {
197 if (this == &other) { return *this; } // self-assignment: no-op
198 // The following handles fCalendar
199 DateFormat::operator=(other);
200
201 // delete fCalendar;
202
203 this->fDateTimeMsg = other.fDateTimeMsg == nullptr ? nullptr : new UnicodeString(*other.fDateTimeMsg);
204 this->fTimeStyle = other.fTimeStyle;
205 this->fDateStyle = other.fDateStyle;
206 this->fLocale = other.fLocale;
207 // this->fCalendar = other.fCalendar->clone();
208 this->fZoneID = other.fZoneID;
209
210 this->fTZI = NEW_ARRAY(TIME_ZONE_INFORMATION, 1);
211 *this->fTZI = *other.fTZI;
212
213 this->fWindowsLocaleName = other.fWindowsLocaleName == nullptr ? nullptr : new UnicodeString(*other.fWindowsLocaleName);
214
215 return *this;
216 }
217
clone() const218 Win32DateFormat *Win32DateFormat::clone() const
219 {
220 return new Win32DateFormat(*this);
221 }
222
223 // TODO: Is just ignoring pos the right thing?
format(Calendar & cal,UnicodeString & appendTo,FieldPosition &) const224 UnicodeString &Win32DateFormat::format(Calendar &cal, UnicodeString &appendTo, FieldPosition & /* pos */) const
225 {
226 FILETIME ft;
227 SYSTEMTIME st_gmt;
228 SYSTEMTIME st_local;
229 TIME_ZONE_INFORMATION tzi = *fTZI;
230 UErrorCode status = U_ZERO_ERROR;
231 const TimeZone &tz = cal.getTimeZone();
232 int64_t uct, uft;
233
234 setTimeZoneInfo(&tzi, tz);
235
236 uct = utmscale_fromInt64((int64_t) cal.getTime(status), UDTS_ICU4C_TIME, &status);
237 uft = utmscale_toInt64(uct, UDTS_WINDOWS_FILE_TIME, &status);
238
239 ft.dwLowDateTime = (DWORD) (uft & 0xFFFFFFFF);
240 ft.dwHighDateTime = (DWORD) ((uft >> 32) & 0xFFFFFFFF);
241
242 FileTimeToSystemTime(&ft, &st_gmt);
243 SystemTimeToTzSpecificLocalTime(&tzi, &st_gmt, &st_local);
244
245
246 if (fDateStyle != DateFormat::kNone && fTimeStyle != DateFormat::kNone) {
247 UnicodeString date;
248 UnicodeString time;
249 UnicodeString *pattern = fDateTimeMsg;
250
251 formatDate(&st_local, date);
252 formatTime(&st_local, time);
253
254 if (strcmp(fCalendar->getType(), cal.getType()) != 0) {
255 pattern = getTimeDateFormat(&cal, &fLocale, status);
256 }
257
258 SimpleFormatter(*pattern, 2, 2, status).format(time, date, appendTo, status);
259 } else if (fDateStyle != DateFormat::kNone) {
260 formatDate(&st_local, appendTo);
261 } else if (fTimeStyle != DateFormat::kNone) {
262 formatTime(&st_local, appendTo);
263 }
264
265 return appendTo;
266 }
267
parse(const UnicodeString &,Calendar &,ParsePosition & pos) const268 void Win32DateFormat::parse(const UnicodeString& /* text */, Calendar& /* cal */, ParsePosition& pos) const
269 {
270 pos.setErrorIndex(pos.getIndex());
271 }
272
adoptCalendar(Calendar * newCalendar)273 void Win32DateFormat::adoptCalendar(Calendar *newCalendar)
274 {
275 if (fCalendar == nullptr || strcmp(fCalendar->getType(), newCalendar->getType()) != 0) {
276 UErrorCode status = U_ZERO_ERROR;
277
278 if (fDateStyle != DateFormat::kNone && fTimeStyle != DateFormat::kNone) {
279 delete fDateTimeMsg;
280 fDateTimeMsg = getTimeDateFormat(newCalendar, &fLocale, status);
281 }
282 }
283
284 delete fCalendar;
285 fCalendar = newCalendar;
286
287 fZoneID = setTimeZoneInfo(fTZI, fCalendar->getTimeZone());
288 }
289
setCalendar(const Calendar & newCalendar)290 void Win32DateFormat::setCalendar(const Calendar &newCalendar)
291 {
292 adoptCalendar(newCalendar.clone());
293 }
294
adoptTimeZone(TimeZone * zoneToAdopt)295 void Win32DateFormat::adoptTimeZone(TimeZone *zoneToAdopt)
296 {
297 fZoneID = setTimeZoneInfo(fTZI, *zoneToAdopt);
298 fCalendar->adoptTimeZone(zoneToAdopt);
299 }
300
setTimeZone(const TimeZone & zone)301 void Win32DateFormat::setTimeZone(const TimeZone& zone)
302 {
303 fZoneID = setTimeZoneInfo(fTZI, zone);
304 fCalendar->setTimeZone(zone);
305 }
306
307 static const DWORD dfFlags[] = {DATE_LONGDATE, DATE_LONGDATE, DATE_SHORTDATE, DATE_SHORTDATE};
308
formatDate(const SYSTEMTIME * st,UnicodeString & appendTo) const309 void Win32DateFormat::formatDate(const SYSTEMTIME *st, UnicodeString &appendTo) const
310 {
311 int result=0;
312 wchar_t stackBuffer[STACK_BUFFER_SIZE];
313 wchar_t *buffer = stackBuffer;
314 const wchar_t *localeName = nullptr;
315
316 if (fWindowsLocaleName != nullptr)
317 {
318 localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
319 }
320
321 result = GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, nullptr, buffer, STACK_BUFFER_SIZE, nullptr);
322
323 if (result == 0) {
324 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
325 int newLength = GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, nullptr, nullptr, 0, nullptr);
326
327 buffer = NEW_ARRAY(wchar_t, newLength);
328
329 GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, nullptr, buffer, newLength, nullptr);
330 }
331 }
332
333 appendTo.append((const char16_t *)buffer, (int32_t) wcslen(buffer));
334
335 if (buffer != stackBuffer) {
336 DELETE_ARRAY(buffer);
337 }
338 }
339
340 static const DWORD tfFlags[] = {0, 0, 0, TIME_NOSECONDS};
341
formatTime(const SYSTEMTIME * st,UnicodeString & appendTo) const342 void Win32DateFormat::formatTime(const SYSTEMTIME *st, UnicodeString &appendTo) const
343 {
344 int result;
345 wchar_t stackBuffer[STACK_BUFFER_SIZE];
346 wchar_t *buffer = stackBuffer;
347 const wchar_t *localeName = nullptr;
348
349 if (fWindowsLocaleName != nullptr)
350 {
351 localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
352 }
353
354 result = GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, nullptr, buffer, STACK_BUFFER_SIZE);
355
356 if (result == 0) {
357 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
358 int newLength = GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, nullptr, nullptr, 0);
359
360 buffer = NEW_ARRAY(wchar_t, newLength);
361
362 GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, nullptr, buffer, newLength);
363 }
364 }
365
366 appendTo.append((const char16_t *)buffer, (int32_t) wcslen(buffer));
367
368 if (buffer != stackBuffer) {
369 DELETE_ARRAY(buffer);
370 }
371 }
372
setTimeZoneInfo(TIME_ZONE_INFORMATION * tzi,const TimeZone & zone) const373 UnicodeString Win32DateFormat::setTimeZoneInfo(TIME_ZONE_INFORMATION *tzi, const TimeZone &zone) const
374 {
375 UnicodeString zoneID;
376
377 zone.getID(zoneID);
378
379 if (zoneID.compare(fZoneID) != 0) {
380 UnicodeString icuid;
381
382 zone.getID(icuid);
383 if (! uprv_getWindowsTimeZoneInfo(tzi, icuid.getBuffer(), icuid.length())) {
384 UBool found = false;
385 int32_t ec = TimeZone::countEquivalentIDs(icuid);
386
387 for (int z = 0; z < ec; z += 1) {
388 UnicodeString equiv = TimeZone::getEquivalentID(icuid, z);
389
390 found = uprv_getWindowsTimeZoneInfo(tzi, equiv.getBuffer(), equiv.length());
391 if (found) {
392 break;
393 }
394 }
395
396 if (! found) {
397 GetTimeZoneInformation(tzi);
398 }
399 }
400 }
401
402 return zoneID;
403 }
404
405 U_NAMESPACE_END
406
407 #endif /* #if !UCONFIG_NO_FORMATTING */
408
409 #endif // U_PLATFORM_USES_ONLY_WIN32_API
410