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 WINNMFMT.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 "winnmfmt.h"
21
22 #include "unicode/format.h"
23 #include "unicode/numfmt.h"
24 #include "unicode/locid.h"
25 #include "unicode/ustring.h"
26
27 #include "cmemory.h"
28 #include "uassert.h"
29 #include "locmap.h"
30
31 #ifndef WIN32_LEAN_AND_MEAN
32 # define WIN32_LEAN_AND_MEAN
33 #endif
34 # define VC_EXTRALEAN
35 # define NOUSER
36 # define NOSERVICE
37 # define NOIME
38 # define NOMCX
39 #include <windows.h>
40 #include <stdio.h>
41
42 U_NAMESPACE_BEGIN
43
44 union FormatInfo
45 {
46 NUMBERFMTW number;
47 CURRENCYFMTW currency;
48 };
49
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Win32NumberFormat)50 UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Win32NumberFormat)
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 32
56
57 /*
58 * Turns a string of the form "3;2;0" into the grouping UINT
59 * needed for NUMBERFMT and CURRENCYFMT. If the string does not
60 * end in ";0" then the return value should be multiplied by 10.
61 * (e.g. "3" => 30, "3;2" => 320)
62 */
63 static UINT getGrouping(const wchar_t *grouping)
64 {
65 UINT g = 0;
66 const wchar_t *s;
67
68 for (s = grouping; *s != L'\0'; s += 1) {
69 if (*s > L'0' && *s < L'9') {
70 g = g * 10 + (*s - L'0');
71 } else if (*s != L';') {
72 break;
73 }
74 }
75
76 if (*s != L'0') {
77 g *= 10;
78 }
79
80 return g;
81 }
82
getNumberFormat(NUMBERFMTW * fmt,const wchar_t * windowsLocaleName)83 static void getNumberFormat(NUMBERFMTW *fmt, const wchar_t *windowsLocaleName)
84 {
85 wchar_t buf[10];
86
87 GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_IDIGITS, (LPWSTR) &fmt->NumDigits, sizeof(UINT));
88 GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_ILZERO, (LPWSTR) &fmt->LeadingZero, sizeof(UINT));
89
90 GetLocaleInfoEx(windowsLocaleName, LOCALE_SGROUPING, (LPWSTR)buf, 10);
91 fmt->Grouping = getGrouping(buf);
92
93 fmt->lpDecimalSep = NEW_ARRAY(wchar_t, 6);
94 GetLocaleInfoEx(windowsLocaleName, LOCALE_SDECIMAL, fmt->lpDecimalSep, 6);
95
96 fmt->lpThousandSep = NEW_ARRAY(wchar_t, 6);
97 GetLocaleInfoEx(windowsLocaleName, LOCALE_STHOUSAND, fmt->lpThousandSep, 6);
98
99 GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_INEGNUMBER, (LPWSTR) &fmt->NegativeOrder, sizeof(UINT));
100 }
101
freeNumberFormat(NUMBERFMTW * fmt)102 static void freeNumberFormat(NUMBERFMTW *fmt)
103 {
104 if (fmt != NULL) {
105 DELETE_ARRAY(fmt->lpThousandSep);
106 DELETE_ARRAY(fmt->lpDecimalSep);
107 }
108 }
109
getCurrencyFormat(CURRENCYFMTW * fmt,const wchar_t * windowsLocaleName)110 static void getCurrencyFormat(CURRENCYFMTW *fmt, const wchar_t *windowsLocaleName)
111 {
112 wchar_t buf[10];
113
114 GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_ICURRDIGITS, (LPWSTR) &fmt->NumDigits, sizeof(UINT));
115 GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_ILZERO, (LPWSTR) &fmt->LeadingZero, sizeof(UINT));
116
117 GetLocaleInfoEx(windowsLocaleName, LOCALE_SMONGROUPING, (LPWSTR)buf, sizeof(buf));
118 fmt->Grouping = getGrouping(buf);
119
120 fmt->lpDecimalSep = NEW_ARRAY(wchar_t, 6);
121 GetLocaleInfoEx(windowsLocaleName, LOCALE_SMONDECIMALSEP, fmt->lpDecimalSep, 6);
122
123 fmt->lpThousandSep = NEW_ARRAY(wchar_t, 6);
124 GetLocaleInfoEx(windowsLocaleName, LOCALE_SMONTHOUSANDSEP, fmt->lpThousandSep, 6);
125
126 GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_INEGCURR, (LPWSTR) &fmt->NegativeOrder, sizeof(UINT));
127 GetLocaleInfoEx(windowsLocaleName, LOCALE_RETURN_NUMBER|LOCALE_ICURRENCY, (LPWSTR) &fmt->PositiveOrder, sizeof(UINT));
128
129 fmt->lpCurrencySymbol = NEW_ARRAY(wchar_t, 8);
130 GetLocaleInfoEx(windowsLocaleName, LOCALE_SCURRENCY, (LPWSTR) fmt->lpCurrencySymbol, 8);
131 }
132
freeCurrencyFormat(CURRENCYFMTW * fmt)133 static void freeCurrencyFormat(CURRENCYFMTW *fmt)
134 {
135 if (fmt != NULL) {
136 DELETE_ARRAY(fmt->lpCurrencySymbol);
137 DELETE_ARRAY(fmt->lpThousandSep);
138 DELETE_ARRAY(fmt->lpDecimalSep);
139 }
140 }
141
142 // TODO: This is copied in both winnmfmt.cpp and windtfmt.cpp, but really should
143 // be factored out into a common helper for both.
GetEquivalentWindowsLocaleName(const Locale & locale,UnicodeString ** buffer)144 static UErrorCode GetEquivalentWindowsLocaleName(const Locale& locale, UnicodeString** buffer)
145 {
146 #if defined(WINVER) && (WINVER >= 0x0601)
147 UErrorCode status = U_ZERO_ERROR;
148 char asciiBCP47Tag[LOCALE_NAME_MAX_LENGTH] = {};
149
150 // Convert from names like "en_CA" and "de_DE@collation=phonebook" to "en-CA" and "de-DE-u-co-phonebk".
151 (void) uloc_toLanguageTag(locale.getName(), asciiBCP47Tag, UPRV_LENGTHOF(asciiBCP47Tag), FALSE, &status);
152
153 if (U_SUCCESS(status))
154 {
155 // Need it to be UTF-16, not 8-bit
156 // TODO: This seems like a good thing for a helper
157 wchar_t bcp47Tag[LOCALE_NAME_MAX_LENGTH] = {};
158 int32_t i;
159 for (i = 0; i < UPRV_LENGTHOF(bcp47Tag); i++)
160 {
161 if (asciiBCP47Tag[i] == '\0')
162 {
163 break;
164 }
165 else
166 {
167 // normally just copy the character
168 bcp47Tag[i] = static_cast<wchar_t>(asciiBCP47Tag[i]);
169 }
170 }
171
172 // Ensure it's null terminated
173 if (i < (UPRV_LENGTHOF(bcp47Tag) - 1))
174 {
175 bcp47Tag[i] = L'\0';
176 }
177 else
178 {
179 // Ran out of room.
180 bcp47Tag[UPRV_LENGTHOF(bcp47Tag) - 1] = L'\0';
181 }
182
183
184 wchar_t windowsLocaleName[LOCALE_NAME_MAX_LENGTH] = {};
185
186 // Note: On Windows versions below 10, there is no support for locale name aliases.
187 // This means that it will fail for locales where ICU has a completely different
188 // name (like ku vs ckb), and it will also not work for alternate sort locale
189 // names like "de-DE-u-co-phonebk".
190
191 // TODO: We could add some sort of exception table for cases like ku vs ckb.
192
193 int length = ResolveLocaleName(bcp47Tag, windowsLocaleName, UPRV_LENGTHOF(windowsLocaleName));
194
195 if (length > 0)
196 {
197 *buffer = new UnicodeString(windowsLocaleName);
198 }
199 else
200 {
201 status = U_UNSUPPORTED_ERROR;
202 }
203 }
204 return status;
205 #else
206 UErrorCode status = U_UNSUPPORTED_ERROR;
207 return status;
208 #endif
209 }
210
Win32NumberFormat(const Locale & locale,UBool currency,UErrorCode & status)211 Win32NumberFormat::Win32NumberFormat(const Locale &locale, UBool currency, UErrorCode &status)
212 : NumberFormat(), fCurrency(currency), fFormatInfo(NULL), fFractionDigitsSet(FALSE), fWindowsLocaleName(nullptr)
213 {
214 if (!U_FAILURE(status)) {
215 fLCID = locale.getLCID();
216
217 GetEquivalentWindowsLocaleName(locale, &fWindowsLocaleName);
218 // Note: In the previous code, it would look up the LCID for the locale, and if
219 // the locale was not recognized then it would get an LCID of 0, which is a
220 // synonym for LOCALE_USER_DEFAULT on Windows.
221 // If the above method fails, then fWindowsLocaleName will remain as nullptr, and
222 // then we will pass nullptr to API GetLocaleInfoEx, which is the same as passing
223 // LOCALE_USER_DEFAULT.
224
225 // Resolve actual locale to be used later
226 UErrorCode tmpsts = U_ZERO_ERROR;
227 char tmpLocID[ULOC_FULLNAME_CAPACITY];
228 int32_t len = uloc_getLocaleForLCID(fLCID, tmpLocID, UPRV_LENGTHOF(tmpLocID) - 1, &tmpsts);
229 if (U_SUCCESS(tmpsts)) {
230 tmpLocID[len] = 0;
231 fLocale = Locale((const char*)tmpLocID);
232 }
233
234 const wchar_t *localeName = nullptr;
235
236 if (fWindowsLocaleName != nullptr)
237 {
238 localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
239 }
240
241 fFormatInfo = (FormatInfo*)uprv_malloc(sizeof(FormatInfo));
242
243 if (fCurrency) {
244 getCurrencyFormat(&fFormatInfo->currency, localeName);
245 } else {
246 getNumberFormat(&fFormatInfo->number, localeName);
247 }
248 }
249 }
250
Win32NumberFormat(const Win32NumberFormat & other)251 Win32NumberFormat::Win32NumberFormat(const Win32NumberFormat &other)
252 : NumberFormat(other), fFormatInfo((FormatInfo*)uprv_malloc(sizeof(FormatInfo)))
253 {
254 if (fFormatInfo != NULL) {
255 uprv_memset(fFormatInfo, 0, sizeof(*fFormatInfo));
256 }
257 *this = other;
258 }
259
~Win32NumberFormat()260 Win32NumberFormat::~Win32NumberFormat()
261 {
262 if (fFormatInfo != NULL) {
263 if (fCurrency) {
264 freeCurrencyFormat(&fFormatInfo->currency);
265 } else {
266 freeNumberFormat(&fFormatInfo->number);
267 }
268
269 uprv_free(fFormatInfo);
270 }
271 delete fWindowsLocaleName;
272 }
273
operator =(const Win32NumberFormat & other)274 Win32NumberFormat &Win32NumberFormat::operator=(const Win32NumberFormat &other)
275 {
276 if (this == &other) { return *this; } // self-assignment: no-op
277 NumberFormat::operator=(other);
278
279 this->fCurrency = other.fCurrency;
280 this->fLocale = other.fLocale;
281 this->fLCID = other.fLCID;
282 this->fFractionDigitsSet = other.fFractionDigitsSet;
283 this->fWindowsLocaleName = other.fWindowsLocaleName == NULL ? NULL : new UnicodeString(*other.fWindowsLocaleName);
284
285 const wchar_t *localeName = nullptr;
286
287 if (fWindowsLocaleName != nullptr)
288 {
289 localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
290 }
291
292 if (fCurrency) {
293 freeCurrencyFormat(&fFormatInfo->currency);
294 getCurrencyFormat(&fFormatInfo->currency, localeName);
295 } else {
296 freeNumberFormat(&fFormatInfo->number);
297 getNumberFormat(&fFormatInfo->number, localeName);
298 }
299
300 return *this;
301 }
302
clone() const303 Win32NumberFormat *Win32NumberFormat::clone() const
304 {
305 return new Win32NumberFormat(*this);
306 }
307
format(double number,UnicodeString & appendTo,FieldPosition &) const308 UnicodeString& Win32NumberFormat::format(double number, UnicodeString& appendTo, FieldPosition& /* pos */) const
309 {
310 return format(getMaximumFractionDigits(), appendTo, L"%.16f", number);
311 }
312
format(int32_t number,UnicodeString & appendTo,FieldPosition &) const313 UnicodeString& Win32NumberFormat::format(int32_t number, UnicodeString& appendTo, FieldPosition& /* pos */) const
314 {
315 return format(getMinimumFractionDigits(), appendTo, L"%I32d", number);
316 }
317
format(int64_t number,UnicodeString & appendTo,FieldPosition &) const318 UnicodeString& Win32NumberFormat::format(int64_t number, UnicodeString& appendTo, FieldPosition& /* pos */) const
319 {
320 return format(getMinimumFractionDigits(), appendTo, L"%I64d", number);
321 }
322
parse(const UnicodeString & text,Formattable & result,ParsePosition & parsePosition) const323 void Win32NumberFormat::parse(const UnicodeString& text, Formattable& result, ParsePosition& parsePosition) const
324 {
325 UErrorCode status = U_ZERO_ERROR;
326 NumberFormat *nf = fCurrency? NumberFormat::createCurrencyInstance(fLocale, status) : NumberFormat::createInstance(fLocale, status);
327
328 nf->parse(text, result, parsePosition);
329 delete nf;
330 }
setMaximumFractionDigits(int32_t newValue)331 void Win32NumberFormat::setMaximumFractionDigits(int32_t newValue)
332 {
333 fFractionDigitsSet = TRUE;
334 NumberFormat::setMaximumFractionDigits(newValue);
335 }
336
setMinimumFractionDigits(int32_t newValue)337 void Win32NumberFormat::setMinimumFractionDigits(int32_t newValue)
338 {
339 fFractionDigitsSet = TRUE;
340 NumberFormat::setMinimumFractionDigits(newValue);
341 }
342
format(int32_t numDigits,UnicodeString & appendTo,const wchar_t * fmt,...) const343 UnicodeString &Win32NumberFormat::format(int32_t numDigits, UnicodeString &appendTo, const wchar_t *fmt, ...) const
344 {
345 wchar_t nStackBuffer[STACK_BUFFER_SIZE];
346 wchar_t *nBuffer = nStackBuffer;
347 va_list args;
348 int result;
349
350 nBuffer[0] = 0x0000;
351
352 /* Due to the arguments causing a result to be <= 23 characters (+2 for NULL and minus),
353 we don't need to reallocate the buffer. */
354 va_start(args, fmt);
355 result = _vsnwprintf(nBuffer, STACK_BUFFER_SIZE, fmt, args);
356 va_end(args);
357
358 /* Just to make sure of the above statement, we add this assert */
359 U_ASSERT(result >=0);
360 // The following code is not used because _vscwprintf isn't available on MinGW at the moment.
361 /*if (result < 0) {
362 int newLength;
363
364 va_start(args, fmt);
365 newLength = _vscwprintf(fmt, args);
366 va_end(args);
367
368 nBuffer = NEW_ARRAY(UChar, newLength + 1);
369
370 va_start(args, fmt);
371 result = _vsnwprintf(nBuffer, newLength + 1, fmt, args);
372 va_end(args);
373 }*/
374
375 // vswprintf is sensitive to the locale set by setlocale. For some locales
376 // it doesn't use "." as the decimal separator, which is what GetNumberFormatW
377 // and GetCurrencyFormatW both expect to see.
378 //
379 // To fix this, we scan over the string and replace the first non-digits, except
380 // for a leading "-", with a "."
381 //
382 // Note: (nBuffer[0] == L'-') will evaluate to 1 if there is a leading '-' in the
383 // number, and 0 otherwise.
384 for (wchar_t *p = &nBuffer[nBuffer[0] == L'-']; *p != L'\0'; p += 1) {
385 if (*p < L'0' || *p > L'9') {
386 *p = L'.';
387 break;
388 }
389 }
390
391 wchar_t stackBuffer[STACK_BUFFER_SIZE];
392 wchar_t *buffer = stackBuffer;
393 FormatInfo formatInfo;
394
395 formatInfo = *fFormatInfo;
396 buffer[0] = 0x0000;
397
398 const wchar_t *localeName = nullptr;
399
400 if (fWindowsLocaleName != nullptr)
401 {
402 localeName = reinterpret_cast<const wchar_t*>(toOldUCharPtr(fWindowsLocaleName->getTerminatedBuffer()));
403 }
404
405 if (fCurrency) {
406 if (fFractionDigitsSet) {
407 formatInfo.currency.NumDigits = (UINT) numDigits;
408 }
409
410 if (!isGroupingUsed()) {
411 formatInfo.currency.Grouping = 0;
412 }
413
414 result = GetCurrencyFormatEx(localeName, 0, nBuffer, &formatInfo.currency, buffer, STACK_BUFFER_SIZE);
415
416 if (result == 0) {
417 DWORD lastError = GetLastError();
418
419 if (lastError == ERROR_INSUFFICIENT_BUFFER) {
420 int newLength = GetCurrencyFormatEx(localeName, 0, nBuffer, &formatInfo.currency, NULL, 0);
421
422 buffer = NEW_ARRAY(wchar_t, newLength);
423 buffer[0] = 0x0000;
424 GetCurrencyFormatEx(localeName, 0, nBuffer, &formatInfo.currency, buffer, newLength);
425 }
426 }
427 } else {
428 if (fFractionDigitsSet) {
429 formatInfo.number.NumDigits = (UINT) numDigits;
430 }
431
432 if (!isGroupingUsed()) {
433 formatInfo.number.Grouping = 0;
434 }
435
436 result = GetNumberFormatEx(localeName, 0, nBuffer, &formatInfo.number, buffer, STACK_BUFFER_SIZE);
437
438 if (result == 0) {
439 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
440 int newLength = GetNumberFormatEx(localeName, 0, nBuffer, &formatInfo.number, NULL, 0);
441
442 buffer = NEW_ARRAY(wchar_t, newLength);
443 buffer[0] = 0x0000;
444 GetNumberFormatEx(localeName, 0, nBuffer, &formatInfo.number, buffer, newLength);
445 }
446 }
447 }
448
449 appendTo.append((UChar *)buffer, (int32_t) wcslen(buffer));
450
451 if (buffer != stackBuffer) {
452 DELETE_ARRAY(buffer);
453 }
454
455 /*if (nBuffer != nStackBuffer) {
456 DELETE_ARRAY(nBuffer);
457 }*/
458
459 return appendTo;
460 }
461
462 U_NAMESPACE_END
463
464 #endif /* #if !UCONFIG_NO_FORMATTING */
465
466 #endif // U_PLATFORM_USES_ONLY_WIN32_API
467