winedbg: Don't dereference possibly NULL thread pointer.
[wine/zf.git] / dlls / oleaut32 / varformat.c
blob8ed8f790d144de663c83ef4b9be4941759bc5957
1 /*
2 * Variant formatting functions
4 * Copyright 2008 Damjan Jovanovic
5 * Copyright 2003 Jon Griffiths
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * NOTES
22 * Since the formatting functions aren't properly documented, I used the
23 * Visual Basic documentation as a guide to implementing these functions. This
24 * means that some named or user-defined formats may work slightly differently.
25 * Please submit a test case if you find a difference.
28 #include <string.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
33 #include "windef.h"
34 #include "winbase.h"
35 #include "winerror.h"
36 #include "variant.h"
37 #include "wine/debug.h"
39 WINE_DEFAULT_DEBUG_CHANNEL(variant);
41 /* Make sure internal conversions to strings use the '.','+'/'-' and ','
42 * format chars from the US locale. This enables us to parse the created
43 * strings to determine the number of decimal places, exponent, etc.
45 #define LCID_US MAKELCID(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),SORT_DEFAULT)
47 /******************************************************************************
48 * Variant-Formats {OLEAUT32}
50 * NOTES
51 * When formatting a variant a variety of format strings may be used to generate
52 * different kinds of formatted output. A format string consists of either a named
53 * format, or a user-defined format.
55 * The following named formats are defined:
56 *| Name Description
57 *| ---- -----------
58 *| General Date Display Date, and time for non-integer values
59 *| Short Date Short date format as defined by locale settings
60 *| Medium Date Medium date format as defined by locale settings
61 *| Long Date Long date format as defined by locale settings
62 *| Short Time Short Time format as defined by locale settings
63 *| Medium Time Medium time format as defined by locale settings
64 *| Long Time Long time format as defined by locale settings
65 *| True/False Localised text of "True" or "False"
66 *| Yes/No Localised text of "Yes" or "No"
67 *| On/Off Localised text of "On" or "Off"
68 *| General Number No thousands separator. No decimal points for integers
69 *| Currency General currency format using localised characters
70 *| Fixed At least one whole and two fractional digits
71 *| Standard Same as 'Fixed', but including decimal separators
72 *| Percent Multiply by 100 and display a trailing '%' character
73 *| Scientific Display with exponent
75 * User-defined formats consist of a combination of tokens and literal
76 * characters. Literal characters are copied unmodified to the formatted
77 * output at the position they occupy in the format string. Any character
78 * that is not recognised as a token is treated as a literal. A literal can
79 * also be specified by preceding it with a backslash character
80 * (e.g. "\L\i\t\e\r\a\l") or enclosing it in double quotes.
82 * A user-defined format can have up to 4 sections, depending on the type of
83 * format. The following table lists sections and their meaning:
84 *| Format Type Sections Meaning
85 *| ----------- -------- -------
86 *| Number 1 Use the same format for all numbers
87 *| Number 2 Use format 1 for positive and 2 for negative numbers
88 *| Number 3 Use format 1 for positive, 2 for zero, and 3
89 *| for negative numbers.
90 *| Number 4 Use format 1 for positive, 2 for zero, 3 for
91 *| negative, and 4 for null numbers.
92 *| String 1 Use the same format for all strings
93 *| String 2 Use format 2 for null and empty strings, otherwise
94 *| use format 1.
95 *| Date 1 Use the same format for all dates
97 * The formatting tokens fall into several categories depending on the type
98 * of formatted output. For more information on each type, see
99 * VarFormat-Dates(), VarFormat-Strings() and VarFormat-Numbers().
101 * SEE ALSO
102 * VarTokenizeFormatString(), VarFormatFromTokens(), VarFormat(),
103 * VarFormatDateTime(), VarFormatNumber(), VarFormatCurrency().
106 /******************************************************************************
107 * VarFormat-Strings {OLEAUT32}
109 * NOTES
110 * When formatting a variant as a string, it is first converted to a VT_BSTR.
111 * The user-format string defines which characters are copied into which
112 * positions in the output string. Literals may be inserted in the format
113 * string. When creating the formatted string, excess characters in the string
114 * (those not consumed by a token) are appended to the end of the output. If
115 * there are more tokens than characters in the string to format, spaces will
116 * be inserted at the start of the string if the '@' token was used.
118 * By default strings are converted to lowercase, or uppercase if the '>' token
119 * is encountered. This applies to the whole string: it is not possible to
120 * generate a mixed-case output string.
122 * In user-defined string formats, the following tokens are recognised:
123 *| Token Description
124 *| ----- -----------
125 *| '@' Copy a char from the source, or a space if no chars are left.
126 *| '&' Copy a char from the source, or write nothing if no chars are left.
127 *| '<' Output the whole string as lower-case (the default).
128 *| '>' Output the whole string as upper-case.
129 *| '!' MSDN indicates that this character should cause right-to-left
130 *| copying, however tests show that it is tokenised but not processed.
134 * Common format definitions
137 /* Format types */
138 #define FMT_TYPE_UNKNOWN 0x0
139 #define FMT_TYPE_GENERAL 0x1
140 #define FMT_TYPE_NUMBER 0x2
141 #define FMT_TYPE_DATE 0x3
142 #define FMT_TYPE_STRING 0x4
144 #define FMT_TO_STRING 0x0 /* If header->size == this, act like VB's Str() fn */
146 typedef struct tagFMT_SHORT_HEADER
148 BYTE size; /* Size of tokenised block (including header), or FMT_TO_STRING */
149 BYTE type; /* Allowable types (FMT_TYPE_*) */
150 BYTE offset[1]; /* Offset of the first (and only) format section */
151 } FMT_SHORT_HEADER;
153 typedef struct tagFMT_HEADER
155 BYTE size; /* Total size of the whole tokenised block (including header) */
156 BYTE type; /* Allowable types (FMT_TYPE_*) */
157 BYTE starts[4]; /* Offset of each of the 4 format sections, or 0 if none */
158 } FMT_HEADER;
160 #define FmtGetPositive(x) (x->starts[0])
161 #define FmtGetNegative(x) (x->starts[1] ? x->starts[1] : x->starts[0])
162 #define FmtGetZero(x) (x->starts[2] ? x->starts[2] : x->starts[0])
163 #define FmtGetNull(x) (x->starts[3] ? x->starts[3] : x->starts[0])
166 * String formats
169 #define FMT_FLAG_LT 0x1 /* Has '<' (lower case) */
170 #define FMT_FLAG_GT 0x2 /* Has '>' (upper case) */
171 #define FMT_FLAG_RTL 0x4 /* Has '!' (Copy right to left) */
173 typedef struct tagFMT_STRING_HEADER
175 BYTE flags; /* LT, GT, RTL */
176 BYTE unknown1;
177 BYTE unknown2;
178 BYTE copy_chars; /* Number of chars to be copied */
179 BYTE unknown3;
180 } FMT_STRING_HEADER;
183 * Number formats
186 #define FMT_FLAG_PERCENT 0x1 /* Has '%' (Percentage) */
187 #define FMT_FLAG_EXPONENT 0x2 /* Has 'e' (Exponent/Scientific notation) */
188 #define FMT_FLAG_THOUSANDS 0x4 /* Has ',' (Standard use of the thousands separator) */
189 #define FMT_FLAG_BOOL 0x20 /* Boolean format */
191 typedef struct tagFMT_NUMBER_HEADER
193 BYTE flags; /* PERCENT, EXPONENT, THOUSANDS, BOOL */
194 BYTE multiplier; /* Multiplier, 100 for percentages */
195 BYTE divisor; /* Divisor, 1000 if '%%' was used */
196 BYTE whole; /* Number of digits before the decimal point */
197 BYTE fractional; /* Number of digits after the decimal point */
198 } FMT_NUMBER_HEADER;
201 * Date Formats
203 typedef struct tagFMT_DATE_HEADER
205 BYTE flags;
206 BYTE unknown1;
207 BYTE unknown2;
208 BYTE unknown3;
209 BYTE unknown4;
210 } FMT_DATE_HEADER;
213 * Format token values
215 #define FMT_GEN_COPY 0x00 /* \n, "lit" => 0,pos,len: Copy len chars from input+pos */
216 #define FMT_GEN_INLINE 0x01 /* => 1,len,[chars]: Copy len chars from token stream */
217 #define FMT_GEN_END 0x02 /* \0,; => 2: End of the tokenised format */
218 #define FMT_DATE_TIME_SEP 0x03 /* Time separator char */
219 #define FMT_DATE_DATE_SEP 0x04 /* Date separator char */
220 #define FMT_DATE_GENERAL 0x05 /* General format date */
221 #define FMT_DATE_QUARTER 0x06 /* Quarter of the year from 1-4 */
222 #define FMT_DATE_TIME_SYS 0x07 /* System long time format */
223 #define FMT_DATE_DAY 0x08 /* Day with no leading 0 */
224 #define FMT_DATE_DAY_0 0x09 /* Day with leading 0 */
225 #define FMT_DATE_DAY_SHORT 0x0A /* Short day name */
226 #define FMT_DATE_DAY_LONG 0x0B /* Long day name */
227 #define FMT_DATE_SHORT 0x0C /* Short date format */
228 #define FMT_DATE_LONG 0x0D /* Long date format */
229 #define FMT_DATE_MEDIUM 0x0E /* Medium date format */
230 #define FMT_DATE_DAY_WEEK 0x0F /* First day of the week */
231 #define FMT_DATE_WEEK_YEAR 0x10 /* First week of the year */
232 #define FMT_DATE_MON 0x11 /* Month with no leading 0 */
233 #define FMT_DATE_MON_0 0x12 /* Month with leading 0 */
234 #define FMT_DATE_MON_SHORT 0x13 /* Short month name */
235 #define FMT_DATE_MON_LONG 0x14 /* Long month name */
236 #define FMT_DATE_YEAR_DOY 0x15 /* Day of the year with no leading 0 */
237 #define FMT_DATE_YEAR_0 0x16 /* 2 digit year with leading 0 */
238 /* NOTE: token 0x17 is not defined, 'yyy' is not valid */
239 #define FMT_DATE_YEAR_LONG 0x18 /* 4 digit year */
240 #define FMT_DATE_MIN 0x1A /* Minutes with no leading 0 */
241 #define FMT_DATE_MIN_0 0x1B /* Minutes with leading 0 */
242 #define FMT_DATE_SEC 0x1C /* Seconds with no leading 0 */
243 #define FMT_DATE_SEC_0 0x1D /* Seconds with leading 0 */
244 #define FMT_DATE_HOUR 0x1E /* Hours with no leading 0 */
245 #define FMT_DATE_HOUR_0 0x1F /* Hours with leading 0 */
246 #define FMT_DATE_HOUR_12 0x20 /* Hours with no leading 0, 12 hour clock */
247 #define FMT_DATE_HOUR_12_0 0x21 /* Hours with leading 0, 12 hour clock */
248 #define FMT_DATE_TIME_UNK2 0x23 /* same as FMT_DATE_HOUR_0, for "short time" format */
249 /* FIXME: probably missing some here */
250 #define FMT_DATE_AMPM_SYS1 0x2E /* AM/PM as defined by system settings */
251 #define FMT_DATE_AMPM_UPPER 0x2F /* Upper-case AM or PM */
252 #define FMT_DATE_A_UPPER 0x30 /* Upper-case A or P */
253 #define FMT_DATE_AMPM_SYS2 0x31 /* AM/PM as defined by system settings */
254 #define FMT_DATE_AMPM_LOWER 0x32 /* Lower-case AM or PM */
255 #define FMT_DATE_A_LOWER 0x33 /* Lower-case A or P */
256 #define FMT_NUM_COPY_ZERO 0x34 /* Copy 1 digit or 0 if no digit */
257 #define FMT_NUM_COPY_SKIP 0x35 /* Copy 1 digit or skip if no digit */
258 #define FMT_NUM_DECIMAL 0x36 /* Decimal separator */
259 #define FMT_NUM_EXP_POS_U 0x37 /* Scientific notation, uppercase, + sign */
260 #define FMT_NUM_EXP_NEG_U 0x38 /* Scientific notation, uppercase, - sign */
261 #define FMT_NUM_EXP_POS_L 0x39 /* Scientific notation, lowercase, + sign */
262 #define FMT_NUM_EXP_NEG_L 0x3A /* Scientific notation, lowercase, - sign */
263 #define FMT_NUM_CURRENCY 0x3B /* Currency symbol */
264 #define FMT_NUM_TRUE_FALSE 0x3D /* Convert to "True" or "False" */
265 #define FMT_NUM_YES_NO 0x3E /* Convert to "Yes" or "No" */
266 #define FMT_NUM_ON_OFF 0x3F /* Convert to "On" or "Off" */
267 #define FMT_STR_COPY_SPACE 0x40 /* Copy len chars with space if no char */
268 #define FMT_STR_COPY_SKIP 0x41 /* Copy len chars or skip if no char */
270 /* Named Formats and their tokenised values */
271 static const BYTE fmtGeneralDate[0x0a] =
273 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
274 0x0,0x0,0x0,0x0,0x0,
275 FMT_DATE_GENERAL,FMT_GEN_END
278 static const BYTE fmtShortDate[0x0a] =
280 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
281 0x0,0x0,0x0,0x0,0x0,
282 FMT_DATE_SHORT,FMT_GEN_END
285 static const BYTE fmtMediumDate[0x0a] =
287 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
288 0x0,0x0,0x0,0x0,0x0,
289 FMT_DATE_MEDIUM,FMT_GEN_END
292 static const BYTE fmtLongDate[0x0a] =
294 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
295 0x0,0x0,0x0,0x0,0x0,
296 FMT_DATE_LONG,FMT_GEN_END
299 static const BYTE fmtShortTime[0x0c] =
301 0x0c,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
302 0x0,0x0,0x0,0x0,0x0,
303 FMT_DATE_TIME_UNK2,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,FMT_GEN_END
306 static const BYTE fmtMediumTime[0x11] =
308 0x11,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
309 0x0,0x0,0x0,0x0,0x0,
310 FMT_DATE_HOUR_12_0,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,
311 FMT_GEN_INLINE,0x01,' ','\0',FMT_DATE_AMPM_SYS1,FMT_GEN_END
314 static const BYTE fmtLongTime[0x0d] =
316 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
317 0x0,0x0,0x0,0x0,0x0,
318 FMT_DATE_TIME_SYS,FMT_GEN_END
321 static const BYTE fmtTrueFalse[0x0d] =
323 0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
324 FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
325 FMT_NUM_TRUE_FALSE,FMT_GEN_END
328 static const BYTE fmtYesNo[0x0d] =
330 0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
331 FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
332 FMT_NUM_YES_NO,FMT_GEN_END
335 static const BYTE fmtOnOff[0x0d] =
337 0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
338 FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
339 FMT_NUM_ON_OFF,FMT_GEN_END
342 static const BYTE fmtGeneralNumber[sizeof(FMT_HEADER)] =
344 sizeof(FMT_HEADER),FMT_TYPE_GENERAL,sizeof(FMT_HEADER),0x0,0x0,0x0
347 static const BYTE fmtCurrency[0x26] =
349 0x26,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x12,0x0,0x0,
350 /* Positive numbers */
351 FMT_FLAG_THOUSANDS,0xcc,0x0,0x1,0x2,
352 FMT_NUM_CURRENCY,FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,
353 FMT_GEN_END,
354 /* Negative numbers */
355 FMT_FLAG_THOUSANDS,0xcc,0x0,0x1,0x2,
356 FMT_GEN_INLINE,0x1,'(','\0',FMT_NUM_CURRENCY,FMT_NUM_COPY_ZERO,0x1,
357 FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_INLINE,0x1,')','\0',
358 FMT_GEN_END
361 static const BYTE fmtFixed[0x11] =
363 0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
364 0x0,0x0,0x0,0x1,0x2,
365 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
368 static const BYTE fmtStandard[0x11] =
370 0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
371 FMT_FLAG_THOUSANDS,0x0,0x0,0x1,0x2,
372 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
375 static const BYTE fmtPercent[0x15] =
377 0x15,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
378 FMT_FLAG_PERCENT,0x1,0x0,0x1,0x2,
379 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,
380 FMT_GEN_INLINE,0x1,'%','\0',FMT_GEN_END
383 static const BYTE fmtScientific[0x13] =
385 0x13,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
386 FMT_FLAG_EXPONENT,0x0,0x0,0x1,0x2,
387 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_NUM_EXP_POS_U,0x2,FMT_GEN_END
390 typedef struct tagNAMED_FORMAT
392 LPCWSTR name;
393 const BYTE* format;
394 } NAMED_FORMAT;
396 /* Format name to tokenised format. Must be kept sorted by name */
397 static const NAMED_FORMAT VARIANT_NamedFormats[] =
399 { L"Currency", fmtCurrency },
400 { L"Fixed", fmtFixed },
401 { L"General Date", fmtGeneralDate },
402 { L"General Number", fmtGeneralNumber },
403 { L"Long Date", fmtLongDate },
404 { L"Long Time", fmtLongTime },
405 { L"Medium Date", fmtMediumDate },
406 { L"Medium Time", fmtMediumTime },
407 { L"On/Off", fmtOnOff },
408 { L"Percent", fmtPercent },
409 { L"Scientific", fmtScientific },
410 { L"Short Date", fmtShortDate },
411 { L"Short Time", fmtShortTime },
412 { L"Standard", fmtStandard },
413 { L"True/False", fmtTrueFalse },
414 { L"Yes/No", fmtYesNo }
416 typedef const NAMED_FORMAT *LPCNAMED_FORMAT;
418 static int __cdecl FormatCompareFn(const void *l, const void *r)
420 return wcsicmp(((LPCNAMED_FORMAT)l)->name, ((LPCNAMED_FORMAT)r)->name);
423 static inline const BYTE *VARIANT_GetNamedFormat(LPCWSTR lpszFormat)
425 NAMED_FORMAT key;
426 LPCNAMED_FORMAT fmt;
428 key.name = lpszFormat;
429 fmt = bsearch(&key, VARIANT_NamedFormats, ARRAY_SIZE(VARIANT_NamedFormats),
430 sizeof(NAMED_FORMAT), FormatCompareFn);
431 return fmt ? fmt->format : NULL;
434 /* Return an error if the token for the value will not fit in the destination */
435 #define NEED_SPACE(x) if (cbTok < (int)(x)) return TYPE_E_BUFFERTOOSMALL; cbTok -= (x)
437 /* Non-zero if the format is unknown or a given type */
438 #define COULD_BE(typ) ((!fmt_number && header->type==FMT_TYPE_UNKNOWN)||header->type==typ)
440 /* State during tokenising */
441 #define FMT_STATE_OPEN_COPY 0x1 /* Last token written was a copy */
442 #define FMT_STATE_WROTE_DECIMAL 0x2 /* Already wrote a decimal separator */
443 #define FMT_STATE_SEEN_HOURS 0x4 /* See the hh specifier */
444 #define FMT_STATE_WROTE_MINUTES 0x8 /* Wrote minutes */
446 /**********************************************************************
447 * VarTokenizeFormatString [OLEAUT32.140]
449 * Convert a format string into tokenised form.
451 * PARAMS
452 * lpszFormat [I] Format string to tokenise
453 * rgbTok [O] Destination for tokenised format
454 * cbTok [I] Size of rgbTok in bytes
455 * nFirstDay [I] First day of the week (1-7, or 0 for current system default)
456 * nFirstWeek [I] How to treat the first week (see notes)
457 * lcid [I] Locale Id of the format string
458 * pcbActual [O] If non-NULL, filled with the first token generated
460 * RETURNS
461 * Success: S_OK. rgbTok contains the tokenised format.
462 * Failure: E_INVALIDARG, if any argument is invalid.
463 * TYPE_E_BUFFERTOOSMALL, if rgbTok is not large enough.
465 * NOTES
466 * Valid values for the nFirstWeek parameter are:
467 *| Value Meaning
468 *| ----- -------
469 *| 0 Use the current system default
470 *| 1 The first week is that containing Jan 1
471 *| 2 Four or more days of the first week are in the current year
472 *| 3 The first week is 7 days long
473 * See Variant-Formats(), VarFormatFromTokens().
475 HRESULT WINAPI VarTokenizeFormatString(LPOLESTR lpszFormat, LPBYTE rgbTok,
476 int cbTok, int nFirstDay, int nFirstWeek,
477 LCID lcid, int *pcbActual)
479 /* Note: none of these strings should be NUL terminated */
480 static const WCHAR szTTTTT[] = { 't','t','t','t','t' };
481 static const WCHAR szAMPM[] = { 'A','M','P','M' };
482 static const WCHAR szampm[] = { 'a','m','p','m' };
483 static const WCHAR szAMSlashPM[] = { 'A','M','/','P','M' };
484 static const WCHAR szamSlashpm[] = { 'a','m','/','p','m' };
485 const BYTE *namedFmt;
486 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
487 FMT_STRING_HEADER *str_header = (FMT_STRING_HEADER*)(rgbTok + sizeof(FMT_HEADER));
488 FMT_NUMBER_HEADER *num_header = (FMT_NUMBER_HEADER*)str_header;
489 BYTE* pOut = rgbTok + sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER);
490 BYTE* pLastHours = NULL;
491 BYTE fmt_number = 0;
492 DWORD fmt_state = 0;
493 LPCWSTR pFormat = lpszFormat;
495 TRACE("(%s,%p,%d,%d,%d,0x%08x,%p)\n", debugstr_w(lpszFormat), rgbTok, cbTok,
496 nFirstDay, nFirstWeek, lcid, pcbActual);
498 if (!rgbTok ||
499 nFirstDay < 0 || nFirstDay > 7 || nFirstWeek < 0 || nFirstWeek > 3)
500 return E_INVALIDARG;
502 if (!lpszFormat || !*lpszFormat)
504 /* An empty string means 'general format' */
505 NEED_SPACE(sizeof(BYTE));
506 *rgbTok = FMT_TO_STRING;
507 if (pcbActual)
508 *pcbActual = FMT_TO_STRING;
509 return S_OK;
512 if (cbTok > 255)
513 cbTok = 255; /* Ensure we error instead of wrapping */
515 /* Named formats */
516 namedFmt = VARIANT_GetNamedFormat(lpszFormat);
517 if (namedFmt)
519 NEED_SPACE(namedFmt[0]);
520 memcpy(rgbTok, namedFmt, namedFmt[0]);
521 TRACE("Using pre-tokenised named format %s\n", debugstr_w(lpszFormat));
522 /* FIXME: pcbActual */
523 return S_OK;
526 /* Insert header */
527 NEED_SPACE(sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER));
528 memset(header, 0, sizeof(FMT_HEADER));
529 memset(str_header, 0, sizeof(FMT_STRING_HEADER));
531 header->starts[fmt_number] = sizeof(FMT_HEADER);
533 while (*pFormat)
535 /* --------------
536 * General tokens
537 * --------------
539 if (*pFormat == ';')
541 while (*pFormat == ';')
543 TRACE(";\n");
544 if (++fmt_number > 3)
545 return E_INVALIDARG; /* too many formats */
546 pFormat++;
548 if (*pFormat)
550 TRACE("New header\n");
551 NEED_SPACE(sizeof(BYTE) + sizeof(FMT_STRING_HEADER));
552 *pOut++ = FMT_GEN_END;
554 header->starts[fmt_number] = pOut - rgbTok;
555 str_header = (FMT_STRING_HEADER*)pOut;
556 num_header = (FMT_NUMBER_HEADER*)pOut;
557 memset(str_header, 0, sizeof(FMT_STRING_HEADER));
558 pOut += sizeof(FMT_STRING_HEADER);
559 fmt_state = 0;
560 pLastHours = NULL;
563 else if (*pFormat == '\\')
565 /* Escaped character */
566 if (pFormat[1])
568 NEED_SPACE(3 * sizeof(BYTE));
569 pFormat++;
570 *pOut++ = FMT_GEN_COPY;
571 *pOut++ = pFormat - lpszFormat;
572 *pOut++ = 0x1;
573 fmt_state |= FMT_STATE_OPEN_COPY;
574 TRACE("'\\'\n");
576 else
577 fmt_state &= ~FMT_STATE_OPEN_COPY;
578 pFormat++;
580 else if (*pFormat == '"')
582 /* Escaped string
583 * Note: Native encodes "" as a copy of length zero. That's just dumb, so
584 * here we avoid encoding anything in this case.
586 if (!pFormat[1])
587 pFormat++;
588 else if (pFormat[1] == '"')
590 pFormat += 2;
592 else
594 LPCWSTR start = ++pFormat;
595 while (*pFormat && *pFormat != '"')
596 pFormat++;
597 NEED_SPACE(3 * sizeof(BYTE));
598 *pOut++ = FMT_GEN_COPY;
599 *pOut++ = start - lpszFormat;
600 *pOut++ = pFormat - start;
601 if (*pFormat == '"')
602 pFormat++;
603 TRACE("Quoted string pos %d, len %d\n", pOut[-2], pOut[-1]);
605 fmt_state &= ~FMT_STATE_OPEN_COPY;
607 /* -------------
608 * Number tokens
609 * -------------
611 else if (*pFormat == '0' && COULD_BE(FMT_TYPE_NUMBER))
613 /* Number formats: Digit from number or '0' if no digits
614 * Other formats: Literal
615 * Types the format if found
617 header->type = FMT_TYPE_NUMBER;
618 NEED_SPACE(2 * sizeof(BYTE));
619 *pOut++ = FMT_NUM_COPY_ZERO;
620 *pOut = 0x0;
621 while (*pFormat == '0')
623 *pOut = *pOut + 1;
624 pFormat++;
626 if (fmt_state & FMT_STATE_WROTE_DECIMAL)
627 num_header->fractional += *pOut;
628 else
629 num_header->whole += *pOut;
630 TRACE("%d 0's\n", *pOut);
631 pOut++;
632 fmt_state &= ~FMT_STATE_OPEN_COPY;
634 else if (*pFormat == '#' && COULD_BE(FMT_TYPE_NUMBER))
636 /* Number formats: Digit from number or blank if no digits
637 * Other formats: Literal
638 * Types the format if found
640 header->type = FMT_TYPE_NUMBER;
641 NEED_SPACE(2 * sizeof(BYTE));
642 *pOut++ = FMT_NUM_COPY_SKIP;
643 *pOut = 0x0;
644 while (*pFormat == '#')
646 *pOut = *pOut + 1;
647 pFormat++;
649 if (fmt_state & FMT_STATE_WROTE_DECIMAL)
650 num_header->fractional += *pOut;
651 else
652 num_header->whole += *pOut;
653 TRACE("%d #'s\n", *pOut);
654 pOut++;
655 fmt_state &= ~FMT_STATE_OPEN_COPY;
657 else if (*pFormat == '.' && COULD_BE(FMT_TYPE_NUMBER) &&
658 !(fmt_state & FMT_STATE_WROTE_DECIMAL))
660 /* Number formats: Decimal separator when 1st seen, literal thereafter
661 * Other formats: Literal
662 * Types the format if found
664 header->type = FMT_TYPE_NUMBER;
665 NEED_SPACE(sizeof(BYTE));
666 *pOut++ = FMT_NUM_DECIMAL;
667 fmt_state |= FMT_STATE_WROTE_DECIMAL;
668 fmt_state &= ~FMT_STATE_OPEN_COPY;
669 pFormat++;
670 TRACE("decimal sep\n");
672 else if ((*pFormat == 'e' || *pFormat == 'E') && (pFormat[1] == '-' ||
673 pFormat[1] == '+') && header->type == FMT_TYPE_NUMBER)
675 /* Number formats: Exponent specifier
676 * Other formats: Literal
678 num_header->flags |= FMT_FLAG_EXPONENT;
679 NEED_SPACE(2 * sizeof(BYTE));
680 if (*pFormat == 'e') {
681 if (pFormat[1] == '+')
682 *pOut = FMT_NUM_EXP_POS_L;
683 else
684 *pOut = FMT_NUM_EXP_NEG_L;
685 } else {
686 if (pFormat[1] == '+')
687 *pOut = FMT_NUM_EXP_POS_U;
688 else
689 *pOut = FMT_NUM_EXP_NEG_U;
691 pFormat += 2;
692 *++pOut = 0x0;
693 while (*pFormat == '0')
695 *pOut = *pOut + 1;
696 pFormat++;
698 pOut++;
699 TRACE("exponent\n");
701 /* FIXME: %% => Divide by 1000 */
702 else if (*pFormat == ',' && header->type == FMT_TYPE_NUMBER)
704 /* Number formats: Use the thousands separator
705 * Other formats: Literal
707 num_header->flags |= FMT_FLAG_THOUSANDS;
708 pFormat++;
709 fmt_state &= ~FMT_STATE_OPEN_COPY;
710 TRACE("thousands sep\n");
712 /* -----------
713 * Date tokens
714 * -----------
716 else if (*pFormat == '/' && COULD_BE(FMT_TYPE_DATE))
718 /* Date formats: Date separator
719 * Other formats: Literal
720 * Types the format if found
722 header->type = FMT_TYPE_DATE;
723 NEED_SPACE(sizeof(BYTE));
724 *pOut++ = FMT_DATE_DATE_SEP;
725 pFormat++;
726 fmt_state &= ~FMT_STATE_OPEN_COPY;
727 TRACE("date sep\n");
729 else if (*pFormat == ':' && COULD_BE(FMT_TYPE_DATE))
731 /* Date formats: Time separator
732 * Other formats: Literal
733 * Types the format if found
735 header->type = FMT_TYPE_DATE;
736 NEED_SPACE(sizeof(BYTE));
737 *pOut++ = FMT_DATE_TIME_SEP;
738 pFormat++;
739 fmt_state &= ~FMT_STATE_OPEN_COPY;
740 TRACE("time sep\n");
742 else if ((*pFormat == 'a' || *pFormat == 'A') &&
743 !wcsnicmp(pFormat, szAMPM, ARRAY_SIZE(szAMPM)))
745 /* Date formats: System AM/PM designation
746 * Other formats: Literal
747 * Types the format if found
749 header->type = FMT_TYPE_DATE;
750 NEED_SPACE(sizeof(BYTE));
751 pFormat += ARRAY_SIZE(szAMPM);
752 if (!wcsncmp(pFormat, szampm, ARRAY_SIZE(szampm)))
753 *pOut++ = FMT_DATE_AMPM_SYS2;
754 else
755 *pOut++ = FMT_DATE_AMPM_SYS1;
756 if (pLastHours)
757 *pLastHours = *pLastHours + 2;
758 TRACE("ampm\n");
760 else if (*pFormat == 'a' && pFormat[1] == '/' &&
761 (pFormat[2] == 'p' || pFormat[2] == 'P'))
763 /* Date formats: lowercase a or p designation
764 * Other formats: Literal
765 * Types the format if found
767 header->type = FMT_TYPE_DATE;
768 NEED_SPACE(sizeof(BYTE));
769 pFormat += 3;
770 *pOut++ = FMT_DATE_A_LOWER;
771 if (pLastHours)
772 *pLastHours = *pLastHours + 2;
773 TRACE("a/p\n");
775 else if (*pFormat == 'A' && pFormat[1] == '/' &&
776 (pFormat[2] == 'p' || pFormat[2] == 'P'))
778 /* Date formats: Uppercase a or p designation
779 * Other formats: Literal
780 * Types the format if found
782 header->type = FMT_TYPE_DATE;
783 NEED_SPACE(sizeof(BYTE));
784 pFormat += 3;
785 *pOut++ = FMT_DATE_A_UPPER;
786 if (pLastHours)
787 *pLastHours = *pLastHours + 2;
788 TRACE("A/P\n");
790 else if (*pFormat == 'a' && !wcsncmp(pFormat, szamSlashpm, ARRAY_SIZE(szamSlashpm)))
792 /* Date formats: lowercase AM or PM designation
793 * Other formats: Literal
794 * Types the format if found
796 header->type = FMT_TYPE_DATE;
797 NEED_SPACE(sizeof(BYTE));
798 pFormat += ARRAY_SIZE(szamSlashpm);
799 *pOut++ = FMT_DATE_AMPM_LOWER;
800 if (pLastHours)
801 *pLastHours = *pLastHours + 2;
802 TRACE("AM/PM\n");
804 else if (*pFormat == 'A' && !wcsncmp(pFormat, szAMSlashPM, ARRAY_SIZE(szAMSlashPM)))
806 /* Date formats: Uppercase AM or PM designation
807 * Other formats: Literal
808 * Types the format if found
810 header->type = FMT_TYPE_DATE;
811 NEED_SPACE(sizeof(BYTE));
812 pFormat += ARRAY_SIZE(szAMSlashPM);
813 *pOut++ = FMT_DATE_AMPM_UPPER;
814 TRACE("AM/PM\n");
816 else if ((*pFormat == 'c' || *pFormat == 'C') && COULD_BE(FMT_TYPE_DATE))
818 /* Date formats: General date format
819 * Other formats: Literal
820 * Types the format if found
822 header->type = FMT_TYPE_DATE;
823 NEED_SPACE(sizeof(BYTE));
824 pFormat += ARRAY_SIZE(szAMSlashPM);
825 *pOut++ = FMT_DATE_GENERAL;
826 TRACE("gen date\n");
828 else if ((*pFormat == 'd' || *pFormat == 'D') && COULD_BE(FMT_TYPE_DATE))
830 /* Date formats: Day specifier
831 * Other formats: Literal
832 * Types the format if found
834 int count = -1;
835 header->type = FMT_TYPE_DATE;
836 while ((*pFormat == 'd' || *pFormat == 'D') && count < 6)
838 pFormat++;
839 count++;
841 NEED_SPACE(sizeof(BYTE));
842 *pOut++ = FMT_DATE_DAY + count;
843 fmt_state &= ~FMT_STATE_OPEN_COPY;
844 /* When we find the days token, reset the seen hours state so that
845 * 'mm' is again written as month when encountered.
847 fmt_state &= ~FMT_STATE_SEEN_HOURS;
848 TRACE("%d d's\n", count + 1);
850 else if ((*pFormat == 'h' || *pFormat == 'H') && COULD_BE(FMT_TYPE_DATE))
852 /* Date formats: Hour specifier
853 * Other formats: Literal
854 * Types the format if found
856 header->type = FMT_TYPE_DATE;
857 NEED_SPACE(sizeof(BYTE));
858 pFormat++;
859 /* Record the position of the hours specifier - if we encounter
860 * an am/pm specifier we will change the hours from 24 to 12.
862 pLastHours = pOut;
863 if (*pFormat == 'h' || *pFormat == 'H')
865 pFormat++;
866 *pOut++ = FMT_DATE_HOUR_0;
867 TRACE("hh\n");
869 else
871 *pOut++ = FMT_DATE_HOUR;
872 TRACE("h\n");
874 fmt_state &= ~FMT_STATE_OPEN_COPY;
875 /* Note that now we have seen an hours token, the next occurrence of
876 * 'mm' indicates minutes, not months.
878 fmt_state |= FMT_STATE_SEEN_HOURS;
880 else if ((*pFormat == 'm' || *pFormat == 'M') && COULD_BE(FMT_TYPE_DATE))
882 /* Date formats: Month specifier (or Minute specifier, after hour specifier)
883 * Other formats: Literal
884 * Types the format if found
886 int count = -1;
887 header->type = FMT_TYPE_DATE;
888 while ((*pFormat == 'm' || *pFormat == 'M') && count < 4)
890 pFormat++;
891 count++;
893 NEED_SPACE(sizeof(BYTE));
894 if (count <= 1 && fmt_state & FMT_STATE_SEEN_HOURS &&
895 !(fmt_state & FMT_STATE_WROTE_MINUTES))
897 /* We have seen an hours specifier and not yet written a minutes
898 * specifier. Write this as minutes and thereafter as months.
900 *pOut++ = count == 1 ? FMT_DATE_MIN_0 : FMT_DATE_MIN;
901 fmt_state |= FMT_STATE_WROTE_MINUTES; /* Hereafter write months */
903 else
904 *pOut++ = FMT_DATE_MON + count; /* Months */
905 fmt_state &= ~FMT_STATE_OPEN_COPY;
906 TRACE("%d m's\n", count + 1);
908 else if ((*pFormat == 'n' || *pFormat == 'N') && COULD_BE(FMT_TYPE_DATE))
910 /* Date formats: Minute specifier
911 * Other formats: Literal
912 * Types the format if found
914 header->type = FMT_TYPE_DATE;
915 NEED_SPACE(sizeof(BYTE));
916 pFormat++;
917 if (*pFormat == 'n' || *pFormat == 'N')
919 pFormat++;
920 *pOut++ = FMT_DATE_MIN_0;
921 TRACE("nn\n");
923 else
925 *pOut++ = FMT_DATE_MIN;
926 TRACE("n\n");
928 fmt_state &= ~FMT_STATE_OPEN_COPY;
930 else if ((*pFormat == 'q' || *pFormat == 'Q') && COULD_BE(FMT_TYPE_DATE))
932 /* Date formats: Quarter specifier
933 * Other formats: Literal
934 * Types the format if found
936 header->type = FMT_TYPE_DATE;
937 NEED_SPACE(sizeof(BYTE));
938 *pOut++ = FMT_DATE_QUARTER;
939 pFormat++;
940 fmt_state &= ~FMT_STATE_OPEN_COPY;
941 TRACE("quarter\n");
943 else if ((*pFormat == 's' || *pFormat == 'S') && COULD_BE(FMT_TYPE_DATE))
945 /* Date formats: Second specifier
946 * Other formats: Literal
947 * Types the format if found
949 header->type = FMT_TYPE_DATE;
950 NEED_SPACE(sizeof(BYTE));
951 pFormat++;
952 if (*pFormat == 's' || *pFormat == 'S')
954 pFormat++;
955 *pOut++ = FMT_DATE_SEC_0;
956 TRACE("ss\n");
958 else
960 *pOut++ = FMT_DATE_SEC;
961 TRACE("s\n");
963 fmt_state &= ~FMT_STATE_OPEN_COPY;
965 else if ((*pFormat == 't' || *pFormat == 'T') &&
966 !wcsnicmp(pFormat, szTTTTT, ARRAY_SIZE(szTTTTT)))
968 /* Date formats: System time specifier
969 * Other formats: Literal
970 * Types the format if found
972 header->type = FMT_TYPE_DATE;
973 pFormat += ARRAY_SIZE(szTTTTT);
974 NEED_SPACE(sizeof(BYTE));
975 *pOut++ = FMT_DATE_TIME_SYS;
976 fmt_state &= ~FMT_STATE_OPEN_COPY;
978 else if ((*pFormat == 'w' || *pFormat == 'W') && COULD_BE(FMT_TYPE_DATE))
980 /* Date formats: Week of the year/Day of the week
981 * Other formats: Literal
982 * Types the format if found
984 header->type = FMT_TYPE_DATE;
985 pFormat++;
986 if (*pFormat == 'w' || *pFormat == 'W')
988 NEED_SPACE(3 * sizeof(BYTE));
989 pFormat++;
990 *pOut++ = FMT_DATE_WEEK_YEAR;
991 *pOut++ = nFirstDay;
992 *pOut++ = nFirstWeek;
993 TRACE("ww\n");
995 else
997 NEED_SPACE(2 * sizeof(BYTE));
998 *pOut++ = FMT_DATE_DAY_WEEK;
999 *pOut++ = nFirstDay;
1000 TRACE("w\n");
1003 fmt_state &= ~FMT_STATE_OPEN_COPY;
1005 else if ((*pFormat == 'y' || *pFormat == 'Y') && COULD_BE(FMT_TYPE_DATE))
1007 /* Date formats: Day of year/Year specifier
1008 * Other formats: Literal
1009 * Types the format if found
1011 int count = -1;
1012 header->type = FMT_TYPE_DATE;
1013 while ((*pFormat == 'y' || *pFormat == 'Y') && count < 4)
1015 pFormat++;
1016 count++;
1018 if (count == 2)
1020 count--; /* 'yyy' has no meaning, despite what MSDN says */
1021 pFormat--;
1023 NEED_SPACE(sizeof(BYTE));
1024 *pOut++ = FMT_DATE_YEAR_DOY + count;
1025 fmt_state &= ~FMT_STATE_OPEN_COPY;
1026 TRACE("%d y's\n", count + 1);
1028 /* -------------
1029 * String tokens
1030 * -------------
1032 else if (*pFormat == '@' && COULD_BE(FMT_TYPE_STRING))
1034 /* String formats: Character from string or space if no char
1035 * Other formats: Literal
1036 * Types the format if found
1038 header->type = FMT_TYPE_STRING;
1039 NEED_SPACE(2 * sizeof(BYTE));
1040 *pOut++ = FMT_STR_COPY_SPACE;
1041 *pOut = 0x0;
1042 while (*pFormat == '@')
1044 *pOut = *pOut + 1;
1045 str_header->copy_chars++;
1046 pFormat++;
1048 TRACE("%d @'s\n", *pOut);
1049 pOut++;
1050 fmt_state &= ~FMT_STATE_OPEN_COPY;
1052 else if (*pFormat == '&' && COULD_BE(FMT_TYPE_STRING))
1054 /* String formats: Character from string or skip if no char
1055 * Other formats: Literal
1056 * Types the format if found
1058 header->type = FMT_TYPE_STRING;
1059 NEED_SPACE(2 * sizeof(BYTE));
1060 *pOut++ = FMT_STR_COPY_SKIP;
1061 *pOut = 0x0;
1062 while (*pFormat == '&')
1064 *pOut = *pOut + 1;
1065 str_header->copy_chars++;
1066 pFormat++;
1068 TRACE("%d &'s\n", *pOut);
1069 pOut++;
1070 fmt_state &= ~FMT_STATE_OPEN_COPY;
1072 else if ((*pFormat == '<' || *pFormat == '>') && COULD_BE(FMT_TYPE_STRING))
1074 /* String formats: Use upper/lower case
1075 * Other formats: Literal
1076 * Types the format if found
1078 header->type = FMT_TYPE_STRING;
1079 if (*pFormat == '<')
1080 str_header->flags |= FMT_FLAG_LT;
1081 else
1082 str_header->flags |= FMT_FLAG_GT;
1083 TRACE("to %s case\n", *pFormat == '<' ? "lower" : "upper");
1084 pFormat++;
1085 fmt_state &= ~FMT_STATE_OPEN_COPY;
1087 else if (*pFormat == '!' && COULD_BE(FMT_TYPE_STRING))
1089 /* String formats: Copy right to left
1090 * Other formats: Literal
1091 * Types the format if found
1093 header->type = FMT_TYPE_STRING;
1094 str_header->flags |= FMT_FLAG_RTL;
1095 pFormat++;
1096 fmt_state &= ~FMT_STATE_OPEN_COPY;
1097 TRACE("copy right-to-left\n");
1099 /* --------
1100 * Literals
1101 * --------
1103 /* FIXME: [ seems to be ignored */
1104 else
1106 if (*pFormat == '%' && header->type == FMT_TYPE_NUMBER)
1108 /* Number formats: Percentage indicator, also a literal
1109 * Other formats: Literal
1110 * Doesn't type the format
1112 num_header->flags |= FMT_FLAG_PERCENT;
1115 if (fmt_state & FMT_STATE_OPEN_COPY)
1117 pOut[-1] = pOut[-1] + 1; /* Increase the length of the open copy */
1118 TRACE("extend copy (char '%c'), length now %d\n", *pFormat, pOut[-1]);
1120 else
1122 /* Create a new open copy */
1123 TRACE("New copy (char '%c')\n", *pFormat);
1124 NEED_SPACE(3 * sizeof(BYTE));
1125 *pOut++ = FMT_GEN_COPY;
1126 *pOut++ = pFormat - lpszFormat;
1127 *pOut++ = 0x1;
1128 fmt_state |= FMT_STATE_OPEN_COPY;
1130 pFormat++;
1134 *pOut++ = FMT_GEN_END;
1136 header->size = pOut - rgbTok;
1137 if (pcbActual)
1138 *pcbActual = header->size;
1140 return S_OK;
1143 /* Number formatting state flags */
1144 #define NUM_WROTE_DEC 0x01 /* Written the decimal separator */
1145 #define NUM_WRITE_ON 0x02 /* Started to write the number */
1146 #define NUM_WROTE_SIGN 0x04 /* Written the negative sign */
1148 /* Format a variant using a number format */
1149 static HRESULT VARIANT_FormatNumber(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1150 LPBYTE rgbTok, ULONG dwFlags,
1151 BSTR *pbstrOut, LCID lcid)
1153 BYTE rgbDig[256], *prgbDig;
1154 NUMPARSE np;
1155 int have_int, need_int = 0, have_frac, need_frac, exponent = 0, pad = 0;
1156 WCHAR buff[256], *pBuff = buff;
1157 WCHAR thousandSeparator[32];
1158 VARIANT vString, vBool;
1159 DWORD dwState = 0;
1160 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1161 FMT_NUMBER_HEADER *numHeader;
1162 const BYTE* pToken = NULL;
1163 HRESULT hRes = S_OK;
1165 TRACE("(%s,%s,%p,0x%08x,%p,0x%08x)\n", debugstr_variant(pVarIn), debugstr_w(lpszFormat),
1166 rgbTok, dwFlags, pbstrOut, lcid);
1168 V_VT(&vString) = VT_EMPTY;
1169 V_VT(&vBool) = VT_BOOL;
1171 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1173 have_int = have_frac = 0;
1174 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNull(header));
1175 V_BOOL(&vBool) = VARIANT_FALSE;
1177 else
1179 /* Get a number string from pVarIn, and parse it */
1180 hRes = VariantChangeTypeEx(&vString, pVarIn, lcid, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1181 if (FAILED(hRes))
1182 return hRes;
1184 np.cDig = sizeof(rgbDig);
1185 np.dwInFlags = NUMPRS_STD;
1186 hRes = VarParseNumFromStr(V_BSTR(&vString), lcid, 0, &np, rgbDig);
1187 if (FAILED(hRes))
1188 return hRes;
1190 have_int = np.cDig;
1191 have_frac = 0;
1192 exponent = np.nPwr10;
1194 /* Figure out which format to use */
1195 if (np.dwOutFlags & NUMPRS_NEG)
1197 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNegative(header));
1198 V_BOOL(&vBool) = VARIANT_TRUE;
1200 else if (have_int == 1 && !exponent && rgbDig[0] == 0)
1202 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetZero(header));
1203 V_BOOL(&vBool) = VARIANT_FALSE;
1205 else
1207 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetPositive(header));
1208 V_BOOL(&vBool) = VARIANT_TRUE;
1211 TRACE("num header: flags = 0x%x, mult=%d, div=%d, whole=%d, fract=%d\n",
1212 numHeader->flags, numHeader->multiplier, numHeader->divisor,
1213 numHeader->whole, numHeader->fractional);
1215 need_int = numHeader->whole;
1216 need_frac = numHeader->fractional;
1218 if (numHeader->flags & FMT_FLAG_PERCENT &&
1219 !(have_int == 1 && !exponent && rgbDig[0] == 0))
1220 exponent += 2;
1222 if (numHeader->flags & FMT_FLAG_EXPONENT)
1224 /* Exponent format: length of the integral number part is fixed and
1225 specified by the format. */
1226 pad = need_int - have_int;
1227 exponent -= pad;
1228 if (pad < 0)
1230 have_int = need_int;
1231 have_frac -= pad;
1232 pad = 0;
1235 else
1237 /* Convert the exponent */
1238 pad = max(exponent, -have_int);
1239 exponent -= pad;
1240 if (pad < 0)
1242 have_int += pad;
1243 have_frac = -pad;
1244 pad = 0;
1246 if(exponent < 0 && exponent > (-256 + have_int + have_frac))
1248 /* Remove exponent notation */
1249 memmove(rgbDig - exponent, rgbDig, have_int + have_frac);
1250 ZeroMemory(rgbDig, -exponent);
1251 have_frac -= exponent;
1252 exponent = 0;
1256 /* Rounding the number */
1257 if (have_frac > need_frac)
1259 prgbDig = &rgbDig[have_int + need_frac];
1260 have_frac = need_frac;
1261 if (*prgbDig >= 5)
1263 while (prgbDig-- > rgbDig && *prgbDig == 9)
1264 *prgbDig = 0;
1265 if (prgbDig < rgbDig)
1267 /* We reached the first digit and that was also a 9 */
1268 rgbDig[0] = 1;
1269 if (numHeader->flags & FMT_FLAG_EXPONENT)
1270 exponent++;
1271 else
1273 rgbDig[have_int + need_frac] = 0;
1274 if (exponent < 0)
1275 exponent++;
1276 else
1277 have_int++;
1280 else
1281 (*prgbDig)++;
1283 /* We converted trailing digits to zeroes => have_frac has changed */
1284 while (have_frac > 0 && rgbDig[have_int + have_frac - 1] == 0)
1285 have_frac--;
1287 TRACE("have_int=%d,need_int=%d,have_frac=%d,need_frac=%d,pad=%d,exp=%d\n",
1288 have_int, need_int, have_frac, need_frac, pad, exponent);
1291 if (numHeader->flags & FMT_FLAG_THOUSANDS)
1293 if (!GetLocaleInfoW(lcid, LOCALE_STHOUSAND, thousandSeparator, ARRAY_SIZE(thousandSeparator)))
1295 thousandSeparator[0] = ',';
1296 thousandSeparator[1] = 0;
1300 pToken = (const BYTE*)numHeader + sizeof(FMT_NUMBER_HEADER);
1301 prgbDig = rgbDig;
1303 while (SUCCEEDED(hRes) && *pToken != FMT_GEN_END)
1305 WCHAR defaultChar = '?';
1306 DWORD boolFlag, localeValue = 0;
1307 BOOL shouldAdvance = TRUE;
1309 if (pToken - rgbTok > header->size)
1311 ERR("Ran off the end of the format!\n");
1312 hRes = E_INVALIDARG;
1313 goto VARIANT_FormatNumber_Exit;
1316 switch (*pToken)
1318 case FMT_GEN_COPY:
1319 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1320 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1321 pBuff += pToken[2];
1322 pToken += 2;
1323 break;
1325 case FMT_GEN_INLINE:
1326 pToken += 2;
1327 TRACE("copy %s\n", debugstr_a((LPCSTR)pToken));
1328 while (*pToken)
1329 *pBuff++ = *pToken++;
1330 break;
1332 case FMT_NUM_YES_NO:
1333 boolFlag = VAR_BOOLYESNO;
1334 goto VARIANT_FormatNumber_Bool;
1336 case FMT_NUM_ON_OFF:
1337 boolFlag = VAR_BOOLONOFF;
1338 goto VARIANT_FormatNumber_Bool;
1340 case FMT_NUM_TRUE_FALSE:
1341 boolFlag = VAR_LOCALBOOL;
1343 VARIANT_FormatNumber_Bool:
1345 BSTR boolStr = NULL;
1347 if (pToken[1] != FMT_GEN_END)
1349 ERR("Boolean token not at end of format!\n");
1350 hRes = E_INVALIDARG;
1351 goto VARIANT_FormatNumber_Exit;
1353 hRes = VarBstrFromBool(V_BOOL(&vBool), lcid, boolFlag, &boolStr);
1354 if (SUCCEEDED(hRes))
1356 lstrcpyW(pBuff, boolStr);
1357 SysFreeString(boolStr);
1358 while (*pBuff)
1359 pBuff++;
1362 break;
1364 case FMT_NUM_DECIMAL:
1365 if ((np.dwOutFlags & NUMPRS_NEG) && !(dwState & NUM_WROTE_SIGN) && !header->starts[1])
1367 /* last chance for a negative sign in the .# case */
1368 TRACE("write negative sign\n");
1369 localeValue = LOCALE_SNEGATIVESIGN;
1370 defaultChar = '-';
1371 dwState |= NUM_WROTE_SIGN;
1372 shouldAdvance = FALSE;
1373 break;
1375 TRACE("write decimal separator\n");
1376 localeValue = LOCALE_SDECIMAL;
1377 defaultChar = '.';
1378 dwState |= NUM_WROTE_DEC;
1379 break;
1381 case FMT_NUM_CURRENCY:
1382 TRACE("write currency symbol\n");
1383 localeValue = LOCALE_SCURRENCY;
1384 defaultChar = '$';
1385 break;
1387 case FMT_NUM_EXP_POS_U:
1388 case FMT_NUM_EXP_POS_L:
1389 case FMT_NUM_EXP_NEG_U:
1390 case FMT_NUM_EXP_NEG_L:
1391 if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_NEG_L)
1392 *pBuff++ = 'e';
1393 else
1394 *pBuff++ = 'E';
1395 if (exponent < 0)
1397 *pBuff++ = '-';
1398 swprintf(pBuff, ARRAY_SIZE(buff) - (pBuff - buff), L"%0*d", pToken[1], -exponent);
1400 else
1402 if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_POS_U)
1403 *pBuff++ = '+';
1404 swprintf(pBuff, ARRAY_SIZE(buff) - (pBuff - buff), L"%0*d", pToken[1], exponent);
1406 while (*pBuff)
1407 pBuff++;
1408 pToken++;
1409 break;
1411 case FMT_NUM_COPY_ZERO:
1412 dwState |= NUM_WRITE_ON;
1413 /* Fall through */
1415 case FMT_NUM_COPY_SKIP:
1416 TRACE("write %d %sdigits or %s\n", pToken[1],
1417 dwState & NUM_WROTE_DEC ? "fractional " : "",
1418 *pToken == FMT_NUM_COPY_ZERO ? "0" : "skip");
1420 if (dwState & NUM_WROTE_DEC)
1422 int count, i;
1424 if (!(numHeader->flags & FMT_FLAG_EXPONENT) && exponent < 0)
1426 /* Pad with 0 before writing the fractional digits */
1427 pad = max(exponent, -pToken[1]);
1428 exponent -= pad;
1429 count = min(have_frac, pToken[1] + pad);
1430 for (i = 0; i > pad; i--)
1431 *pBuff++ = '0';
1433 else
1434 count = min(have_frac, pToken[1]);
1436 pad += pToken[1] - count;
1437 have_frac -= count;
1438 while (count--)
1439 *pBuff++ = '0' + *prgbDig++;
1440 if (*pToken == FMT_NUM_COPY_ZERO)
1442 for (; pad > 0; pad--)
1443 *pBuff++ = '0'; /* Write zeros for missing trailing digits */
1446 else
1448 int count, count_max, position;
1450 if ((np.dwOutFlags & NUMPRS_NEG) && !(dwState & NUM_WROTE_SIGN) && !header->starts[1])
1452 TRACE("write negative sign\n");
1453 localeValue = LOCALE_SNEGATIVESIGN;
1454 defaultChar = '-';
1455 dwState |= NUM_WROTE_SIGN;
1456 shouldAdvance = FALSE;
1457 break;
1460 position = have_int + pad;
1461 if (dwState & NUM_WRITE_ON)
1462 position = max(position, need_int);
1463 need_int -= pToken[1];
1464 count_max = have_int + pad - need_int;
1465 if (count_max < 0)
1466 count_max = 0;
1467 if (dwState & NUM_WRITE_ON)
1469 count = pToken[1] - count_max;
1470 TRACE("write %d leading zeros\n", count);
1471 while (count-- > 0)
1473 *pBuff++ = '0';
1474 if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1475 position > 1 && (--position % 3) == 0)
1477 int k;
1478 TRACE("write thousand separator\n");
1479 for (k = 0; thousandSeparator[k]; k++)
1480 *pBuff++ = thousandSeparator[k];
1484 if (*pToken == FMT_NUM_COPY_ZERO || have_int > 1 ||
1485 (have_int > 0 && *prgbDig > 0))
1487 count = min(count_max, have_int);
1488 count_max -= count;
1489 have_int -= count;
1490 TRACE("write %d whole number digits\n", count);
1491 while (count--)
1493 dwState |= NUM_WRITE_ON;
1494 *pBuff++ = '0' + *prgbDig++;
1495 if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1496 position > 1 && (--position % 3) == 0)
1498 int k;
1499 TRACE("write thousand separator\n");
1500 for (k = 0; thousandSeparator[k]; k++)
1501 *pBuff++ = thousandSeparator[k];
1505 count = min(count_max, pad);
1506 pad -= count;
1507 TRACE("write %d whole trailing 0's\n", count);
1508 while (count--)
1510 *pBuff++ = '0';
1511 if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1512 position > 1 && (--position % 3) == 0)
1514 int k;
1515 TRACE("write thousand separator\n");
1516 for (k = 0; thousandSeparator[k]; k++)
1517 *pBuff++ = thousandSeparator[k];
1521 pToken++;
1522 break;
1524 default:
1525 ERR("Unknown token 0x%02x!\n", *pToken);
1526 hRes = E_INVALIDARG;
1527 goto VARIANT_FormatNumber_Exit;
1529 if (localeValue)
1531 if (GetLocaleInfoW(lcid, localeValue, pBuff, ARRAY_SIZE(buff)-(pBuff-buff)))
1533 TRACE("added %s\n", debugstr_w(pBuff));
1534 while (*pBuff)
1535 pBuff++;
1537 else
1539 TRACE("added %d '%c'\n", defaultChar, defaultChar);
1540 *pBuff++ = defaultChar;
1543 if (shouldAdvance)
1544 pToken++;
1547 VARIANT_FormatNumber_Exit:
1548 VariantClear(&vString);
1549 *pBuff = '\0';
1550 TRACE("buff is %s\n", debugstr_w(buff));
1551 if (SUCCEEDED(hRes))
1553 *pbstrOut = SysAllocString(buff);
1554 if (!*pbstrOut)
1555 hRes = E_OUTOFMEMORY;
1557 return hRes;
1560 /* Format a variant using a date format */
1561 static HRESULT VARIANT_FormatDate(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1562 LPBYTE rgbTok, ULONG dwFlags,
1563 BSTR *pbstrOut, LCID lcid)
1565 WCHAR buff[256], *pBuff = buff;
1566 VARIANT vDate;
1567 UDATE udate;
1568 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1569 FMT_DATE_HEADER *dateHeader;
1570 const BYTE* pToken = NULL;
1571 HRESULT hRes;
1573 TRACE("(%s,%s,%p,0x%08x,%p,0x%08x)\n", debugstr_variant(pVarIn),
1574 debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut, lcid);
1576 V_VT(&vDate) = VT_EMPTY;
1578 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1580 dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetNegative(header));
1581 V_DATE(&vDate) = 0;
1583 else
1585 USHORT usFlags = dwFlags & VARIANT_CALENDAR_HIJRI ? VAR_CALENDAR_HIJRI : 0;
1587 hRes = VariantChangeTypeEx(&vDate, pVarIn, lcid, usFlags, VT_DATE);
1588 if (FAILED(hRes))
1589 return hRes;
1590 dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetPositive(header));
1593 hRes = VarUdateFromDate(V_DATE(&vDate), 0 /* FIXME: flags? */, &udate);
1594 if (FAILED(hRes))
1595 return hRes;
1596 pToken = (const BYTE*)dateHeader + sizeof(FMT_DATE_HEADER);
1598 while (*pToken != FMT_GEN_END)
1600 DWORD dwVal = 0, localeValue = 0, dwFmt = 0;
1601 LPCWSTR szPrintFmt = NULL;
1602 WCHAR defaultChar = '?';
1604 if (pToken - rgbTok > header->size)
1606 ERR("Ran off the end of the format!\n");
1607 hRes = E_INVALIDARG;
1608 goto VARIANT_FormatDate_Exit;
1611 switch (*pToken)
1613 case FMT_GEN_COPY:
1614 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1615 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1616 pBuff += pToken[2];
1617 pToken += 2;
1618 break;
1620 case FMT_GEN_INLINE:
1621 pToken += 2;
1622 TRACE("copy %s\n", debugstr_a((LPCSTR)pToken));
1623 while (*pToken)
1624 *pBuff++ = *pToken++;
1625 break;
1627 case FMT_DATE_TIME_SEP:
1628 TRACE("time separator\n");
1629 localeValue = LOCALE_STIME;
1630 defaultChar = ':';
1631 break;
1633 case FMT_DATE_DATE_SEP:
1634 TRACE("date separator\n");
1635 localeValue = LOCALE_SDATE;
1636 defaultChar = '/';
1637 break;
1639 case FMT_DATE_GENERAL:
1641 BSTR date = NULL;
1642 WCHAR *pDate;
1643 hRes = VarBstrFromDate(V_DATE(&vDate), lcid, 0, &date);
1644 if (FAILED(hRes))
1645 goto VARIANT_FormatDate_Exit;
1646 pDate = date;
1647 while (*pDate)
1648 *pBuff++ = *pDate++;
1649 SysFreeString(date);
1651 break;
1653 case FMT_DATE_QUARTER:
1654 if (udate.st.wMonth <= 3)
1655 *pBuff++ = '1';
1656 else if (udate.st.wMonth <= 6)
1657 *pBuff++ = '2';
1658 else if (udate.st.wMonth <= 9)
1659 *pBuff++ = '3';
1660 else
1661 *pBuff++ = '4';
1662 break;
1664 case FMT_DATE_TIME_SYS:
1666 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1667 BSTR date = NULL;
1668 WCHAR *pDate;
1669 hRes = VarBstrFromDate(V_DATE(&vDate), lcid, VAR_TIMEVALUEONLY, &date);
1670 if (FAILED(hRes))
1671 goto VARIANT_FormatDate_Exit;
1672 pDate = date;
1673 while (*pDate)
1674 *pBuff++ = *pDate++;
1675 SysFreeString(date);
1677 break;
1679 case FMT_DATE_DAY:
1680 szPrintFmt = L"%d";
1681 dwVal = udate.st.wDay;
1682 break;
1684 case FMT_DATE_DAY_0:
1685 szPrintFmt = L"%02d";
1686 dwVal = udate.st.wDay;
1687 break;
1689 case FMT_DATE_DAY_SHORT:
1690 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1691 TRACE("short day\n");
1692 localeValue = LOCALE_SABBREVDAYNAME1 + (udate.st.wDayOfWeek + 6)%7;
1693 defaultChar = '?';
1694 break;
1696 case FMT_DATE_DAY_LONG:
1697 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1698 TRACE("long day\n");
1699 localeValue = LOCALE_SDAYNAME1 + (udate.st.wDayOfWeek + 6)%7;
1700 defaultChar = '?';
1701 break;
1703 case FMT_DATE_SHORT:
1704 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1705 dwFmt = LOCALE_SSHORTDATE;
1706 break;
1708 case FMT_DATE_LONG:
1709 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1710 dwFmt = LOCALE_SLONGDATE;
1711 break;
1713 case FMT_DATE_MEDIUM:
1714 FIXME("Medium date treated as long date\n");
1715 dwFmt = LOCALE_SLONGDATE;
1716 break;
1718 case FMT_DATE_DAY_WEEK:
1719 szPrintFmt = L"%d";
1720 if (pToken[1])
1721 dwVal = udate.st.wDayOfWeek + 2 - pToken[1];
1722 else
1724 GetLocaleInfoW(lcid,LOCALE_RETURN_NUMBER|LOCALE_IFIRSTDAYOFWEEK,
1725 (LPWSTR)&dwVal, sizeof(dwVal)/sizeof(WCHAR));
1726 dwVal = udate.st.wDayOfWeek + 1 - dwVal;
1728 pToken++;
1729 break;
1731 case FMT_DATE_WEEK_YEAR:
1732 szPrintFmt = L"%d";
1733 dwVal = udate.wDayOfYear / 7 + 1;
1734 pToken += 2;
1735 FIXME("Ignoring nFirstDay of %d, nFirstWeek of %d\n", pToken[0], pToken[1]);
1736 break;
1738 case FMT_DATE_MON:
1739 szPrintFmt = L"%d";
1740 dwVal = udate.st.wMonth;
1741 break;
1743 case FMT_DATE_MON_0:
1744 szPrintFmt = L"%02d";
1745 dwVal = udate.st.wMonth;
1746 break;
1748 case FMT_DATE_MON_SHORT:
1749 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1750 TRACE("short month\n");
1751 localeValue = LOCALE_SABBREVMONTHNAME1 + udate.st.wMonth - 1;
1752 defaultChar = '?';
1753 break;
1755 case FMT_DATE_MON_LONG:
1756 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1757 TRACE("long month\n");
1758 localeValue = LOCALE_SMONTHNAME1 + udate.st.wMonth - 1;
1759 defaultChar = '?';
1760 break;
1762 case FMT_DATE_YEAR_DOY:
1763 szPrintFmt = L"%d";
1764 dwVal = udate.wDayOfYear;
1765 break;
1767 case FMT_DATE_YEAR_0:
1768 szPrintFmt = L"%02d";
1769 dwVal = udate.st.wYear % 100;
1770 break;
1772 case FMT_DATE_YEAR_LONG:
1773 szPrintFmt = L"%d";
1774 dwVal = udate.st.wYear;
1775 break;
1777 case FMT_DATE_MIN:
1778 szPrintFmt = L"%d";
1779 dwVal = udate.st.wMinute;
1780 break;
1782 case FMT_DATE_MIN_0:
1783 szPrintFmt = L"%02d";
1784 dwVal = udate.st.wMinute;
1785 break;
1787 case FMT_DATE_SEC:
1788 szPrintFmt = L"%d";
1789 dwVal = udate.st.wSecond;
1790 break;
1792 case FMT_DATE_SEC_0:
1793 szPrintFmt = L"%02d";
1794 dwVal = udate.st.wSecond;
1795 break;
1797 case FMT_DATE_HOUR:
1798 szPrintFmt = L"%d";
1799 dwVal = udate.st.wHour;
1800 break;
1802 case FMT_DATE_HOUR_0:
1803 case FMT_DATE_TIME_UNK2:
1804 szPrintFmt = L"%02d";
1805 dwVal = udate.st.wHour;
1806 break;
1808 case FMT_DATE_HOUR_12:
1809 szPrintFmt = L"%d";
1810 dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
1811 break;
1813 case FMT_DATE_HOUR_12_0:
1814 szPrintFmt = L"%02d";
1815 dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
1816 break;
1818 case FMT_DATE_AMPM_SYS1:
1819 case FMT_DATE_AMPM_SYS2:
1820 localeValue = udate.st.wHour < 12 ? LOCALE_S1159 : LOCALE_S2359;
1821 defaultChar = '?';
1822 break;
1824 case FMT_DATE_AMPM_UPPER:
1825 *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1826 *pBuff++ = 'M';
1827 break;
1829 case FMT_DATE_A_UPPER:
1830 *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1831 break;
1833 case FMT_DATE_AMPM_LOWER:
1834 *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1835 *pBuff++ = 'm';
1836 break;
1838 case FMT_DATE_A_LOWER:
1839 *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1840 break;
1842 default:
1843 ERR("Unknown token 0x%02x!\n", *pToken);
1844 hRes = E_INVALIDARG;
1845 goto VARIANT_FormatDate_Exit;
1847 if (localeValue)
1849 *pBuff = '\0';
1850 if (GetLocaleInfoW(lcid, localeValue, pBuff, ARRAY_SIZE(buff)-(pBuff-buff)))
1852 TRACE("added %s\n", debugstr_w(pBuff));
1853 while (*pBuff)
1854 pBuff++;
1856 else
1858 TRACE("added %d %c\n", defaultChar, defaultChar);
1859 *pBuff++ = defaultChar;
1862 else if (dwFmt)
1864 WCHAR fmt_buff[80];
1866 if (!GetLocaleInfoW(lcid, dwFmt, fmt_buff, ARRAY_SIZE(fmt_buff)) ||
1867 !get_date_format(lcid, 0, &udate.st, fmt_buff, pBuff, ARRAY_SIZE(buff)-(pBuff-buff)))
1869 hRes = E_INVALIDARG;
1870 goto VARIANT_FormatDate_Exit;
1872 while (*pBuff)
1873 pBuff++;
1875 else if (szPrintFmt)
1877 swprintf(pBuff, ARRAY_SIZE(buff) - (pBuff - buff), szPrintFmt, dwVal);
1878 while (*pBuff)
1879 pBuff++;
1881 pToken++;
1884 VARIANT_FormatDate_Exit:
1885 *pBuff = '\0';
1886 TRACE("buff is %s\n", debugstr_w(buff));
1887 if (SUCCEEDED(hRes))
1889 *pbstrOut = SysAllocString(buff);
1890 if (!*pbstrOut)
1891 hRes = E_OUTOFMEMORY;
1893 return hRes;
1896 /* Format a variant using a string format */
1897 static HRESULT VARIANT_FormatString(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1898 LPBYTE rgbTok, ULONG dwFlags,
1899 BSTR *pbstrOut, LCID lcid)
1901 static WCHAR szEmpty[] = L"";
1902 WCHAR buff[256], *pBuff = buff;
1903 WCHAR *pSrc;
1904 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1905 FMT_STRING_HEADER *strHeader;
1906 const BYTE* pToken = NULL;
1907 VARIANT vStr;
1908 int blanks_first;
1909 BOOL bUpper = FALSE;
1910 HRESULT hRes = S_OK;
1912 TRACE("%s,%s,%p,0x%08x,%p,0x%08x)\n", debugstr_variant(pVarIn), debugstr_w(lpszFormat),
1913 rgbTok, dwFlags, pbstrOut, lcid);
1915 V_VT(&vStr) = VT_EMPTY;
1917 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1919 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1920 V_BSTR(&vStr) = szEmpty;
1922 else
1924 hRes = VariantChangeTypeEx(&vStr, pVarIn, lcid, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1925 if (FAILED(hRes))
1926 return hRes;
1928 if (V_BSTR(&vStr)[0] == '\0')
1929 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1930 else
1931 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetPositive(header));
1933 pSrc = V_BSTR(&vStr);
1934 if ((strHeader->flags & (FMT_FLAG_LT|FMT_FLAG_GT)) == FMT_FLAG_GT)
1935 bUpper = TRUE;
1936 blanks_first = strHeader->copy_chars - lstrlenW(pSrc);
1937 pToken = (const BYTE*)strHeader + sizeof(FMT_DATE_HEADER);
1939 while (*pToken != FMT_GEN_END)
1941 int dwCount = 0;
1943 if (pToken - rgbTok > header->size)
1945 ERR("Ran off the end of the format!\n");
1946 hRes = E_INVALIDARG;
1947 goto VARIANT_FormatString_Exit;
1950 switch (*pToken)
1952 case FMT_GEN_COPY:
1953 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1954 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1955 pBuff += pToken[2];
1956 pToken += 2;
1957 break;
1959 case FMT_STR_COPY_SPACE:
1960 case FMT_STR_COPY_SKIP:
1961 dwCount = pToken[1];
1962 if (*pToken == FMT_STR_COPY_SPACE && blanks_first > 0)
1964 TRACE("insert %d initial spaces\n", blanks_first);
1965 while (dwCount > 0 && blanks_first > 0)
1967 *pBuff++ = ' ';
1968 dwCount--;
1969 blanks_first--;
1972 TRACE("copy %d chars%s\n", dwCount,
1973 *pToken == FMT_STR_COPY_SPACE ? " with space" :"");
1974 while (dwCount > 0 && *pSrc)
1976 if (bUpper)
1977 *pBuff++ = towupper(*pSrc);
1978 else
1979 *pBuff++ = towlower(*pSrc);
1980 dwCount--;
1981 pSrc++;
1983 if (*pToken == FMT_STR_COPY_SPACE && dwCount > 0)
1985 TRACE("insert %d spaces\n", dwCount);
1986 while (dwCount-- > 0)
1987 *pBuff++ = ' ';
1989 pToken++;
1990 break;
1992 default:
1993 ERR("Unknown token 0x%02x!\n", *pToken);
1994 hRes = E_INVALIDARG;
1995 goto VARIANT_FormatString_Exit;
1997 pToken++;
2000 VARIANT_FormatString_Exit:
2001 /* Copy out any remaining chars */
2002 while (*pSrc)
2004 if (bUpper)
2005 *pBuff++ = towupper(*pSrc);
2006 else
2007 *pBuff++ = towlower(*pSrc);
2008 pSrc++;
2010 VariantClear(&vStr);
2011 *pBuff = '\0';
2012 TRACE("buff is %s\n", debugstr_w(buff));
2013 if (SUCCEEDED(hRes))
2015 *pbstrOut = SysAllocString(buff);
2016 if (!*pbstrOut)
2017 hRes = E_OUTOFMEMORY;
2019 return hRes;
2022 #define NUMBER_VTBITS (VTBIT_I1|VTBIT_UI1|VTBIT_I2|VTBIT_UI2| \
2023 VTBIT_I4|VTBIT_UI4|VTBIT_I8|VTBIT_UI8| \
2024 VTBIT_R4|VTBIT_R8|VTBIT_CY|VTBIT_DECIMAL| \
2025 VTBIT_BOOL|VTBIT_INT|VTBIT_UINT)
2027 /**********************************************************************
2028 * VarFormatFromTokens [OLEAUT32.139]
2030 HRESULT WINAPI VarFormatFromTokens(LPVARIANT pVarIn, LPOLESTR lpszFormat,
2031 LPBYTE rgbTok, ULONG dwFlags,
2032 BSTR *pbstrOut, LCID lcid)
2034 FMT_SHORT_HEADER *header = (FMT_SHORT_HEADER *)rgbTok;
2035 VARIANT vTmp;
2036 HRESULT hres;
2038 TRACE("(%p,%s,%p,%x,%p,0x%08x)\n", pVarIn, debugstr_w(lpszFormat),
2039 rgbTok, dwFlags, pbstrOut, lcid);
2041 if (!pbstrOut)
2042 return E_INVALIDARG;
2044 *pbstrOut = NULL;
2046 if (!pVarIn || !rgbTok)
2047 return E_INVALIDARG;
2049 if (V_VT(pVarIn) == VT_NULL)
2050 return S_OK;
2052 if (*rgbTok == FMT_TO_STRING || header->type == FMT_TYPE_GENERAL)
2054 /* According to MSDN, general format acts somewhat like the 'Str'
2055 * function in Visual Basic.
2057 VarFormatFromTokens_AsStr:
2058 V_VT(&vTmp) = VT_EMPTY;
2059 hres = VariantChangeTypeEx(&vTmp, pVarIn, lcid, dwFlags, VT_BSTR);
2060 *pbstrOut = V_BSTR(&vTmp);
2062 else
2064 if (header->type == FMT_TYPE_NUMBER ||
2065 (header->type == FMT_TYPE_UNKNOWN && ((1 << V_TYPE(pVarIn)) & NUMBER_VTBITS)))
2067 hres = VARIANT_FormatNumber(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2069 else if (header->type == FMT_TYPE_DATE ||
2070 (header->type == FMT_TYPE_UNKNOWN && V_TYPE(pVarIn) == VT_DATE))
2072 hres = VARIANT_FormatDate(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2074 else if (header->type == FMT_TYPE_STRING || V_TYPE(pVarIn) == VT_BSTR)
2076 hres = VARIANT_FormatString(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2078 else
2080 ERR("unrecognised format type 0x%02x\n", header->type);
2081 return E_INVALIDARG;
2083 /* If the coercion failed, still try to create output, unless the
2084 * VAR_FORMAT_NOSUBSTITUTE flag is set.
2086 if ((hres == DISP_E_OVERFLOW || hres == DISP_E_TYPEMISMATCH) &&
2087 !(dwFlags & VAR_FORMAT_NOSUBSTITUTE))
2088 goto VarFormatFromTokens_AsStr;
2091 return hres;
2094 /**********************************************************************
2095 * VarFormat [OLEAUT32.87]
2097 * Format a variant from a format string.
2099 * PARAMS
2100 * pVarIn [I] Variant to format
2101 * lpszFormat [I] Format string (see notes)
2102 * nFirstDay [I] First day of the week, (See VarTokenizeFormatString() for details)
2103 * nFirstWeek [I] First week of the year (See VarTokenizeFormatString() for details)
2104 * dwFlags [I] Flags for the format (VAR_ flags from "oleauto.h")
2105 * pbstrOut [O] Destination for formatted string.
2107 * RETURNS
2108 * Success: S_OK. pbstrOut contains the formatted value.
2109 * Failure: E_INVALIDARG, if any parameter is invalid.
2110 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2111 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2113 * NOTES
2114 * - See Variant-Formats for details concerning creating format strings.
2115 * - This function uses LOCALE_USER_DEFAULT when calling VarTokenizeFormatString()
2116 * and VarFormatFromTokens().
2118 HRESULT WINAPI VarFormat(LPVARIANT pVarIn, LPOLESTR lpszFormat,
2119 int nFirstDay, int nFirstWeek, ULONG dwFlags,
2120 BSTR *pbstrOut)
2122 BYTE buff[256];
2123 HRESULT hres;
2125 TRACE("(%s,%s,%d,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), debugstr_w(lpszFormat),
2126 nFirstDay, nFirstWeek, dwFlags, pbstrOut);
2128 if (!pbstrOut)
2129 return E_INVALIDARG;
2130 *pbstrOut = NULL;
2132 hres = VarTokenizeFormatString(lpszFormat, buff, sizeof(buff), nFirstDay,
2133 nFirstWeek, LOCALE_USER_DEFAULT, NULL);
2134 if (SUCCEEDED(hres))
2135 hres = VarFormatFromTokens(pVarIn, lpszFormat, buff, dwFlags,
2136 pbstrOut, LOCALE_USER_DEFAULT);
2137 TRACE("returning 0x%08x, %s\n", hres, debugstr_w(*pbstrOut));
2138 return hres;
2141 /**********************************************************************
2142 * VarFormatDateTime [OLEAUT32.97]
2144 * Format a variant value as a date and/or time.
2146 * PARAMS
2147 * pVarIn [I] Variant to format
2148 * nFormat [I] Format type (see notes)
2149 * dwFlags [I] Flags for the format (VAR_ flags from "oleauto.h")
2150 * pbstrOut [O] Destination for formatted string.
2152 * RETURNS
2153 * Success: S_OK. pbstrOut contains the formatted value.
2154 * Failure: E_INVALIDARG, if any parameter is invalid.
2155 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2156 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2158 * NOTES
2159 * This function uses LOCALE_USER_DEFAULT when determining the date format
2160 * characters to use.
2161 * Possible values for the nFormat parameter are:
2162 *| Value Meaning
2163 *| ----- -------
2164 *| 0 General date format
2165 *| 1 Long date format
2166 *| 2 Short date format
2167 *| 3 Long time format
2168 *| 4 Short time format
2170 HRESULT WINAPI VarFormatDateTime(LPVARIANT pVarIn, INT nFormat, ULONG dwFlags, BSTR *pbstrOut)
2172 static WCHAR szEmpty[] = L"";
2173 const BYTE* lpFmt = NULL;
2175 TRACE("%s,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), nFormat, dwFlags, pbstrOut);
2177 if (!pVarIn || !pbstrOut || nFormat < 0 || nFormat > 4)
2178 return E_INVALIDARG;
2180 switch (nFormat)
2182 case 0: lpFmt = fmtGeneralDate; break;
2183 case 1: lpFmt = fmtLongDate; break;
2184 case 2: lpFmt = fmtShortDate; break;
2185 case 3: lpFmt = fmtLongTime; break;
2186 case 4: lpFmt = fmtShortTime; break;
2188 return VarFormatFromTokens(pVarIn, szEmpty, (BYTE*)lpFmt, dwFlags,
2189 pbstrOut, LOCALE_USER_DEFAULT);
2192 #define GETLOCALENUMBER(type,field) GetLocaleInfoW(LOCALE_USER_DEFAULT, \
2193 type|LOCALE_RETURN_NUMBER, \
2194 (LPWSTR)&numfmt.field, \
2195 sizeof(numfmt.field)/sizeof(WCHAR))
2197 /**********************************************************************
2198 * VarFormatNumber [OLEAUT32.107]
2200 * Format a variant value as a number.
2202 * PARAMS
2203 * pVarIn [I] Variant to format
2204 * nDigits [I] Number of digits following the decimal point (-1 = user default)
2205 * nLeading [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2206 * nParens [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2207 * nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2208 * dwFlags [I] Currently unused, set to zero
2209 * pbstrOut [O] Destination for formatted string.
2211 * RETURNS
2212 * Success: S_OK. pbstrOut contains the formatted value.
2213 * Failure: E_INVALIDARG, if any parameter is invalid.
2214 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2215 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2217 * NOTES
2218 * This function uses LOCALE_USER_DEFAULT when determining the number format
2219 * characters to use.
2221 HRESULT WINAPI VarFormatNumber(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2222 INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2224 HRESULT hRet;
2225 VARIANT vStr;
2227 TRACE("(%s,%d,%d,%d,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), nDigits, nLeading,
2228 nParens, nGrouping, dwFlags, pbstrOut);
2230 if (!pVarIn || !pbstrOut || nDigits > 9)
2231 return E_INVALIDARG;
2233 *pbstrOut = NULL;
2235 V_VT(&vStr) = VT_EMPTY;
2236 hRet = VariantCopyInd(&vStr, pVarIn);
2238 if (SUCCEEDED(hRet))
2239 hRet = VariantChangeTypeEx(&vStr, &vStr, LCID_US, 0, VT_BSTR);
2241 if (SUCCEEDED(hRet))
2243 WCHAR buff[256], decimal[8], thousands[8];
2244 NUMBERFMTW numfmt;
2246 /* Although MSDN makes it clear that the native versions of these functions
2247 * are implemented using VarTokenizeFormatString()/VarFormatFromTokens(),
2248 * using NLS gives us the same result.
2250 if (nDigits < 0)
2251 GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2252 else
2253 numfmt.NumDigits = nDigits;
2255 if (nLeading == -2)
2256 GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2257 else if (nLeading == -1)
2258 numfmt.LeadingZero = 1;
2259 else
2260 numfmt.LeadingZero = 0;
2262 if (nGrouping == -2)
2264 WCHAR grouping[10];
2265 grouping[2] = '\0';
2266 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SGROUPING, grouping, ARRAY_SIZE(grouping));
2267 numfmt.Grouping = grouping[2] == '2' ? 32 : grouping[0] - '0';
2269 else if (nGrouping == -1)
2270 numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2271 else
2272 numfmt.Grouping = 0; /* 0 = No grouping */
2274 if (nParens == -2)
2275 GETLOCALENUMBER(LOCALE_INEGNUMBER, NegativeOrder);
2276 else if (nParens == -1)
2277 numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2278 else
2279 numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2281 numfmt.lpDecimalSep = decimal;
2282 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal, ARRAY_SIZE(decimal));
2283 numfmt.lpThousandSep = thousands;
2284 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, thousands, ARRAY_SIZE(thousands));
2286 if (GetNumberFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt, buff, ARRAY_SIZE(buff)))
2288 *pbstrOut = SysAllocString(buff);
2289 if (!*pbstrOut)
2290 hRet = E_OUTOFMEMORY;
2292 else
2293 hRet = DISP_E_TYPEMISMATCH;
2295 SysFreeString(V_BSTR(&vStr));
2297 return hRet;
2300 /**********************************************************************
2301 * VarFormatPercent [OLEAUT32.117]
2303 * Format a variant value as a percentage.
2305 * PARAMS
2306 * pVarIn [I] Variant to format
2307 * nDigits [I] Number of digits following the decimal point (-1 = user default)
2308 * nLeading [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2309 * nParens [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2310 * nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2311 * dwFlags [I] Currently unused, set to zero
2312 * pbstrOut [O] Destination for formatted string.
2314 * RETURNS
2315 * Success: S_OK. pbstrOut contains the formatted value.
2316 * Failure: E_INVALIDARG, if any parameter is invalid.
2317 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2318 * DISP_E_OVERFLOW, if overflow occurs during the conversion.
2319 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2321 * NOTES
2322 * This function uses LOCALE_USER_DEFAULT when determining the number format
2323 * characters to use.
2325 HRESULT WINAPI VarFormatPercent(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2326 INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2328 WCHAR buff[256];
2329 HRESULT hRet;
2330 VARIANT vDbl;
2332 TRACE("(%s,%d,%d,%d,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), nDigits, nLeading,
2333 nParens, nGrouping, dwFlags, pbstrOut);
2335 if (!pVarIn || !pbstrOut || nDigits > 9)
2336 return E_INVALIDARG;
2338 *pbstrOut = NULL;
2340 V_VT(&vDbl) = VT_EMPTY;
2341 hRet = VariantCopyInd(&vDbl, pVarIn);
2343 if (SUCCEEDED(hRet))
2345 hRet = VariantChangeTypeEx(&vDbl, &vDbl, LOCALE_USER_DEFAULT, 0, VT_R8);
2347 if (SUCCEEDED(hRet))
2349 if (V_R8(&vDbl) > (R8_MAX / 100.0))
2350 return DISP_E_OVERFLOW;
2352 V_R8(&vDbl) *= 100.0;
2353 hRet = VarFormatNumber(&vDbl, nDigits, nLeading, nParens,
2354 nGrouping, dwFlags, pbstrOut);
2356 if (SUCCEEDED(hRet))
2358 DWORD dwLen = lstrlenW(*pbstrOut);
2359 BOOL bBracket = (*pbstrOut)[dwLen] == ')';
2361 dwLen -= bBracket;
2362 memcpy(buff, *pbstrOut, dwLen * sizeof(WCHAR));
2363 lstrcpyW(buff + dwLen, bBracket ? L"%)" : L"%");
2364 SysFreeString(*pbstrOut);
2365 *pbstrOut = SysAllocString(buff);
2366 if (!*pbstrOut)
2367 hRet = E_OUTOFMEMORY;
2371 return hRet;
2374 /**********************************************************************
2375 * VarFormatCurrency [OLEAUT32.127]
2377 * Format a variant value as a currency.
2379 * PARAMS
2380 * pVarIn [I] Variant to format
2381 * nDigits [I] Number of digits following the decimal point (-1 = user default)
2382 * nLeading [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2383 * nParens [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2384 * nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2385 * dwFlags [I] Currently unused, set to zero
2386 * pbstrOut [O] Destination for formatted string.
2388 * RETURNS
2389 * Success: S_OK. pbstrOut contains the formatted value.
2390 * Failure: E_INVALIDARG, if any parameter is invalid.
2391 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2392 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2394 * NOTES
2395 * This function uses LOCALE_USER_DEFAULT when determining the currency format
2396 * characters to use.
2398 HRESULT WINAPI VarFormatCurrency(LPVARIANT pVarIn, INT nDigits, INT nLeading,
2399 INT nParens, INT nGrouping, ULONG dwFlags,
2400 BSTR *pbstrOut)
2402 HRESULT hRet;
2403 VARIANT vStr;
2404 CY cy;
2406 TRACE("(%s,%d,%d,%d,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), nDigits, nLeading,
2407 nParens, nGrouping, dwFlags, pbstrOut);
2409 if (!pVarIn || !pbstrOut || nDigits > 9)
2410 return E_INVALIDARG;
2412 *pbstrOut = NULL;
2414 if (V_VT(pVarIn) == VT_BSTR || V_VT(pVarIn) == (VT_BSTR | VT_BYREF))
2416 hRet = VarCyFromStr(V_ISBYREF(pVarIn) ? *V_BSTRREF(pVarIn) : V_BSTR(pVarIn), LOCALE_USER_DEFAULT, 0, &cy);
2417 if (FAILED(hRet)) return hRet;
2418 V_VT(&vStr) = VT_CY;
2419 V_CY(&vStr) = cy;
2421 else
2423 V_VT(&vStr) = VT_EMPTY;
2424 hRet = VariantCopyInd(&vStr, pVarIn);
2427 if (SUCCEEDED(hRet))
2428 hRet = VariantChangeTypeEx(&vStr, &vStr, LOCALE_USER_DEFAULT, 0, VT_BSTR);
2430 if (SUCCEEDED(hRet))
2432 WCHAR buff[256], decimal[8], thousands[4], currency[13];
2433 CURRENCYFMTW numfmt;
2435 if (nDigits < 0)
2436 GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2437 else
2438 numfmt.NumDigits = nDigits;
2440 if (nLeading == -2)
2441 GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2442 else if (nLeading == -1)
2443 numfmt.LeadingZero = 1;
2444 else
2445 numfmt.LeadingZero = 0;
2447 if (nGrouping == -2)
2449 WCHAR grouping[10];
2450 grouping[2] = '\0';
2451 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SGROUPING, grouping, ARRAY_SIZE(grouping));
2452 numfmt.Grouping = grouping[2] == '2' ? 32 : grouping[0] - '0';
2454 else if (nGrouping == -1)
2455 numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2456 else
2457 numfmt.Grouping = 0; /* 0 = No grouping */
2459 if (nParens == -2)
2460 GETLOCALENUMBER(LOCALE_INEGCURR, NegativeOrder);
2461 else if (nParens == -1)
2462 numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2463 else
2464 numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2466 GETLOCALENUMBER(LOCALE_ICURRENCY, PositiveOrder);
2468 numfmt.lpDecimalSep = decimal;
2469 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal, ARRAY_SIZE(decimal));
2470 numfmt.lpThousandSep = thousands;
2471 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, thousands, ARRAY_SIZE(thousands));
2472 numfmt.lpCurrencySymbol = currency;
2473 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SCURRENCY, currency, ARRAY_SIZE(currency));
2475 /* use NLS as per VarFormatNumber() */
2476 if (GetCurrencyFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt, buff, ARRAY_SIZE(buff)))
2478 *pbstrOut = SysAllocString(buff);
2479 if (!*pbstrOut)
2480 hRet = E_OUTOFMEMORY;
2482 else
2483 hRet = DISP_E_TYPEMISMATCH;
2485 SysFreeString(V_BSTR(&vStr));
2487 return hRet;
2490 /**********************************************************************
2491 * VarMonthName [OLEAUT32.129]
2493 * Print the specified month as localized name.
2495 * PARAMS
2496 * iMonth [I] month number 1..12
2497 * fAbbrev [I] 0 - full name, !0 - abbreviated name
2498 * dwFlags [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
2499 * pbstrOut [O] Destination for month name
2501 * RETURNS
2502 * Success: S_OK. pbstrOut contains the name.
2503 * Failure: E_INVALIDARG, if any parameter is invalid.
2504 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2506 HRESULT WINAPI VarMonthName(INT iMonth, INT fAbbrev, ULONG dwFlags, BSTR *pbstrOut)
2508 DWORD localeValue;
2509 INT size;
2511 if ((iMonth < 1) || (iMonth > 12))
2512 return E_INVALIDARG;
2514 if (dwFlags)
2515 FIXME("Does not support dwFlags 0x%x, ignoring.\n", dwFlags);
2517 if (fAbbrev)
2518 localeValue = LOCALE_SABBREVMONTHNAME1 + iMonth - 1;
2519 else
2520 localeValue = LOCALE_SMONTHNAME1 + iMonth - 1;
2522 size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, NULL, 0);
2523 if (!size) {
2524 ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2525 return HRESULT_FROM_WIN32(GetLastError());
2527 *pbstrOut = SysAllocStringLen(NULL,size - 1);
2528 if (!*pbstrOut)
2529 return E_OUTOFMEMORY;
2530 size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, *pbstrOut, size);
2531 if (!size) {
2532 ERR("GetLocaleInfo of 0x%x failed in 2nd stage?!\n", localeValue);
2533 SysFreeString(*pbstrOut);
2534 return HRESULT_FROM_WIN32(GetLastError());
2536 return S_OK;
2539 /**********************************************************************
2540 * VarWeekdayName [OLEAUT32.129]
2542 * Print the specified weekday as localized name.
2544 * PARAMS
2545 * iWeekday [I] day of week, 1..7, 1="the first day of the week"
2546 * fAbbrev [I] 0 - full name, !0 - abbreviated name
2547 * iFirstDay [I] first day of week,
2548 * 0=system default, 1=Sunday, 2=Monday, .. (contrary to MSDN)
2549 * dwFlags [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
2550 * pbstrOut [O] Destination for weekday name.
2552 * RETURNS
2553 * Success: S_OK, pbstrOut contains the name.
2554 * Failure: E_INVALIDARG, if any parameter is invalid.
2555 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2557 HRESULT WINAPI VarWeekdayName(INT iWeekday, INT fAbbrev, INT iFirstDay,
2558 ULONG dwFlags, BSTR *pbstrOut)
2560 DWORD localeValue;
2561 INT size;
2563 /* Windows XP oleaut32.dll doesn't allow iWekday==0, contrary to MSDN */
2564 if (iWeekday < 1 || iWeekday > 7)
2565 return E_INVALIDARG;
2566 if (iFirstDay < 0 || iFirstDay > 7)
2567 return E_INVALIDARG;
2568 if (!pbstrOut)
2569 return E_INVALIDARG;
2571 if (dwFlags)
2572 FIXME("Does not support dwFlags 0x%x, ignoring.\n", dwFlags);
2574 /* If we have to use the default firstDay, find which one it is */
2575 if (iFirstDay == 0) {
2576 DWORD firstDay;
2577 localeValue = LOCALE_RETURN_NUMBER | LOCALE_IFIRSTDAYOFWEEK;
2578 size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue,
2579 (LPWSTR)&firstDay, sizeof(firstDay) / sizeof(WCHAR));
2580 if (!size) {
2581 ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2582 return HRESULT_FROM_WIN32(GetLastError());
2584 iFirstDay = firstDay + 2;
2587 /* Determine what we need to return */
2588 localeValue = fAbbrev ? LOCALE_SABBREVDAYNAME1 : LOCALE_SDAYNAME1;
2589 localeValue += (7 + iWeekday - 1 + iFirstDay - 2) % 7;
2591 /* Determine the size of the data, allocate memory and retrieve the data */
2592 size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue, NULL, 0);
2593 if (!size) {
2594 ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2595 return HRESULT_FROM_WIN32(GetLastError());
2597 *pbstrOut = SysAllocStringLen(NULL, size - 1);
2598 if (!*pbstrOut)
2599 return E_OUTOFMEMORY;
2600 size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue, *pbstrOut, size);
2601 if (!size) {
2602 ERR("GetLocaleInfo 0x%x failed in 2nd stage?!\n", localeValue);
2603 SysFreeString(*pbstrOut);
2604 return HRESULT_FROM_WIN32(GetLastError());
2606 return S_OK;