• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #if defined(WINVER) && (WINVER >= 0x0601)
102     UErrorCode status = U_ZERO_ERROR;
103     char asciiBCP47Tag[LOCALE_NAME_MAX_LENGTH] = {};
104 
105     // Convert from names like "en_CA" and "de_DE@collation=phonebook" to "en-CA" and "de-DE-u-co-phonebk".
106     (void)uloc_toLanguageTag(locale.getName(), asciiBCP47Tag, UPRV_LENGTHOF(asciiBCP47Tag), 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 #else
161     UErrorCode status = U_UNSUPPORTED_ERROR;
162     return status;
163 #endif
164 }
165 
166 // TODO: Range-check timeStyle, dateStyle
Win32DateFormat(DateFormat::EStyle timeStyle,DateFormat::EStyle dateStyle,const Locale & locale,UErrorCode & status)167 Win32DateFormat::Win32DateFormat(DateFormat::EStyle timeStyle, DateFormat::EStyle dateStyle, const Locale &locale, UErrorCode &status)
168   : DateFormat(), fDateTimeMsg(NULL), fTimeStyle(timeStyle), fDateStyle(dateStyle), fLocale(locale), fZoneID(), fWindowsLocaleName(nullptr)
169 {
170     if (U_SUCCESS(status)) {
171         GetEquivalentWindowsLocaleName(locale, &fWindowsLocaleName);
172         // Note: In the previous code, it would look up the LCID for the locale, and if
173         // the locale was not recognized then it would get an LCID of 0, which is a
174         // synonym for LOCALE_USER_DEFAULT on Windows.
175         // If the above method fails, then fWindowsLocaleName will remain as nullptr, and
176         // then we will pass nullptr to API GetLocaleInfoEx, which is the same as passing
177         // LOCALE_USER_DEFAULT.
178 
179         fTZI = NEW_ARRAY(TIME_ZONE_INFORMATION, 1);
180         uprv_memset(fTZI, 0, sizeof(TIME_ZONE_INFORMATION));
181         adoptCalendar(Calendar::createInstance(locale, status));
182     }
183 }
184 
Win32DateFormat(const Win32DateFormat & other)185 Win32DateFormat::Win32DateFormat(const Win32DateFormat &other)
186   : DateFormat(other)
187 {
188     *this = other;
189 }
190 
~Win32DateFormat()191 Win32DateFormat::~Win32DateFormat()
192 {
193 //    delete fCalendar;
194     uprv_free(fTZI);
195     delete fDateTimeMsg;
196     delete fWindowsLocaleName;
197 }
198 
operator =(const Win32DateFormat & other)199 Win32DateFormat &Win32DateFormat::operator=(const Win32DateFormat &other)
200 {
201     if (this == &other) { return *this; }  // self-assignment: no-op
202     // The following handles fCalendar
203     DateFormat::operator=(other);
204 
205 //    delete fCalendar;
206 
207     this->fDateTimeMsg = other.fDateTimeMsg == NULL ? NULL : new UnicodeString(*other.fDateTimeMsg);
208     this->fTimeStyle   = other.fTimeStyle;
209     this->fDateStyle   = other.fDateStyle;
210     this->fLocale      = other.fLocale;
211 //    this->fCalendar    = other.fCalendar->clone();
212     this->fZoneID      = other.fZoneID;
213 
214     this->fTZI = NEW_ARRAY(TIME_ZONE_INFORMATION, 1);
215     *this->fTZI = *other.fTZI;
216 
217     this->fWindowsLocaleName = other.fWindowsLocaleName == NULL ? NULL : new UnicodeString(*other.fWindowsLocaleName);
218 
219     return *this;
220 }
221 
clone() const222 Win32DateFormat *Win32DateFormat::clone() const
223 {
224     return new Win32DateFormat(*this);
225 }
226 
227 // TODO: Is just ignoring pos the right thing?
format(Calendar & cal,UnicodeString & appendTo,FieldPosition &) const228 UnicodeString &Win32DateFormat::format(Calendar &cal, UnicodeString &appendTo, FieldPosition & /* pos */) const
229 {
230     FILETIME ft;
231     SYSTEMTIME st_gmt;
232     SYSTEMTIME st_local;
233     TIME_ZONE_INFORMATION tzi = *fTZI;
234     UErrorCode status = U_ZERO_ERROR;
235     const TimeZone &tz = cal.getTimeZone();
236     int64_t uct, uft;
237 
238     setTimeZoneInfo(&tzi, tz);
239 
240     uct = utmscale_fromInt64((int64_t) cal.getTime(status), UDTS_ICU4C_TIME, &status);
241     uft = utmscale_toInt64(uct, UDTS_WINDOWS_FILE_TIME, &status);
242 
243     ft.dwLowDateTime =  (DWORD) (uft & 0xFFFFFFFF);
244     ft.dwHighDateTime = (DWORD) ((uft >> 32) & 0xFFFFFFFF);
245 
246     FileTimeToSystemTime(&ft, &st_gmt);
247     SystemTimeToTzSpecificLocalTime(&tzi, &st_gmt, &st_local);
248 
249 
250     if (fDateStyle != DateFormat::kNone && fTimeStyle != DateFormat::kNone) {
251         UnicodeString date;
252         UnicodeString time;
253         UnicodeString *pattern = fDateTimeMsg;
254 
255         formatDate(&st_local, date);
256         formatTime(&st_local, time);
257 
258         if (strcmp(fCalendar->getType(), cal.getType()) != 0) {
259             pattern = getTimeDateFormat(&cal, &fLocale, status);
260         }
261 
262         SimpleFormatter(*pattern, 2, 2, status).format(time, date, appendTo, status);
263     } else if (fDateStyle != DateFormat::kNone) {
264         formatDate(&st_local, appendTo);
265     } else if (fTimeStyle != DateFormat::kNone) {
266         formatTime(&st_local, appendTo);
267     }
268 
269     return appendTo;
270 }
271 
parse(const UnicodeString &,Calendar &,ParsePosition & pos) const272 void Win32DateFormat::parse(const UnicodeString& /* text */, Calendar& /* cal */, ParsePosition& pos) const
273 {
274     pos.setErrorIndex(pos.getIndex());
275 }
276 
adoptCalendar(Calendar * newCalendar)277 void Win32DateFormat::adoptCalendar(Calendar *newCalendar)
278 {
279     if (fCalendar == NULL || strcmp(fCalendar->getType(), newCalendar->getType()) != 0) {
280         UErrorCode status = U_ZERO_ERROR;
281 
282         if (fDateStyle != DateFormat::kNone && fTimeStyle != DateFormat::kNone) {
283             delete fDateTimeMsg;
284             fDateTimeMsg = getTimeDateFormat(newCalendar, &fLocale, status);
285         }
286     }
287 
288     delete fCalendar;
289     fCalendar = newCalendar;
290 
291     fZoneID = setTimeZoneInfo(fTZI, fCalendar->getTimeZone());
292 }
293 
setCalendar(const Calendar & newCalendar)294 void Win32DateFormat::setCalendar(const Calendar &newCalendar)
295 {
296     adoptCalendar(newCalendar.clone());
297 }
298 
adoptTimeZone(TimeZone * zoneToAdopt)299 void Win32DateFormat::adoptTimeZone(TimeZone *zoneToAdopt)
300 {
301     fZoneID = setTimeZoneInfo(fTZI, *zoneToAdopt);
302     fCalendar->adoptTimeZone(zoneToAdopt);
303 }
304 
setTimeZone(const TimeZone & zone)305 void Win32DateFormat::setTimeZone(const TimeZone& zone)
306 {
307     fZoneID = setTimeZoneInfo(fTZI, zone);
308     fCalendar->setTimeZone(zone);
309 }
310 
311 static const DWORD dfFlags[] = {DATE_LONGDATE, DATE_LONGDATE, DATE_SHORTDATE, DATE_SHORTDATE};
312 
formatDate(const SYSTEMTIME * st,UnicodeString & appendTo) const313 void Win32DateFormat::formatDate(const SYSTEMTIME *st, UnicodeString &appendTo) const
314 {
315     int result=0;
316     wchar_t stackBuffer[STACK_BUFFER_SIZE];
317     wchar_t *buffer = stackBuffer;
318     const wchar_t *localeName = nullptr;
319 
320     if (fWindowsLocaleName != nullptr)
321     {
322         localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
323     }
324 
325     result = GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, NULL, buffer, STACK_BUFFER_SIZE, NULL);
326 
327     if (result == 0) {
328         if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
329             int newLength = GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, NULL, NULL, 0, NULL);
330 
331             buffer = NEW_ARRAY(wchar_t, newLength);
332 
333             GetDateFormatEx(localeName, dfFlags[fDateStyle - kDateOffset], st, NULL, buffer, newLength, NULL);
334         }
335     }
336 
337     appendTo.append((const UChar *)buffer, (int32_t) wcslen(buffer));
338 
339     if (buffer != stackBuffer) {
340         DELETE_ARRAY(buffer);
341     }
342 }
343 
344 static const DWORD tfFlags[] = {0, 0, 0, TIME_NOSECONDS};
345 
formatTime(const SYSTEMTIME * st,UnicodeString & appendTo) const346 void Win32DateFormat::formatTime(const SYSTEMTIME *st, UnicodeString &appendTo) const
347 {
348     int result;
349     wchar_t stackBuffer[STACK_BUFFER_SIZE];
350     wchar_t *buffer = stackBuffer;
351     const wchar_t *localeName = nullptr;
352 
353     if (fWindowsLocaleName != nullptr)
354     {
355         localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
356     }
357 
358     result = GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, NULL, buffer, STACK_BUFFER_SIZE);
359 
360     if (result == 0) {
361         if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
362             int newLength = GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, NULL, NULL, 0);
363 
364             buffer = NEW_ARRAY(wchar_t, newLength);
365 
366             GetTimeFormatEx(localeName, tfFlags[fTimeStyle], st, NULL, buffer, newLength);
367         }
368     }
369 
370     appendTo.append((const UChar *)buffer, (int32_t) wcslen(buffer));
371 
372     if (buffer != stackBuffer) {
373         DELETE_ARRAY(buffer);
374     }
375 }
376 
setTimeZoneInfo(TIME_ZONE_INFORMATION * tzi,const TimeZone & zone) const377 UnicodeString Win32DateFormat::setTimeZoneInfo(TIME_ZONE_INFORMATION *tzi, const TimeZone &zone) const
378 {
379     UnicodeString zoneID;
380 
381     zone.getID(zoneID);
382 
383     if (zoneID.compare(fZoneID) != 0) {
384         UnicodeString icuid;
385 
386         zone.getID(icuid);
387         if (! uprv_getWindowsTimeZoneInfo(tzi, icuid.getBuffer(), icuid.length())) {
388             UBool found = FALSE;
389             int32_t ec = TimeZone::countEquivalentIDs(icuid);
390 
391             for (int z = 0; z < ec; z += 1) {
392                 UnicodeString equiv = TimeZone::getEquivalentID(icuid, z);
393 
394                 found = uprv_getWindowsTimeZoneInfo(tzi, equiv.getBuffer(), equiv.length());
395                 if (found) {
396                     break;
397                 }
398             }
399 
400             if (! found) {
401                 GetTimeZoneInformation(tzi);
402             }
403         }
404     }
405 
406     return zoneID;
407 }
408 
409 U_NAMESPACE_END
410 
411 #endif /* #if !UCONFIG_NO_FORMATTING */
412 
413 #endif // U_PLATFORM_USES_ONLY_WIN32_API
414 
415