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 // TODO: This is copied in both winnmfmt.cpp and windtfmt.cpp, but really should
98 // be factored out into a common helper for both.
GetEquivalentWindowsLocaleName(const Locale & locale,UnicodeString ** buffer)99 static UErrorCode GetEquivalentWindowsLocaleName(const Locale& locale, UnicodeString** buffer)
100 {
101 UErrorCode status = U_ZERO_ERROR;
102 char asciiBCP47Tag[LOCALE_NAME_MAX_LENGTH] = {};
103
104 // Convert from names like "en_CA" and "de_DE@collation=phonebook" to "en-CA" and "de-DE-u-co-phonebk".
105 (void)uloc_toLanguageTag(locale.getName(), asciiBCP47Tag, UPRV_LENGTHOF(asciiBCP47Tag), FALSE, &status);
106
107 if (U_SUCCESS(status))
108 {
109 // Need it to be UTF-16, not 8-bit
110 // TODO: This seems like a good thing for a helper
111 wchar_t bcp47Tag[LOCALE_NAME_MAX_LENGTH] = {};
112 int32_t i;
113 for (i = 0; i < UPRV_LENGTHOF(bcp47Tag); i++)
114 {
115 if (asciiBCP47Tag[i] == '\0')
116 {
117 break;
118 }
119 else
120 {
121 // normally just copy the character
122 bcp47Tag[i] = static_cast<wchar_t>(asciiBCP47Tag[i]);
123 }
124 }
125
126 // Ensure it's null terminated
127 if (i < (UPRV_LENGTHOF(bcp47Tag) - 1))
128 {
129 bcp47Tag[i] = L'\0';
130 }
131 else
132 {
133 // Ran out of room.
134 bcp47Tag[UPRV_LENGTHOF(bcp47Tag) - 1] = L'\0';
135 }
136
137
138 wchar_t windowsLocaleName[LOCALE_NAME_MAX_LENGTH] = {};
139
140 // Note: On Windows versions below 10, there is no support for locale name aliases.
141 // This means that it will fail for locales where ICU has a completely different
142 // name (like ku vs ckb), and it will also not work for alternate sort locale
143 // names like "de-DE-u-co-phonebk".
144
145 // TODO: We could add some sort of exception table for cases like ku vs ckb.
146
147 int length = ResolveLocaleName(bcp47Tag, windowsLocaleName, UPRV_LENGTHOF(windowsLocaleName));
148
149 if (length > 0)
150 {
151 *buffer = new UnicodeString(windowsLocaleName);
152 }
153 else
154 {
155 status = U_UNSUPPORTED_ERROR;
156 }
157 }
158 return status;
159 }
160
161 // TODO: Range-check timeStyle, dateStyle
Win32DateFormat(DateFormat::EStyle timeStyle,DateFormat::EStyle dateStyle,const Locale & locale,UErrorCode & status)162 Win32DateFormat::Win32DateFormat(DateFormat::EStyle timeStyle, DateFormat::EStyle dateStyle, const Locale &locale, UErrorCode &status)
163 : DateFormat(), fDateTimeMsg(NULL), fTimeStyle(timeStyle), fDateStyle(dateStyle), fLocale(locale), fZoneID(), fWindowsLocaleName(nullptr)
164 {
165 if (U_SUCCESS(status)) {
166 GetEquivalentWindowsLocaleName(locale, &fWindowsLocaleName);
167 // Note: In the previous code, it would look up the LCID for the locale, and if
168 // the locale was not recognized then it would get an LCID of 0, which is a
169 // synonym for LOCALE_USER_DEFAULT on Windows.
170 // If the above method fails, then fWindowsLocaleName will remain as nullptr, and
171 // then we will pass nullptr to API GetLocaleInfoEx, which is the same as passing
172 // LOCALE_USER_DEFAULT.
173
174 fTZI = NEW_ARRAY(TIME_ZONE_INFORMATION, 1);
175 uprv_memset(fTZI, 0, sizeof(TIME_ZONE_INFORMATION));
176 adoptCalendar(Calendar::createInstance(locale, status));
177 }
178 }
179
Win32DateFormat(const Win32DateFormat & other)180 Win32DateFormat::Win32DateFormat(const Win32DateFormat &other)
181 : DateFormat(other)
182 {
183 *this = other;
184 }
185
~Win32DateFormat()186 Win32DateFormat::~Win32DateFormat()
187 {
188 // delete fCalendar;
189 uprv_free(fTZI);
190 delete fDateTimeMsg;
191 delete fWindowsLocaleName;
192 }
193
operator =(const Win32DateFormat & other)194 Win32DateFormat &Win32DateFormat::operator=(const Win32DateFormat &other)
195 {
196 if (this == &other) { return *this; } // self-assignment: no-op
197 // The following handles fCalendar
198 DateFormat::operator=(other);
199
200 // delete fCalendar;
201
202 this->fDateTimeMsg = other.fDateTimeMsg == NULL ? NULL : new UnicodeString(*other.fDateTimeMsg);
203 this->fTimeStyle = other.fTimeStyle;
204 this->fDateStyle = other.fDateStyle;
205 this->fLocale = other.fLocale;
206 // this->fCalendar = other.fCalendar->clone();
207 this->fZoneID = other.fZoneID;
208
209 this->fTZI = NEW_ARRAY(TIME_ZONE_INFORMATION, 1);
210 *this->fTZI = *other.fTZI;
211
212 this->fWindowsLocaleName = other.fWindowsLocaleName == NULL ? NULL : new UnicodeString(*other.fWindowsLocaleName);
213
214 return *this;
215 }
216
clone() const217 Win32DateFormat *Win32DateFormat::clone() const
218 {
219 return new Win32DateFormat(*this);
220 }
221
222 // TODO: Is just ignoring pos the right thing?
format(Calendar & cal,UnicodeString & appendTo,FieldPosition &) const223 UnicodeString &Win32DateFormat::format(Calendar &cal, UnicodeString &appendTo, FieldPosition & /* pos */) const
224 {
225 FILETIME ft;
226 SYSTEMTIME st_gmt;
227 SYSTEMTIME st_local;
228 TIME_ZONE_INFORMATION tzi = *fTZI;
229 UErrorCode status = U_ZERO_ERROR;
230 const TimeZone &tz = cal.getTimeZone();
231 int64_t uct, uft;
232
233 setTimeZoneInfo(&tzi, tz);
234
235 uct = utmscale_fromInt64((int64_t) cal.getTime(status), UDTS_ICU4C_TIME, &status);
236 uft = utmscale_toInt64(uct, UDTS_WINDOWS_FILE_TIME, &status);
237
238 ft.dwLowDateTime = (DWORD) (uft & 0xFFFFFFFF);
239 ft.dwHighDateTime = (DWORD) ((uft >> 32) & 0xFFFFFFFF);
240
241 FileTimeToSystemTime(&ft, &st_gmt);
242 SystemTimeToTzSpecificLocalTime(&tzi, &st_gmt, &st_local);
243
244
245 if (fDateStyle != DateFormat::kNone && fTimeStyle != DateFormat::kNone) {
246 UnicodeString date;
247 UnicodeString time;
248 UnicodeString *pattern = fDateTimeMsg;
249
250 formatDate(&st_local, date);
251 formatTime(&st_local, time);
252
253 if (strcmp(fCalendar->getType(), cal.getType()) != 0) {
254 pattern = getTimeDateFormat(&cal, &fLocale, status);
255 }
256
257 SimpleFormatter(*pattern, 2, 2, status).format(time, date, appendTo, status);
258 } else if (fDateStyle != DateFormat::kNone) {
259 formatDate(&st_local, appendTo);
260 } else if (fTimeStyle != DateFormat::kNone) {
261 formatTime(&st_local, appendTo);
262 }
263
264 return appendTo;
265 }
266
parse(const UnicodeString &,Calendar &,ParsePosition & pos) const267 void Win32DateFormat::parse(const UnicodeString& /* text */, Calendar& /* cal */, ParsePosition& pos) const
268 {
269 pos.setErrorIndex(pos.getIndex());
270 }
271
adoptCalendar(Calendar * newCalendar)272 void Win32DateFormat::adoptCalendar(Calendar *newCalendar)
273 {
274 if (fCalendar == NULL || strcmp(fCalendar->getType(), newCalendar->getType()) != 0) {
275 UErrorCode status = U_ZERO_ERROR;
276
277 if (fDateStyle != DateFormat::kNone && fTimeStyle != DateFormat::kNone) {
278 delete fDateTimeMsg;
279 fDateTimeMsg = getTimeDateFormat(newCalendar, &fLocale, status);
280 }
281 }
282
283 delete fCalendar;
284 fCalendar = newCalendar;
285
286 fZoneID = setTimeZoneInfo(fTZI, fCalendar->getTimeZone());
287 }
288
setCalendar(const Calendar & newCalendar)289 void Win32DateFormat::setCalendar(const Calendar &newCalendar)
290 {
291 adoptCalendar(newCalendar.clone());
292 }
293
adoptTimeZone(TimeZone * zoneToAdopt)294 void Win32DateFormat::adoptTimeZone(TimeZone *zoneToAdopt)
295 {
296 fZoneID = setTimeZoneInfo(fTZI, *zoneToAdopt);
297 fCalendar->adoptTimeZone(zoneToAdopt);
298 }
299
setTimeZone(const TimeZone & zone)300 void Win32DateFormat::setTimeZone(const TimeZone& zone)
301 {
302 fZoneID = setTimeZoneInfo(fTZI, zone);
303 fCalendar->setTimeZone(zone);
304 }
305
306 static const DWORD dfFlags[] = {DATE_LONGDATE, DATE_LONGDATE, DATE_SHORTDATE, DATE_SHORTDATE};
307
formatDate(const SYSTEMTIME * st,UnicodeString & appendTo) const308 void Win32DateFormat::formatDate(const SYSTEMTIME *st, UnicodeString &appendTo) const
309 {
310 int result=0;
311 wchar_t stackBuffer[STACK_BUFFER_SIZE];
312 wchar_t *buffer = stackBuffer;
313 const wchar_t *localeName = nullptr;
314
315 if (fWindowsLocaleName != nullptr)
316 {
317 localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
318 }
319
320 result = GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, NULL, buffer, STACK_BUFFER_SIZE, NULL);
321
322 if (result == 0) {
323 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
324 int newLength = GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, NULL, NULL, 0, NULL);
325
326 buffer = NEW_ARRAY(wchar_t, newLength);
327
328 GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, NULL, buffer, newLength, NULL);
329 }
330 }
331
332 appendTo.append((const UChar *)buffer, (int32_t) wcslen(buffer));
333
334 if (buffer != stackBuffer) {
335 DELETE_ARRAY(buffer);
336 }
337 }
338
339 static const DWORD tfFlags[] = {0, 0, 0, TIME_NOSECONDS};
340
formatTime(const SYSTEMTIME * st,UnicodeString & appendTo) const341 void Win32DateFormat::formatTime(const SYSTEMTIME *st, UnicodeString &appendTo) const
342 {
343 int result;
344 wchar_t stackBuffer[STACK_BUFFER_SIZE];
345 wchar_t *buffer = stackBuffer;
346 const wchar_t *localeName = nullptr;
347
348 if (fWindowsLocaleName != nullptr)
349 {
350 localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
351 }
352
353 result = GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, NULL, buffer, STACK_BUFFER_SIZE);
354
355 if (result == 0) {
356 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
357 int newLength = GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, NULL, NULL, 0);
358
359 buffer = NEW_ARRAY(wchar_t, newLength);
360
361 GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, NULL, buffer, newLength);
362 }
363 }
364
365 appendTo.append((const UChar *)buffer, (int32_t) wcslen(buffer));
366
367 if (buffer != stackBuffer) {
368 DELETE_ARRAY(buffer);
369 }
370 }
371
setTimeZoneInfo(TIME_ZONE_INFORMATION * tzi,const TimeZone & zone) const372 UnicodeString Win32DateFormat::setTimeZoneInfo(TIME_ZONE_INFORMATION *tzi, const TimeZone &zone) const
373 {
374 UnicodeString zoneID;
375
376 zone.getID(zoneID);
377
378 if (zoneID.compare(fZoneID) != 0) {
379 UnicodeString icuid;
380
381 zone.getID(icuid);
382 if (! uprv_getWindowsTimeZoneInfo(tzi, icuid.getBuffer(), icuid.length())) {
383 UBool found = FALSE;
384 int32_t ec = TimeZone::countEquivalentIDs(icuid);
385
386 for (int z = 0; z < ec; z += 1) {
387 UnicodeString equiv = TimeZone::getEquivalentID(icuid, z);
388
389 found = uprv_getWindowsTimeZoneInfo(tzi, equiv.getBuffer(), equiv.length());
390 if (found) {
391 break;
392 }
393 }
394
395 if (! found) {
396 GetTimeZoneInformation(tzi);
397 }
398 }
399 }
400
401 return zoneID;
402 }
403
404 U_NAMESPACE_END
405
406 #endif /* #if !UCONFIG_NO_FORMATTING */
407
408 #endif // U_PLATFORM_USES_ONLY_WIN32_API
409
410