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