oleaut32: Added VT_BSTR handling to ctl2_add_default_value.
[wine] / dlls / oleaut32 / varformat.c
1 /*
2  * Variant formatting functions
3  *
4  * Copyright 2008 Damjan Jovanovic
5  * Copyright 2003 Jon Griffiths
6  *
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.
11  *
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.
16  *
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
20  *
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.
26  */
27
28 #include "config.h"
29
30 #include <string.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34
35 #define NONAMELESSUNION
36 #define NONAMELESSSTRUCT
37 #include "windef.h"
38 #include "winbase.h"
39 #include "wine/unicode.h"
40 #include "winerror.h"
41 #include "variant.h"
42 #include "wine/debug.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(variant);
45
46 /* Make sure internal conversions to strings use the '.','+'/'-' and ','
47  * format chars from the US locale. This enables us to parse the created
48  * strings to determine the number of decimal places, exponent, etc.
49  */
50 #define LCID_US MAKELCID(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),SORT_DEFAULT)
51
52 static const WCHAR szPercent_d[] = { '%','d','\0' };
53 static const WCHAR szPercentZeroTwo_d[] = { '%','0','2','d','\0' };
54 static const WCHAR szPercentZeroStar_d[] = { '%','0','*','d','\0' };
55
56 #if 0
57 #define dump_tokens(rgb) do { \
58   int i_; TRACE("Tokens->{\n"); \
59   for (i_ = 0; i_ < rgb[0]; i_++) \
60     TRACE("%s0x%02x", i_?",":"",rgb[i_]); \
61   TRACE(" }\n"); \
62   } while(0)
63 #endif
64
65 /******************************************************************************
66  * Variant-Formats {OLEAUT32}
67  *
68  * NOTES
69  *  When formatting a variant a variety of format strings may be used to generate
70  *  different kinds of formatted output. A format string consists of either a named
71  *  format, or a user-defined format.
72  *
73  *  The following named formats are defined:
74  *| Name           Description
75  *| ----           -----------
76  *| General Date   Display Date, and time for non-integer values
77  *| Short Date     Short date format as defined by locale settings
78  *| Medium Date    Medium date format as defined by locale settings
79  *| Long Date      Long date format as defined by locale settings
80  *| Short Time     Short Time format as defined by locale settings
81  *| Medium Time    Medium time format as defined by locale settings
82  *| Long Time      Long time format as defined by locale settings
83  *| True/False     Localised text of "True" or "False"
84  *| Yes/No         Localised text of "Yes" or "No"
85  *| On/Off         Localised text of "On" or "Off"
86  *| General Number No thousands separator. No decimal points for integers
87  *| Currency       General currency format using localised characters
88  *| Fixed          At least one whole and two fractional digits
89  *| Standard       Same as 'Fixed', but including decimal separators
90  *| Percent        Multiply by 100 and display a trailing '%' character
91  *| Scientific     Display with exponent
92  *
93  *  User-defined formats consist of a combination of tokens and literal
94  *  characters. Literal characters are copied unmodified to the formatted
95  *  output at the position they occupy in the format string. Any character
96  *  that is not recognised as a token is treated as a literal. A literal can
97  *  also be specified by preceding it with a backslash character
98  *  (e.g. "\L\i\t\e\r\a\l") or enclosing it in double quotes.
99  *
100  *  A user-defined format can have up to 4 sections, depending on the type of
101  *  format. The following table lists sections and their meaning:
102  *| Format Type  Sections Meaning
103  *| -----------  -------- -------
104  *| Number       1        Use the same format for all numbers
105  *| Number       2        Use format 1 for positive and 2 for negative numbers
106  *| Number       3        Use format 1 for positive, 2 for zero, and 3
107  *|                       for negative numbers.
108  *| Number       4        Use format 1 for positive, 2 for zero, 3 for
109  *|                       negative, and 4 for null numbers.
110  *| String       1        Use the same format for all strings
111  *| String       2        Use format 2 for null and empty strings, otherwise
112  *|                       use format 1.
113  *| Date         1        Use the same format for all dates
114  *
115  *  The formatting tokens fall into several categories depending on the type
116  *  of formatted output. For more information on each type, see
117  *  VarFormat-Dates(), VarFormat-Strings() and VarFormat-Numbers().
118  *
119  *  SEE ALSO
120  *  VarTokenizeFormatString(), VarFormatFromTokens(), VarFormat(),
121  *  VarFormatDateTime(), VarFormatNumber(), VarFormatCurrency().
122  */
123
124 /******************************************************************************
125  * VarFormat-Strings {OLEAUT32}
126  *
127  * NOTES
128  *  When formatting a variant as a string, it is first converted to a VT_BSTR.
129  *  The user-format string defines which characters are copied into which
130  *  positions in the output string. Literals may be inserted in the format
131  *  string. When creating the formatted string, excess characters in the string
132  *  (those not consumed by a token) are appended to the end of the output. If
133  *  there are more tokens than characters in the string to format, spaces will
134  *  be inserted at the start of the string if the '@' token was used.
135  *
136  *  By default strings are converted to lowercase, or uppercase if the '>' token
137  *  is encountered. This applies to the whole string: it is not possible to
138  *  generate a mixed-case output string.
139  *
140  *  In user-defined string formats, the following tokens are recognised:
141  *| Token  Description
142  *| -----  -----------
143  *| '@'    Copy a char from the source, or a space if no chars are left.
144  *| '&'    Copy a char from the source, or write nothing if no chars are left.
145  *| '<'    Output the whole string as lower-case (the default).
146  *| '>'    Output the whole string as upper-case.
147  *| '!'    MSDN indicates that this character should cause right-to-left
148  *|        copying, however tests show that it is tokenised but not processed.
149  */
150
151 /*
152  * Common format definitions
153  */
154
155  /* Format types */
156 #define FMT_TYPE_UNKNOWN 0x0
157 #define FMT_TYPE_GENERAL 0x1
158 #define FMT_TYPE_NUMBER  0x2
159 #define FMT_TYPE_DATE    0x3
160 #define FMT_TYPE_STRING  0x4
161
162 #define FMT_TO_STRING    0x0 /* If header->size == this, act like VB's Str() fn */
163
164 typedef struct tagFMT_SHORT_HEADER
165 {
166   BYTE   size;      /* Size of tokenised block (including header), or FMT_TO_STRING */
167   BYTE   type;      /* Allowable types (FMT_TYPE_*) */
168   BYTE   offset[1]; /* Offset of the first (and only) format section */
169 } FMT_SHORT_HEADER;
170
171 typedef struct tagFMT_HEADER
172 {
173   BYTE   size;      /* Total size of the whole tokenised block (including header) */
174   BYTE   type;      /* Allowable types (FMT_TYPE_*) */
175   BYTE   starts[4]; /* Offset of each of the 4 format sections, or 0 if none */
176 } FMT_HEADER;
177
178 #define FmtGetPositive(x)  (x->starts[0])
179 #define FmtGetNegative(x)  (x->starts[1] ? x->starts[1] : x->starts[0])
180 #define FmtGetZero(x)      (x->starts[2] ? x->starts[2] : x->starts[0])
181 #define FmtGetNull(x)      (x->starts[3] ? x->starts[3] : x->starts[0])
182
183 /*
184  * String formats
185  */
186
187 #define FMT_FLAG_LT  0x1 /* Has '<' (lower case) */
188 #define FMT_FLAG_GT  0x2 /* Has '>' (upper case) */
189 #define FMT_FLAG_RTL 0x4 /* Has '!' (Copy right to left) */
190
191 typedef struct tagFMT_STRING_HEADER
192 {
193   BYTE   flags;      /* LT, GT, RTL */
194   BYTE   unknown1;
195   BYTE   unknown2;
196   BYTE   copy_chars; /* Number of chars to be copied */
197   BYTE   unknown3;
198 } FMT_STRING_HEADER;
199
200 /*
201  * Number formats
202  */
203
204 #define FMT_FLAG_PERCENT   0x1  /* Has '%' (Percentage) */
205 #define FMT_FLAG_EXPONENT  0x2  /* Has 'e' (Exponent/Scientific notation) */
206 #define FMT_FLAG_THOUSANDS 0x4  /* Has ',' (Standard use of the thousands separator) */
207 #define FMT_FLAG_BOOL      0x20 /* Boolean format */
208
209 typedef struct tagFMT_NUMBER_HEADER
210 {
211   BYTE   flags;      /* PERCENT, EXPONENT, THOUSANDS, BOOL */
212   BYTE   multiplier; /* Multiplier, 100 for percentages */
213   BYTE   divisor;    /* Divisor, 1000 if '%%' was used */
214   BYTE   whole;      /* Number of digits before the decimal point */
215   BYTE   fractional; /* Number of digits after the decimal point */
216 } FMT_NUMBER_HEADER;
217
218 /*
219  * Date Formats
220  */
221 typedef struct tagFMT_DATE_HEADER
222 {
223   BYTE   flags;
224   BYTE   unknown1;
225   BYTE   unknown2;
226   BYTE   unknown3;
227   BYTE   unknown4;
228 } FMT_DATE_HEADER;
229
230 /*
231  * Format token values
232  */
233 #define FMT_GEN_COPY        0x00 /* \n, "lit" => 0,pos,len: Copy len chars from input+pos */
234 #define FMT_GEN_INLINE      0x01 /*      => 1,len,[chars]: Copy len chars from token stream */
235 #define FMT_GEN_END         0x02 /* \0,; => 2: End of the tokenised format */
236 #define FMT_DATE_TIME_SEP   0x03 /* Time separator char */
237 #define FMT_DATE_DATE_SEP   0x04 /* Date separator char */
238 #define FMT_DATE_GENERAL    0x05 /* General format date */
239 #define FMT_DATE_QUARTER    0x06 /* Quarter of the year from 1-4 */
240 #define FMT_DATE_TIME_SYS   0x07 /* System long time format */
241 #define FMT_DATE_DAY        0x08 /* Day with no leading 0 */
242 #define FMT_DATE_DAY_0      0x09 /* Day with leading 0 */
243 #define FMT_DATE_DAY_SHORT  0x0A /* Short day name */
244 #define FMT_DATE_DAY_LONG   0x0B /* Long day name */
245 #define FMT_DATE_SHORT      0x0C /* Short date format */
246 #define FMT_DATE_LONG       0x0D /* Long date format */
247 #define FMT_DATE_MEDIUM     0x0E /* Medium date format */
248 #define FMT_DATE_DAY_WEEK   0x0F /* First day of the week */
249 #define FMT_DATE_WEEK_YEAR  0x10 /* First week of the year */
250 #define FMT_DATE_MON        0x11 /* Month with no leading 0 */
251 #define FMT_DATE_MON_0      0x12 /* Month with leading 0 */
252 #define FMT_DATE_MON_SHORT  0x13 /* Short month name */
253 #define FMT_DATE_MON_LONG   0x14 /* Long month name */
254 #define FMT_DATE_YEAR_DOY   0x15 /* Day of the year with no leading 0 */
255 #define FMT_DATE_YEAR_0     0x16 /* 2 digit year with leading 0 */
256 /* NOTE: token 0x17 is not defined, 'yyy' is not valid */
257 #define FMT_DATE_YEAR_LONG  0x18 /* 4 digit year */
258 #define FMT_DATE_MIN        0x1A /* Minutes with no leading 0 */
259 #define FMT_DATE_MIN_0      0x1B /* Minutes with leading 0 */
260 #define FMT_DATE_SEC        0x1C /* Seconds with no leading 0 */
261 #define FMT_DATE_SEC_0      0x1D /* Seconds with leading 0 */
262 #define FMT_DATE_HOUR       0x1E /* Hours with no leading 0 */
263 #define FMT_DATE_HOUR_0     0x1F /* Hours with leading 0 */
264 #define FMT_DATE_HOUR_12    0x20 /* Hours with no leading 0, 12 hour clock */
265 #define FMT_DATE_HOUR_12_0  0x21 /* Hours with leading 0, 12 hour clock */
266 #define FMT_DATE_TIME_UNK2  0x23
267 /* FIXME: probably missing some here */
268 #define FMT_DATE_AMPM_SYS1  0x2E /* AM/PM as defined by system settings */
269 #define FMT_DATE_AMPM_UPPER 0x2F /* Upper-case AM or PM */
270 #define FMT_DATE_A_UPPER    0x30 /* Upper-case A or P */
271 #define FMT_DATE_AMPM_SYS2  0x31 /* AM/PM as defined by system settings */
272 #define FMT_DATE_AMPM_LOWER 0x32 /* Lower-case AM or PM */
273 #define FMT_DATE_A_LOWER    0x33 /* Lower-case A or P */
274 #define FMT_NUM_COPY_ZERO   0x34 /* Copy 1 digit or 0 if no digit */
275 #define FMT_NUM_COPY_SKIP   0x35 /* Copy 1 digit or skip if no digit */
276 #define FMT_NUM_DECIMAL     0x36 /* Decimal separator */
277 #define FMT_NUM_EXP_POS_U   0x37 /* Scientific notation, uppercase, + sign */
278 #define FMT_NUM_EXP_NEG_U   0x38 /* Scientific notation, uppercase, - sign */
279 #define FMT_NUM_EXP_POS_L   0x39 /* Scientific notation, lowercase, + sign */
280 #define FMT_NUM_EXP_NEG_L   0x3A /* Scientific notation, lowercase, - sign */
281 #define FMT_NUM_CURRENCY    0x3B /* Currency symbol */
282 #define FMT_NUM_TRUE_FALSE  0x3D /* Convert to "True" or "False" */
283 #define FMT_NUM_YES_NO      0x3E /* Convert to "Yes" or "No" */
284 #define FMT_NUM_ON_OFF      0x3F /* Convert to "On" or "Off"  */
285 #define FMT_STR_COPY_SPACE  0x40 /* Copy len chars with space if no char */
286 #define FMT_STR_COPY_SKIP   0x41 /* Copy len chars or skip if no char */
287 /* Wine additions */
288 #define FMT_WINE_HOURS_12   0x81 /* Hours using 12 hour clock */
289
290 /* Named Formats and their tokenised values */
291 static const WCHAR szGeneralDate[] = { 'G','e','n','e','r','a','l',' ','D','a','t','e','\0' };
292 static const BYTE fmtGeneralDate[0x0a] =
293 {
294   0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
295   0x0,0x0,0x0,0x0,0x0,
296   FMT_DATE_GENERAL,FMT_GEN_END
297 };
298
299 static const WCHAR szShortDate[] = { 'S','h','o','r','t',' ','D','a','t','e','\0' };
300 static const BYTE fmtShortDate[0x0a] =
301 {
302   0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
303   0x0,0x0,0x0,0x0,0x0,
304   FMT_DATE_SHORT,FMT_GEN_END
305 };
306
307 static const WCHAR szMediumDate[] = { 'M','e','d','i','u','m',' ','D','a','t','e','\0' };
308 static const BYTE fmtMediumDate[0x0a] =
309 {
310   0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
311   0x0,0x0,0x0,0x0,0x0,
312   FMT_DATE_MEDIUM,FMT_GEN_END
313 };
314
315 static const WCHAR szLongDate[] = { 'L','o','n','g',' ','D','a','t','e','\0' };
316 static const BYTE fmtLongDate[0x0a] =
317 {
318   0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
319   0x0,0x0,0x0,0x0,0x0,
320   FMT_DATE_LONG,FMT_GEN_END
321 };
322
323 static const WCHAR szShortTime[] = { 'S','h','o','r','t',' ','T','i','m','e','\0' };
324 static const BYTE fmtShortTime[0x0c] =
325 {
326   0x0c,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
327   0x0,0x0,0x0,0x0,0x0,
328   FMT_DATE_TIME_UNK2,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,FMT_GEN_END
329 };
330
331 static const WCHAR szMediumTime[] = { 'M','e','d','i','u','m',' ','T','i','m','e','\0' };
332 static const BYTE fmtMediumTime[0x11] =
333 {
334   0x11,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
335   0x0,0x0,0x0,0x0,0x0,
336   FMT_DATE_HOUR_12_0,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,
337   FMT_GEN_INLINE,0x01,' ','\0',FMT_DATE_AMPM_SYS1,FMT_GEN_END
338 };
339
340 static const WCHAR szLongTime[] = { 'L','o','n','g',' ','T','i','m','e','\0' };
341 static const BYTE fmtLongTime[0x0d] =
342 {
343   0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
344   0x0,0x0,0x0,0x0,0x0,
345   FMT_DATE_TIME_SYS,FMT_GEN_END
346 };
347
348 static const WCHAR szTrueFalse[] = { 'T','r','u','e','/','F','a','l','s','e','\0' };
349 static const BYTE fmtTrueFalse[0x0d] =
350 {
351   0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
352   FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
353   FMT_NUM_TRUE_FALSE,FMT_GEN_END
354 };
355
356 static const WCHAR szYesNo[] = { 'Y','e','s','/','N','o','\0' };
357 static const BYTE fmtYesNo[0x0d] =
358 {
359   0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
360   FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
361   FMT_NUM_YES_NO,FMT_GEN_END
362 };
363
364 static const WCHAR szOnOff[] = { 'O','n','/','O','f','f','\0' };
365 static const BYTE fmtOnOff[0x0d] =
366 {
367   0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
368   FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
369   FMT_NUM_ON_OFF,FMT_GEN_END
370 };
371
372 static const WCHAR szGeneralNumber[] = { 'G','e','n','e','r','a','l',' ','N','u','m','b','e','r','\0' };
373 static const BYTE fmtGeneralNumber[sizeof(FMT_HEADER)] =
374 {
375   sizeof(FMT_HEADER),FMT_TYPE_GENERAL,sizeof(FMT_HEADER),0x0,0x0,0x0
376 };
377
378 static const WCHAR szCurrency[] = { 'C','u','r','r','e','n','c','y','\0' };
379 static const BYTE fmtCurrency[0x26] =
380 {
381   0x26,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x12,0x0,0x0,
382   /* Positive numbers */
383   FMT_FLAG_THOUSANDS,0xcc,0x0,0x1,0x2,
384   FMT_NUM_CURRENCY,FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,
385   FMT_GEN_END,
386   /* Negative numbers */
387   FMT_FLAG_THOUSANDS,0xcc,0x0,0x1,0x2,
388   FMT_GEN_INLINE,0x1,'(','\0',FMT_NUM_CURRENCY,FMT_NUM_COPY_ZERO,0x1,
389   FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_INLINE,0x1,')','\0',
390   FMT_GEN_END
391 };
392
393 static const WCHAR szFixed[] = { 'F','i','x','e','d','\0' };
394 static const BYTE fmtFixed[0x11] =
395 {
396   0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
397   0x0,0x0,0x0,0x1,0x2,
398   FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
399 };
400
401 static const WCHAR szStandard[] = { 'S','t','a','n','d','a','r','d','\0' };
402 static const BYTE fmtStandard[0x11] =
403 {
404   0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
405   FMT_FLAG_THOUSANDS,0x0,0x0,0x1,0x2,
406   FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
407 };
408
409 static const WCHAR szPercent[] = { 'P','e','r','c','e','n','t','\0' };
410 static const BYTE fmtPercent[0x15] =
411 {
412   0x15,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
413   FMT_FLAG_PERCENT,0x1,0x0,0x1,0x2,
414   FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,
415   FMT_GEN_INLINE,0x1,'%','\0',FMT_GEN_END
416 };
417
418 static const WCHAR szScientific[] = { 'S','c','i','e','n','t','i','f','i','c','\0' };
419 static const BYTE fmtScientific[0x13] =
420 {
421   0x13,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
422   FMT_FLAG_EXPONENT,0x0,0x0,0x1,0x2,
423   FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_NUM_EXP_POS_U,0x2,FMT_GEN_END
424 };
425
426 typedef struct tagNAMED_FORMAT
427 {
428   LPCWSTR name;
429   const BYTE* format;
430 } NAMED_FORMAT;
431
432 /* Format name to tokenised format. Must be kept sorted by name */
433 static const NAMED_FORMAT VARIANT_NamedFormats[] =
434 {
435   { szCurrency, fmtCurrency },
436   { szFixed, fmtFixed },
437   { szGeneralDate, fmtGeneralDate },
438   { szGeneralNumber, fmtGeneralNumber },
439   { szLongDate, fmtLongDate },
440   { szLongTime, fmtLongTime },
441   { szMediumDate, fmtMediumDate },
442   { szMediumTime, fmtMediumTime },
443   { szOnOff, fmtOnOff },
444   { szPercent, fmtPercent },
445   { szScientific, fmtScientific },
446   { szShortDate, fmtShortDate },
447   { szShortTime, fmtShortTime },
448   { szStandard, fmtStandard },
449   { szTrueFalse, fmtTrueFalse },
450   { szYesNo, fmtYesNo }
451 };
452 typedef const NAMED_FORMAT *LPCNAMED_FORMAT;
453
454 static int FormatCompareFn(const void *l, const void *r)
455 {
456   return strcmpiW(((LPCNAMED_FORMAT)l)->name, ((LPCNAMED_FORMAT)r)->name);
457 }
458
459 static inline const BYTE *VARIANT_GetNamedFormat(LPCWSTR lpszFormat)
460 {
461   NAMED_FORMAT key;
462   LPCNAMED_FORMAT fmt;
463
464   key.name = lpszFormat;
465   fmt = bsearch(&key, VARIANT_NamedFormats,
466                                  sizeof(VARIANT_NamedFormats)/sizeof(NAMED_FORMAT),
467                                  sizeof(NAMED_FORMAT), FormatCompareFn);
468   return fmt ? fmt->format : NULL;
469 }
470
471 /* Return an error if the token for the value will not fit in the destination */
472 #define NEED_SPACE(x) if (cbTok < (int)(x)) return TYPE_E_BUFFERTOOSMALL; cbTok -= (x)
473
474 /* Non-zero if the format is unknown or a given type */
475 #define COULD_BE(typ) ((!fmt_number && header->type==FMT_TYPE_UNKNOWN)||header->type==typ)
476
477 /* State during tokenising */
478 #define FMT_STATE_OPEN_COPY     0x1 /* Last token written was a copy */
479 #define FMT_STATE_WROTE_DECIMAL 0x2 /* Already wrote a decimal separator */
480 #define FMT_STATE_SEEN_HOURS    0x4 /* See the hh specifier */
481 #define FMT_STATE_WROTE_MINUTES 0x8 /* Wrote minutes */
482
483 /**********************************************************************
484  *              VarTokenizeFormatString [OLEAUT32.140]
485  *
486  * Convert a format string into tokenised form.
487  *
488  * PARAMS
489  *  lpszFormat [I] Format string to tokenise
490  *  rgbTok     [O] Destination for tokenised format
491  *  cbTok      [I] Size of rgbTok in bytes
492  *  nFirstDay  [I] First day of the week (1-7, or 0 for current system default)
493  *  nFirstWeek [I] How to treat the first week (see notes)
494  *  lcid       [I] Locale Id of the format string
495  *  pcbActual  [O] If non-NULL, filled with the first token generated
496  *
497  * RETURNS
498  *  Success: S_OK. rgbTok contains the tokenised format.
499  *  Failure: E_INVALIDARG, if any argument is invalid.
500  *           TYPE_E_BUFFERTOOSMALL, if rgbTok is not large enough.
501  *
502  * NOTES
503  * Valid values for the nFirstWeek parameter are:
504  *| Value  Meaning
505  *| -----  -------
506  *|   0    Use the current system default
507  *|   1    The first week is that containing Jan 1
508  *|   2    Four or more days of the first week are in the current year
509  *|   3    The first week is 7 days long
510  * See Variant-Formats(), VarFormatFromTokens().
511  */
512 HRESULT WINAPI VarTokenizeFormatString(LPOLESTR lpszFormat, LPBYTE rgbTok,
513                                        int cbTok, int nFirstDay, int nFirstWeek,
514                                        LCID lcid, int *pcbActual)
515 {
516   /* Note: none of these strings should be NUL terminated */
517   static const WCHAR szTTTTT[] = { 't','t','t','t','t' };
518   static const WCHAR szAMPM[] = { 'A','M','P','M' };
519   static const WCHAR szampm[] = { 'a','m','p','m' };
520   static const WCHAR szAMSlashPM[] = { 'A','M','/','P','M' };
521   static const WCHAR szamSlashpm[] = { 'a','m','/','p','m' };
522   const BYTE *namedFmt;
523   FMT_HEADER *header = (FMT_HEADER*)rgbTok;
524   FMT_STRING_HEADER *str_header = (FMT_STRING_HEADER*)(rgbTok + sizeof(FMT_HEADER));
525   FMT_NUMBER_HEADER *num_header = (FMT_NUMBER_HEADER*)str_header;
526   BYTE* pOut = rgbTok + sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER);
527   BYTE* pLastHours = NULL;
528   BYTE fmt_number = 0;
529   DWORD fmt_state = 0;
530   LPCWSTR pFormat = lpszFormat;
531
532   TRACE("(%s,%p,%d,%d,%d,0x%08x,%p)\n", debugstr_w(lpszFormat), rgbTok, cbTok,
533         nFirstDay, nFirstWeek, lcid, pcbActual);
534
535   if (!rgbTok ||
536       nFirstDay < 0 || nFirstDay > 7 || nFirstWeek < 0 || nFirstWeek > 3)
537     return E_INVALIDARG;
538
539   if (!lpszFormat || !*lpszFormat)
540   {
541     /* An empty string means 'general format' */
542     NEED_SPACE(sizeof(BYTE));
543     *rgbTok = FMT_TO_STRING;
544     if (pcbActual)
545       *pcbActual = FMT_TO_STRING;
546     return S_OK;
547   }
548
549   if (cbTok > 255)
550     cbTok = 255; /* Ensure we error instead of wrapping */
551
552   /* Named formats */
553   namedFmt = VARIANT_GetNamedFormat(lpszFormat);
554   if (namedFmt)
555   {
556     NEED_SPACE(namedFmt[0]);
557     memcpy(rgbTok, namedFmt, namedFmt[0]);
558     TRACE("Using pre-tokenised named format %s\n", debugstr_w(lpszFormat));
559     /* FIXME: pcbActual */
560     return S_OK;
561   }
562
563   /* Insert header */
564   NEED_SPACE(sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER));
565   memset(header, 0, sizeof(FMT_HEADER));
566   memset(str_header, 0, sizeof(FMT_STRING_HEADER));
567
568   header->starts[fmt_number] = sizeof(FMT_HEADER);
569
570   while (*pFormat)
571   {
572     /* --------------
573      * General tokens
574      * --------------
575      */
576     if (*pFormat == ';')
577     {
578       while (*pFormat == ';')
579       {
580         TRACE(";\n");
581         if (++fmt_number > 3)
582           return E_INVALIDARG; /* too many formats */
583         pFormat++;
584       }
585       if (*pFormat)
586       {
587         TRACE("New header\n");
588         NEED_SPACE(sizeof(BYTE) + sizeof(FMT_STRING_HEADER));
589         *pOut++ = FMT_GEN_END;
590
591         header->starts[fmt_number] = pOut - rgbTok;
592         str_header = (FMT_STRING_HEADER*)pOut;
593         num_header = (FMT_NUMBER_HEADER*)pOut;
594         memset(str_header, 0, sizeof(FMT_STRING_HEADER));
595         pOut += sizeof(FMT_STRING_HEADER);
596         fmt_state = 0;
597         pLastHours = NULL;
598       }
599     }
600     else if (*pFormat == '\\')
601     {
602       /* Escaped character */
603       if (pFormat[1])
604       {
605         NEED_SPACE(3 * sizeof(BYTE));
606         pFormat++;
607         *pOut++ = FMT_GEN_COPY;
608         *pOut++ = pFormat - lpszFormat;
609         *pOut++ = 0x1;
610         fmt_state |= FMT_STATE_OPEN_COPY;
611         TRACE("'\\'\n");
612       }
613       else
614         fmt_state &= ~FMT_STATE_OPEN_COPY;
615       pFormat++;
616     }
617     else if (*pFormat == '"')
618     {
619       /* Escaped string
620        * Note: Native encodes "" as a copy of length zero. That's just dumb, so
621        * here we avoid encoding anything in this case.
622        */
623       if (!pFormat[1])
624         pFormat++;
625       else if (pFormat[1] == '"')
626       {
627         pFormat += 2;
628       }
629       else
630       {
631         LPCWSTR start = ++pFormat;
632         while (*pFormat && *pFormat != '"')
633           pFormat++;
634         NEED_SPACE(3 * sizeof(BYTE));
635         *pOut++ = FMT_GEN_COPY;
636         *pOut++ = start - lpszFormat;
637         *pOut++ = pFormat - start;
638         if (*pFormat == '"')
639           pFormat++;
640         TRACE("Quoted string pos %d, len %d\n", pOut[-2], pOut[-1]);
641       }
642       fmt_state &= ~FMT_STATE_OPEN_COPY;
643     }
644     /* -------------
645      * Number tokens
646      * -------------
647      */
648     else if (*pFormat == '0' && COULD_BE(FMT_TYPE_NUMBER))
649     {
650       /* Number formats: Digit from number or '0' if no digits
651        * Other formats: Literal
652        * Types the format if found
653        */
654       header->type = FMT_TYPE_NUMBER;
655       NEED_SPACE(2 * sizeof(BYTE));
656       *pOut++ = FMT_NUM_COPY_ZERO;
657       *pOut = 0x0;
658       while (*pFormat == '0')
659       {
660         *pOut = *pOut + 1;
661         pFormat++;
662       }
663       if (fmt_state & FMT_STATE_WROTE_DECIMAL)
664         num_header->fractional += *pOut;
665       else
666         num_header->whole += *pOut;
667       TRACE("%d 0's\n", *pOut);
668       pOut++;
669       fmt_state &= ~FMT_STATE_OPEN_COPY;
670     }
671     else if (*pFormat == '#' && COULD_BE(FMT_TYPE_NUMBER))
672     {
673       /* Number formats: Digit from number or blank if no digits
674        * Other formats: Literal
675        * Types the format if found
676        */
677       header->type = FMT_TYPE_NUMBER;
678       NEED_SPACE(2 * sizeof(BYTE));
679       *pOut++ = FMT_NUM_COPY_SKIP;
680       *pOut = 0x0;
681       while (*pFormat == '#')
682       {
683         *pOut = *pOut + 1;
684         pFormat++;
685       }
686       if (fmt_state & FMT_STATE_WROTE_DECIMAL)
687         num_header->fractional += *pOut;
688       else
689         num_header->whole += *pOut;
690       TRACE("%d #'s\n", *pOut);
691       pOut++;
692       fmt_state &= ~FMT_STATE_OPEN_COPY;
693     }
694     else if (*pFormat == '.' && COULD_BE(FMT_TYPE_NUMBER) &&
695               !(fmt_state & FMT_STATE_WROTE_DECIMAL))
696     {
697       /* Number formats: Decimal separator when 1st seen, literal thereafter
698        * Other formats: Literal
699        * Types the format if found
700        */
701       header->type = FMT_TYPE_NUMBER;
702       NEED_SPACE(sizeof(BYTE));
703       *pOut++ = FMT_NUM_DECIMAL;
704       fmt_state |= FMT_STATE_WROTE_DECIMAL;
705       fmt_state &= ~FMT_STATE_OPEN_COPY;
706       pFormat++;
707       TRACE("decimal sep\n");
708     }
709     else if ((*pFormat == 'e' || *pFormat == 'E') && (pFormat[1] == '-' ||
710               pFormat[1] == '+') && header->type == FMT_TYPE_NUMBER)
711     {
712       /* Number formats: Exponent specifier
713        * Other formats: Literal
714        */
715       num_header->flags |= FMT_FLAG_EXPONENT;
716       NEED_SPACE(2 * sizeof(BYTE));
717       if (*pFormat == 'e') {
718         if (pFormat[1] == '+')
719           *pOut = FMT_NUM_EXP_POS_L;
720         else
721           *pOut = FMT_NUM_EXP_NEG_L;
722       } else {
723         if (pFormat[1] == '+')
724           *pOut = FMT_NUM_EXP_POS_U;
725         else
726           *pOut = FMT_NUM_EXP_NEG_U;
727       }
728       pFormat += 2;
729       *++pOut = 0x0;
730       while (*pFormat == '0')
731       {
732         *pOut = *pOut + 1;
733         pFormat++;
734       }
735       pOut++;
736       TRACE("exponent\n");
737     }
738     /* FIXME: %% => Divide by 1000 */
739     else if (*pFormat == ',' && header->type == FMT_TYPE_NUMBER)
740     {
741       /* Number formats: Use the thousands separator
742        * Other formats: Literal
743        */
744       num_header->flags |= FMT_FLAG_THOUSANDS;
745       pFormat++;
746       fmt_state &= ~FMT_STATE_OPEN_COPY;
747       TRACE("thousands sep\n");
748     }
749     /* -----------
750      * Date tokens
751      * -----------
752      */
753     else if (*pFormat == '/' && COULD_BE(FMT_TYPE_DATE))
754     {
755       /* Date formats: Date separator
756        * Other formats: Literal
757        * Types the format if found
758        */
759       header->type = FMT_TYPE_DATE;
760       NEED_SPACE(sizeof(BYTE));
761       *pOut++ = FMT_DATE_DATE_SEP;
762       pFormat++;
763       fmt_state &= ~FMT_STATE_OPEN_COPY;
764       TRACE("date sep\n");
765     }
766     else if (*pFormat == ':' && COULD_BE(FMT_TYPE_DATE))
767     {
768       /* Date formats: Time separator
769        * Other formats: Literal
770        * Types the format if found
771        */
772       header->type = FMT_TYPE_DATE;
773       NEED_SPACE(sizeof(BYTE));
774       *pOut++ = FMT_DATE_TIME_SEP;
775       pFormat++;
776       fmt_state &= ~FMT_STATE_OPEN_COPY;
777       TRACE("time sep\n");
778     }
779     else if ((*pFormat == 'a' || *pFormat == 'A') &&
780               !strncmpiW(pFormat, szAMPM, sizeof(szAMPM)/sizeof(WCHAR)))
781     {
782       /* Date formats: System AM/PM designation
783        * Other formats: Literal
784        * Types the format if found
785        */
786       header->type = FMT_TYPE_DATE;
787       NEED_SPACE(sizeof(BYTE));
788       pFormat += sizeof(szAMPM)/sizeof(WCHAR);
789       if (!strncmpW(pFormat, szampm, sizeof(szampm)/sizeof(WCHAR)))
790         *pOut++ = FMT_DATE_AMPM_SYS2;
791       else
792         *pOut++ = FMT_DATE_AMPM_SYS1;
793       if (pLastHours)
794         *pLastHours = *pLastHours + 2;
795       TRACE("ampm\n");
796     }
797     else if (*pFormat == 'a' && pFormat[1] == '/' &&
798               (pFormat[2] == 'p' || pFormat[2] == 'P'))
799     {
800       /* Date formats: lowercase a or p designation
801        * Other formats: Literal
802        * Types the format if found
803        */
804       header->type = FMT_TYPE_DATE;
805       NEED_SPACE(sizeof(BYTE));
806       pFormat += 3;
807       *pOut++ = FMT_DATE_A_LOWER;
808       if (pLastHours)
809         *pLastHours = *pLastHours + 2;
810       TRACE("a/p\n");
811     }
812     else if (*pFormat == 'A' && pFormat[1] == '/' &&
813               (pFormat[2] == 'p' || pFormat[2] == 'P'))
814     {
815       /* Date formats: Uppercase a or p designation
816        * Other formats: Literal
817        * Types the format if found
818        */
819       header->type = FMT_TYPE_DATE;
820       NEED_SPACE(sizeof(BYTE));
821       pFormat += 3;
822       *pOut++ = FMT_DATE_A_UPPER;
823       if (pLastHours)
824         *pLastHours = *pLastHours + 2;
825       TRACE("A/P\n");
826     }
827     else if (*pFormat == 'a' &&
828               !strncmpW(pFormat, szamSlashpm, sizeof(szamSlashpm)/sizeof(WCHAR)))
829     {
830       /* Date formats: lowercase AM or PM designation
831        * Other formats: Literal
832        * Types the format if found
833        */
834       header->type = FMT_TYPE_DATE;
835       NEED_SPACE(sizeof(BYTE));
836       pFormat += sizeof(szamSlashpm)/sizeof(WCHAR);
837       *pOut++ = FMT_DATE_AMPM_LOWER;
838       if (pLastHours)
839         *pLastHours = *pLastHours + 2;
840       TRACE("AM/PM\n");
841     }
842     else if (*pFormat == 'A' &&
843               !strncmpW(pFormat, szAMSlashPM, sizeof(szAMSlashPM)/sizeof(WCHAR)))
844     {
845       /* Date formats: Uppercase AM or PM designation
846        * Other formats: Literal
847        * Types the format if found
848        */
849       header->type = FMT_TYPE_DATE;
850       NEED_SPACE(sizeof(BYTE));
851       pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
852       *pOut++ = FMT_DATE_AMPM_UPPER;
853       TRACE("AM/PM\n");
854     }
855     else if (*pFormat == 'c' || *pFormat == 'C')
856     {
857       /* Date formats: General date format
858        * Other formats: Literal
859        * Types the format if found
860        */
861       header->type = FMT_TYPE_DATE;
862       NEED_SPACE(sizeof(BYTE));
863       pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
864       *pOut++ = FMT_DATE_GENERAL;
865       TRACE("gen date\n");
866     }
867     else if ((*pFormat == 'd' || *pFormat == 'D') && COULD_BE(FMT_TYPE_DATE))
868     {
869       /* Date formats: Day specifier
870        * Other formats: Literal
871        * Types the format if found
872        */
873       int count = -1;
874       header->type = FMT_TYPE_DATE;
875       while ((*pFormat == 'd' || *pFormat == 'D') && count < 6)
876       {
877         pFormat++;
878         count++;
879       }
880       NEED_SPACE(sizeof(BYTE));
881       *pOut++ = FMT_DATE_DAY + count;
882       fmt_state &= ~FMT_STATE_OPEN_COPY;
883       /* When we find the days token, reset the seen hours state so that
884        * 'mm' is again written as month when encountered.
885        */
886       fmt_state &= ~FMT_STATE_SEEN_HOURS;
887       TRACE("%d d's\n", count + 1);
888     }
889     else if ((*pFormat == 'h' || *pFormat == 'H') && COULD_BE(FMT_TYPE_DATE))
890     {
891       /* Date formats: Hour specifier
892        * Other formats: Literal
893        * Types the format if found
894        */
895       header->type = FMT_TYPE_DATE;
896       NEED_SPACE(sizeof(BYTE));
897       pFormat++;
898       /* Record the position of the hours specifier - if we encounter
899        * an am/pm specifier we will change the hours from 24 to 12.
900        */
901       pLastHours = pOut;
902       if (*pFormat == 'h' || *pFormat == 'H')
903       {
904         pFormat++;
905         *pOut++ = FMT_DATE_HOUR_0;
906         TRACE("hh\n");
907       }
908       else
909       {
910         *pOut++ = FMT_DATE_HOUR;
911         TRACE("h\n");
912       }
913       fmt_state &= ~FMT_STATE_OPEN_COPY;
914       /* Note that now we have seen an hours token, the next occurrence of
915        * 'mm' indicates minutes, not months.
916        */
917       fmt_state |= FMT_STATE_SEEN_HOURS;
918     }
919     else if ((*pFormat == 'm' || *pFormat == 'M') && COULD_BE(FMT_TYPE_DATE))
920     {
921       /* Date formats: Month specifier (or Minute specifier, after hour specifier)
922        * Other formats: Literal
923        * Types the format if found
924        */
925       int count = -1;
926       header->type = FMT_TYPE_DATE;
927       while ((*pFormat == 'm' || *pFormat == 'M') && count < 4)
928       {
929         pFormat++;
930         count++;
931       }
932       NEED_SPACE(sizeof(BYTE));
933       if (count <= 1 && fmt_state & FMT_STATE_SEEN_HOURS &&
934           !(fmt_state & FMT_STATE_WROTE_MINUTES))
935       {
936         /* We have seen an hours specifier and not yet written a minutes
937          * specifier. Write this as minutes and thereafter as months.
938          */
939         *pOut++ = count == 1 ? FMT_DATE_MIN_0 : FMT_DATE_MIN;
940         fmt_state |= FMT_STATE_WROTE_MINUTES; /* Hereafter write months */
941       }
942       else
943         *pOut++ = FMT_DATE_MON + count; /* Months */
944       fmt_state &= ~FMT_STATE_OPEN_COPY;
945       TRACE("%d m's\n", count + 1);
946     }
947     else if ((*pFormat == 'n' || *pFormat == 'N') && COULD_BE(FMT_TYPE_DATE))
948     {
949       /* Date formats: Minute specifier
950        * Other formats: Literal
951        * Types the format if found
952        */
953       header->type = FMT_TYPE_DATE;
954       NEED_SPACE(sizeof(BYTE));
955       pFormat++;
956       if (*pFormat == 'n' || *pFormat == 'N')
957       {
958         pFormat++;
959         *pOut++ = FMT_DATE_MIN_0;
960         TRACE("nn\n");
961       }
962       else
963       {
964         *pOut++ = FMT_DATE_MIN;
965         TRACE("n\n");
966       }
967       fmt_state &= ~FMT_STATE_OPEN_COPY;
968     }
969     else if ((*pFormat == 'q' || *pFormat == 'Q') && COULD_BE(FMT_TYPE_DATE))
970     {
971       /* Date formats: Quarter specifier
972        * Other formats: Literal
973        * Types the format if found
974        */
975       header->type = FMT_TYPE_DATE;
976       NEED_SPACE(sizeof(BYTE));
977       *pOut++ = FMT_DATE_QUARTER;
978       pFormat++;
979       fmt_state &= ~FMT_STATE_OPEN_COPY;
980       TRACE("quarter\n");
981     }
982     else if ((*pFormat == 's' || *pFormat == 'S') && COULD_BE(FMT_TYPE_DATE))
983     {
984       /* Date formats: Second specifier
985        * Other formats: Literal
986        * Types the format if found
987        */
988       header->type = FMT_TYPE_DATE;
989       NEED_SPACE(sizeof(BYTE));
990       pFormat++;
991       if (*pFormat == 's' || *pFormat == 'S')
992       {
993         pFormat++;
994         *pOut++ = FMT_DATE_SEC_0;
995         TRACE("ss\n");
996       }
997       else
998       {
999         *pOut++ = FMT_DATE_SEC;
1000         TRACE("s\n");
1001       }
1002       fmt_state &= ~FMT_STATE_OPEN_COPY;
1003     }
1004     else if ((*pFormat == 't' || *pFormat == 'T') &&
1005               !strncmpiW(pFormat, szTTTTT, sizeof(szTTTTT)/sizeof(WCHAR)))
1006     {
1007       /* Date formats: System time specifier
1008        * Other formats: Literal
1009        * Types the format if found
1010        */
1011       header->type = FMT_TYPE_DATE;
1012       pFormat += sizeof(szTTTTT)/sizeof(WCHAR);
1013       NEED_SPACE(sizeof(BYTE));
1014       *pOut++ = FMT_DATE_TIME_SYS;
1015       fmt_state &= ~FMT_STATE_OPEN_COPY;
1016     }
1017     else if ((*pFormat == 'w' || *pFormat == 'W') && COULD_BE(FMT_TYPE_DATE))
1018     {
1019       /* Date formats: Week of the year/Day of the week
1020        * Other formats: Literal
1021        * Types the format if found
1022        */
1023       header->type = FMT_TYPE_DATE;
1024       pFormat++;
1025       if (*pFormat == 'w' || *pFormat == 'W')
1026       {
1027         NEED_SPACE(3 * sizeof(BYTE));
1028         pFormat++;
1029         *pOut++ = FMT_DATE_WEEK_YEAR;
1030         *pOut++ = nFirstDay;
1031         *pOut++ = nFirstWeek;
1032         TRACE("ww\n");
1033       }
1034       else
1035       {
1036         NEED_SPACE(2 * sizeof(BYTE));
1037         *pOut++ = FMT_DATE_DAY_WEEK;
1038         *pOut++ = nFirstDay;
1039         TRACE("w\n");
1040       }
1041
1042       fmt_state &= ~FMT_STATE_OPEN_COPY;
1043     }
1044     else if ((*pFormat == 'y' || *pFormat == 'Y') && COULD_BE(FMT_TYPE_DATE))
1045     {
1046       /* Date formats: Day of year/Year specifier
1047        * Other formats: Literal
1048        * Types the format if found
1049        */
1050       int count = -1;
1051       header->type = FMT_TYPE_DATE;
1052       while ((*pFormat == 'y' || *pFormat == 'Y') && count < 4)
1053       {
1054         pFormat++;
1055         count++;
1056       }
1057       if (count == 2)
1058       {
1059         count--; /* 'yyy' has no meaning, despite what MSDN says */
1060         pFormat--;
1061       }
1062       NEED_SPACE(sizeof(BYTE));
1063       *pOut++ = FMT_DATE_YEAR_DOY + count;
1064       fmt_state &= ~FMT_STATE_OPEN_COPY;
1065       TRACE("%d y's\n", count + 1);
1066     }
1067     /* -------------
1068      * String tokens
1069      * -------------
1070      */
1071     else if (*pFormat == '@' && COULD_BE(FMT_TYPE_STRING))
1072     {
1073       /* String formats: Character from string or space if no char
1074        * Other formats: Literal
1075        * Types the format if found
1076        */
1077       header->type = FMT_TYPE_STRING;
1078       NEED_SPACE(2 * sizeof(BYTE));
1079       *pOut++ = FMT_STR_COPY_SPACE;
1080       *pOut = 0x0;
1081       while (*pFormat == '@')
1082       {
1083         *pOut = *pOut + 1;
1084         str_header->copy_chars++;
1085         pFormat++;
1086       }
1087       TRACE("%d @'s\n", *pOut);
1088       pOut++;
1089       fmt_state &= ~FMT_STATE_OPEN_COPY;
1090     }
1091     else if (*pFormat == '&' && COULD_BE(FMT_TYPE_STRING))
1092     {
1093       /* String formats: Character from string or skip if no char
1094        * Other formats: Literal
1095        * Types the format if found
1096        */
1097       header->type = FMT_TYPE_STRING;
1098       NEED_SPACE(2 * sizeof(BYTE));
1099       *pOut++ = FMT_STR_COPY_SKIP;
1100       *pOut = 0x0;
1101       while (*pFormat == '&')
1102       {
1103         *pOut = *pOut + 1;
1104         str_header->copy_chars++;
1105         pFormat++;
1106       }
1107       TRACE("%d &'s\n", *pOut);
1108       pOut++;
1109       fmt_state &= ~FMT_STATE_OPEN_COPY;
1110     }
1111     else if ((*pFormat == '<' || *pFormat == '>') && COULD_BE(FMT_TYPE_STRING))
1112     {
1113       /* String formats: Use upper/lower case
1114        * Other formats: Literal
1115        * Types the format if found
1116        */
1117       header->type = FMT_TYPE_STRING;
1118       if (*pFormat == '<')
1119         str_header->flags |= FMT_FLAG_LT;
1120       else
1121         str_header->flags |= FMT_FLAG_GT;
1122       TRACE("to %s case\n", *pFormat == '<' ? "lower" : "upper");
1123       pFormat++;
1124       fmt_state &= ~FMT_STATE_OPEN_COPY;
1125     }
1126     else if (*pFormat == '!' && COULD_BE(FMT_TYPE_STRING))
1127     {
1128       /* String formats: Copy right to left
1129        * Other formats: Literal
1130        * Types the format if found
1131        */
1132       header->type = FMT_TYPE_STRING;
1133       str_header->flags |= FMT_FLAG_RTL;
1134       pFormat++;
1135       fmt_state &= ~FMT_STATE_OPEN_COPY;
1136       TRACE("copy right-to-left\n");
1137     }
1138     /* --------
1139      * Literals
1140      * --------
1141      */
1142     /* FIXME: [ seems to be ignored */
1143     else
1144     {
1145       if (*pFormat == '%' && header->type == FMT_TYPE_NUMBER)
1146       {
1147         /* Number formats: Percentage indicator, also a literal
1148          * Other formats: Literal
1149          * Doesn't type the format
1150          */
1151         num_header->flags |= FMT_FLAG_PERCENT;
1152       }
1153
1154       if (fmt_state & FMT_STATE_OPEN_COPY)
1155       {
1156         pOut[-1] = pOut[-1] + 1; /* Increase the length of the open copy */
1157         TRACE("extend copy (char '%c'), length now %d\n", *pFormat, pOut[-1]);
1158       }
1159       else
1160       {
1161         /* Create a new open copy */
1162         TRACE("New copy (char '%c')\n", *pFormat);
1163         NEED_SPACE(3 * sizeof(BYTE));
1164         *pOut++ = FMT_GEN_COPY;
1165         *pOut++ = pFormat - lpszFormat;
1166         *pOut++ = 0x1;
1167         fmt_state |= FMT_STATE_OPEN_COPY;
1168       }
1169       pFormat++;
1170     }
1171   }
1172
1173   *pOut++ = FMT_GEN_END;
1174
1175   header->size = pOut - rgbTok;
1176   if (pcbActual)
1177     *pcbActual = header->size;
1178
1179   return S_OK;
1180 }
1181
1182 /* Number formatting state flags */
1183 #define NUM_WROTE_DEC  0x01 /* Written the decimal separator */
1184 #define NUM_WRITE_ON   0x02 /* Started to write the number */
1185 #define NUM_WROTE_SIGN 0x04 /* Written the negative sign */
1186
1187 /* Format a variant using a number format */
1188 static HRESULT VARIANT_FormatNumber(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1189                                     LPBYTE rgbTok, ULONG dwFlags,
1190                                     BSTR *pbstrOut, LCID lcid)
1191 {
1192   BYTE rgbDig[256], *prgbDig;
1193   NUMPARSE np;
1194   int have_int, need_int = 0, have_frac, need_frac, exponent = 0, pad = 0;
1195   WCHAR buff[256], *pBuff = buff;
1196   WCHAR thousandSeparator[32];
1197   VARIANT vString, vBool;
1198   DWORD dwState = 0;
1199   FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1200   FMT_NUMBER_HEADER *numHeader;
1201   const BYTE* pToken = NULL;
1202   HRESULT hRes = S_OK;
1203
1204   TRACE("(%p->(%s%s),%s,%p,0x%08x,%p,0x%08x)\n", pVarIn, debugstr_VT(pVarIn),
1205         debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
1206         lcid);
1207
1208   V_VT(&vString) = VT_EMPTY;
1209   V_VT(&vBool) = VT_BOOL;
1210
1211   if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1212   {
1213     have_int = have_frac = 0;
1214     numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNull(header));
1215     V_BOOL(&vBool) = VARIANT_FALSE;
1216   }
1217   else
1218   {
1219     /* Get a number string from pVarIn, and parse it */
1220     hRes = VariantChangeTypeEx(&vString, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1221     if (FAILED(hRes))
1222       return hRes;
1223
1224     np.cDig = sizeof(rgbDig);
1225     np.dwInFlags = NUMPRS_STD;
1226     hRes = VarParseNumFromStr(V_BSTR(&vString), LCID_US, 0, &np, rgbDig);
1227     if (FAILED(hRes))
1228       return hRes;
1229
1230     have_int = np.cDig;
1231     have_frac = 0;
1232     exponent = np.nPwr10;
1233
1234     /* Figure out which format to use */
1235     if (np.dwOutFlags & NUMPRS_NEG)
1236     {
1237       numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNegative(header));
1238       V_BOOL(&vBool) = VARIANT_TRUE;
1239     }
1240     else if (have_int == 1 && !exponent && rgbDig[0] == 0)
1241     {
1242       numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetZero(header));
1243       V_BOOL(&vBool) = VARIANT_FALSE;
1244     }
1245     else
1246     {
1247       numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetPositive(header));
1248       V_BOOL(&vBool) = VARIANT_TRUE;
1249     }
1250
1251     TRACE("num header: flags = 0x%x, mult=%d, div=%d, whole=%d, fract=%d\n",
1252           numHeader->flags, numHeader->multiplier, numHeader->divisor,
1253           numHeader->whole, numHeader->fractional);
1254
1255     need_int = numHeader->whole;
1256     need_frac = numHeader->fractional;
1257
1258     if (numHeader->flags & FMT_FLAG_PERCENT &&
1259         !(have_int == 1 && !exponent && rgbDig[0] == 0))
1260       exponent += 2;
1261
1262     if (numHeader->flags & FMT_FLAG_EXPONENT)
1263     {
1264       /* Exponent format: length of the integral number part is fixed and
1265          specified by the format. */
1266       pad = need_int - have_int;
1267       exponent -= pad;
1268       if (pad < 0)
1269       {
1270         have_int = need_int;
1271         have_frac -= pad;
1272         pad = 0;
1273       }
1274     }
1275     else
1276     {
1277       /* Convert the exponent */
1278       pad = max(exponent, -have_int);
1279       exponent -= pad;
1280       if (pad < 0)
1281       {
1282         have_int += pad;
1283         have_frac = -pad;
1284         pad = 0;
1285       }
1286       if(exponent < 0 && exponent > (-256 + have_int + have_frac))
1287       {
1288         /* Remove exponent notation */
1289         memmove(rgbDig - exponent, rgbDig, have_int + have_frac);
1290         ZeroMemory(rgbDig, -exponent);
1291         have_frac -= exponent;
1292         exponent = 0;
1293       }
1294     }
1295
1296     /* Rounding the number */
1297     if (have_frac > need_frac)
1298     {
1299       prgbDig = &rgbDig[have_int + need_frac ? need_frac + 1 : 0];
1300       if (*prgbDig < 5) prgbDig--;
1301       have_frac = need_frac;
1302       if (*prgbDig >= 5)
1303       {
1304         while (prgbDig-- > rgbDig && *prgbDig == 9)
1305           *prgbDig = 0;
1306         if (prgbDig < rgbDig)
1307         {
1308           /* We reached the first digit and that was also a 9 */
1309           rgbDig[0] = 1;
1310           if (numHeader->flags & FMT_FLAG_EXPONENT)
1311             exponent++;
1312           else
1313           {
1314             rgbDig[have_int + need_frac] = 0;
1315             if (exponent < 0)
1316               exponent++;
1317             else
1318               have_int++;
1319           }
1320         }
1321         else
1322           (*prgbDig)++;
1323         /* We converted trailing digits to zeroes => have_frac has changed */
1324         while (have_frac > 0 && rgbDig[have_int + have_frac - 1] == 0)
1325           have_frac--;
1326       }
1327     }
1328     TRACE("have_int=%d,need_int=%d,have_frac=%d,need_frac=%d,pad=%d,exp=%d\n",
1329           have_int, need_int, have_frac, need_frac, pad, exponent);
1330   }
1331
1332   if (numHeader->flags & FMT_FLAG_THOUSANDS)
1333   {
1334     if (!GetLocaleInfoW(lcid, LOCALE_STHOUSAND, thousandSeparator,
1335                         sizeof(thousandSeparator)/sizeof(WCHAR)))
1336     {
1337       thousandSeparator[0] = ',';
1338       thousandSeparator[1] = 0;
1339     }
1340   }
1341
1342   pToken = (const BYTE*)numHeader + sizeof(FMT_NUMBER_HEADER);
1343   prgbDig = rgbDig;
1344
1345   while (SUCCEEDED(hRes) && *pToken != FMT_GEN_END)
1346   {
1347     WCHAR defaultChar = '?';
1348     DWORD boolFlag, localeValue = 0;
1349     BOOL shouldAdvance = TRUE;
1350
1351     if (pToken - rgbTok > header->size)
1352     {
1353       ERR("Ran off the end of the format!\n");
1354       hRes = E_INVALIDARG;
1355       goto VARIANT_FormatNumber_Exit;
1356     }
1357
1358     switch (*pToken)
1359     {
1360     case FMT_GEN_COPY:
1361       TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1362       memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1363       pBuff += pToken[2];
1364       pToken += 2;
1365       break;
1366
1367     case FMT_GEN_INLINE:
1368       pToken += 2;
1369       TRACE("copy %s\n", debugstr_a((LPCSTR)pToken));
1370       while (*pToken)
1371         *pBuff++ = *pToken++;
1372       break;
1373
1374     case FMT_NUM_YES_NO:
1375       boolFlag = VAR_BOOLYESNO;
1376       goto VARIANT_FormatNumber_Bool;
1377
1378     case FMT_NUM_ON_OFF:
1379       boolFlag = VAR_BOOLONOFF;
1380       goto VARIANT_FormatNumber_Bool;
1381
1382     case FMT_NUM_TRUE_FALSE:
1383       boolFlag = VAR_LOCALBOOL;
1384
1385 VARIANT_FormatNumber_Bool:
1386       {
1387         BSTR boolStr = NULL;
1388
1389         if (pToken[1] != FMT_GEN_END)
1390         {
1391           ERR("Boolean token not at end of format!\n");
1392           hRes = E_INVALIDARG;
1393           goto VARIANT_FormatNumber_Exit;
1394         }
1395         hRes = VarBstrFromBool(V_BOOL(&vBool), lcid, boolFlag, &boolStr);
1396         if (SUCCEEDED(hRes))
1397         {
1398           strcpyW(pBuff, boolStr);
1399           SysFreeString(boolStr);
1400           while (*pBuff)
1401             pBuff++;
1402         }
1403       }
1404       break;
1405
1406     case FMT_NUM_DECIMAL:
1407       if ((np.dwOutFlags & NUMPRS_NEG) && !(dwState & NUM_WROTE_SIGN) && !header->starts[1])
1408       {
1409         /* last chance for a negative sign in the .# case */
1410         TRACE("write negative sign\n");
1411         localeValue = LOCALE_SNEGATIVESIGN;
1412         defaultChar = '-';
1413         dwState |= NUM_WROTE_SIGN;
1414         shouldAdvance = FALSE;
1415         break;
1416       }
1417       TRACE("write decimal separator\n");
1418       localeValue = LOCALE_SDECIMAL;
1419       defaultChar = '.';
1420       dwState |= NUM_WROTE_DEC;
1421       break;
1422
1423     case FMT_NUM_CURRENCY:
1424       TRACE("write currency symbol\n");
1425       localeValue = LOCALE_SCURRENCY;
1426       defaultChar = '$';
1427       break;
1428
1429     case FMT_NUM_EXP_POS_U:
1430     case FMT_NUM_EXP_POS_L:
1431     case FMT_NUM_EXP_NEG_U:
1432     case FMT_NUM_EXP_NEG_L:
1433       if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_NEG_L)
1434         *pBuff++ = 'e';
1435       else
1436         *pBuff++ = 'E';
1437       if (exponent < 0)
1438       {
1439         *pBuff++ = '-';
1440         sprintfW(pBuff, szPercentZeroStar_d, pToken[1], -exponent);
1441       }
1442       else
1443       {
1444         if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_POS_U)
1445           *pBuff++ = '+';
1446         sprintfW(pBuff, szPercentZeroStar_d, pToken[1], exponent);
1447       }
1448       while (*pBuff)
1449         pBuff++;
1450       pToken++;
1451       break;
1452
1453     case FMT_NUM_COPY_ZERO:
1454       dwState |= NUM_WRITE_ON;
1455       /* Fall through */
1456
1457     case FMT_NUM_COPY_SKIP:
1458       TRACE("write %d %sdigits or %s\n", pToken[1],
1459             dwState & NUM_WROTE_DEC ? "fractional " : "",
1460             *pToken == FMT_NUM_COPY_ZERO ? "0" : "skip");
1461
1462       if (dwState & NUM_WROTE_DEC)
1463       {
1464         int count, i;
1465
1466         if (!(numHeader->flags & FMT_FLAG_EXPONENT) && exponent < 0)
1467         {
1468           /* Pad with 0 before writing the fractional digits */
1469           pad = max(exponent, -pToken[1]);
1470           exponent -= pad;
1471           count = min(have_frac, pToken[1] + pad);
1472           for (i = 0; i > pad; i--)
1473             *pBuff++ = '0';
1474         }
1475         else
1476           count = min(have_frac, pToken[1]);
1477
1478         pad += pToken[1] - count;
1479         have_frac -= count;
1480         while (count--)
1481           *pBuff++ = '0' + *prgbDig++;
1482         if (*pToken == FMT_NUM_COPY_ZERO)
1483         {
1484           for (; pad > 0; pad--)
1485             *pBuff++ = '0'; /* Write zeros for missing trailing digits */
1486         }
1487       }
1488       else
1489       {
1490         int count, count_max, position;
1491
1492         if ((np.dwOutFlags & NUMPRS_NEG) && !(dwState & NUM_WROTE_SIGN) && !header->starts[1])
1493         {
1494           TRACE("write negative sign\n");
1495           localeValue = LOCALE_SNEGATIVESIGN;
1496           defaultChar = '-';
1497           dwState |= NUM_WROTE_SIGN;
1498           shouldAdvance = FALSE;
1499           break;
1500         }
1501
1502         position = have_int + pad;
1503         if (dwState & NUM_WRITE_ON)
1504           position = max(position, need_int);
1505         need_int -= pToken[1];
1506         count_max = have_int + pad - need_int;
1507         if (count_max < 0)
1508             count_max = 0;
1509         if (dwState & NUM_WRITE_ON)
1510         {
1511           count = pToken[1] - count_max;
1512           TRACE("write %d leading zeros\n", count);
1513           while (count-- > 0)
1514           {
1515             *pBuff++ = '0';
1516             if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1517                 position > 1 && (--position % 3) == 0)
1518             {
1519               int k;
1520               TRACE("write thousand separator\n");
1521               for (k = 0; thousandSeparator[k]; k++)
1522                 *pBuff++ = thousandSeparator[k];
1523             }
1524           }
1525         }
1526         if (*pToken == FMT_NUM_COPY_ZERO || have_int > 1 ||
1527             (have_int > 0 && *prgbDig > 0))
1528         {
1529           count = min(count_max, have_int);
1530           count_max -= count;
1531           have_int -= count;
1532           TRACE("write %d whole number digits\n", count);
1533           while (count--)
1534           {
1535             dwState |= NUM_WRITE_ON;
1536             *pBuff++ = '0' + *prgbDig++;
1537             if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1538                 position > 1 && (--position % 3) == 0)
1539             {
1540               int k;
1541               TRACE("write thousand separator\n");
1542               for (k = 0; thousandSeparator[k]; k++)
1543                 *pBuff++ = thousandSeparator[k];
1544             }
1545           }
1546         }
1547         count = min(count_max, pad);
1548         pad -= count;
1549         TRACE("write %d whole trailing 0's\n", count);
1550         while (count--)
1551         {
1552           *pBuff++ = '0';
1553           if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1554               position > 1 && (--position % 3) == 0)
1555           {
1556             int k;
1557             TRACE("write thousand separator\n");
1558             for (k = 0; thousandSeparator[k]; k++)
1559               *pBuff++ = thousandSeparator[k];
1560           }
1561         }
1562       }
1563       pToken++;
1564       break;
1565
1566     default:
1567       ERR("Unknown token 0x%02x!\n", *pToken);
1568       hRes = E_INVALIDARG;
1569       goto VARIANT_FormatNumber_Exit;
1570     }
1571     if (localeValue)
1572     {
1573       if (GetLocaleInfoW(lcid, localeValue, pBuff, 
1574                          sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1575       {
1576         TRACE("added %s\n", debugstr_w(pBuff));
1577         while (*pBuff)
1578           pBuff++;
1579       }
1580       else
1581       {
1582         TRACE("added %d '%c'\n", defaultChar, defaultChar);
1583         *pBuff++ = defaultChar;
1584       }
1585     }
1586     if (shouldAdvance)
1587       pToken++;
1588   }
1589
1590 VARIANT_FormatNumber_Exit:
1591   VariantClear(&vString);
1592   *pBuff = '\0';
1593   TRACE("buff is %s\n", debugstr_w(buff));
1594   if (SUCCEEDED(hRes))
1595   {
1596     *pbstrOut = SysAllocString(buff);
1597     if (!*pbstrOut)
1598       hRes = E_OUTOFMEMORY;
1599   }
1600   return hRes;
1601 }
1602
1603 /* Format a variant using a date format */
1604 static HRESULT VARIANT_FormatDate(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1605                                   LPBYTE rgbTok, ULONG dwFlags,
1606                                   BSTR *pbstrOut, LCID lcid)
1607 {
1608   WCHAR buff[256], *pBuff = buff;
1609   VARIANT vDate;
1610   UDATE udate;
1611   FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1612   FMT_DATE_HEADER *dateHeader;
1613   const BYTE* pToken = NULL;
1614   HRESULT hRes;
1615
1616   TRACE("(%p->(%s%s),%s,%p,0x%08x,%p,0x%08x)\n", pVarIn, debugstr_VT(pVarIn),
1617         debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
1618         lcid);
1619
1620   V_VT(&vDate) = VT_EMPTY;
1621
1622   if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1623   {
1624     dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetNegative(header));
1625     V_DATE(&vDate) = 0;
1626   }
1627   else
1628   {
1629     USHORT usFlags = dwFlags & VARIANT_CALENDAR_HIJRI ? VAR_CALENDAR_HIJRI : 0;
1630
1631     hRes = VariantChangeTypeEx(&vDate, pVarIn, LCID_US, usFlags, VT_DATE);
1632     if (FAILED(hRes))
1633       return hRes;
1634     dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetPositive(header));
1635   }
1636
1637   hRes = VarUdateFromDate(V_DATE(&vDate), 0 /* FIXME: flags? */, &udate);
1638   if (FAILED(hRes))
1639     return hRes;
1640   pToken = (const BYTE*)dateHeader + sizeof(FMT_DATE_HEADER);
1641
1642   while (*pToken != FMT_GEN_END)
1643   {
1644     DWORD dwVal = 0, localeValue = 0, dwFmt = 0;
1645     LPCWSTR szPrintFmt = NULL;
1646     WCHAR defaultChar = '?';
1647
1648     if (pToken - rgbTok > header->size)
1649     {
1650       ERR("Ran off the end of the format!\n");
1651       hRes = E_INVALIDARG;
1652       goto VARIANT_FormatDate_Exit;
1653     }
1654
1655     switch (*pToken)
1656     {
1657     case FMT_GEN_COPY:
1658       TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1659       memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1660       pBuff += pToken[2];
1661       pToken += 2;
1662       break;
1663
1664     case FMT_DATE_TIME_SEP:
1665       TRACE("time separator\n");
1666       localeValue = LOCALE_STIME;
1667       defaultChar = ':';
1668       break;
1669
1670     case FMT_DATE_DATE_SEP:
1671       TRACE("date separator\n");
1672       localeValue = LOCALE_SDATE;
1673       defaultChar = '/';
1674       break;
1675
1676     case FMT_DATE_GENERAL:
1677       {
1678         BSTR date = NULL;
1679         WCHAR *pDate;
1680         hRes = VarBstrFromDate(V_DATE(&vDate), lcid, 0, &date);
1681         if (FAILED(hRes))
1682           goto VARIANT_FormatDate_Exit;
1683         pDate = date;
1684         while (*pDate)
1685           *pBuff++ = *pDate++;
1686         SysFreeString(date);
1687       }
1688       break;
1689
1690     case FMT_DATE_QUARTER:
1691       if (udate.st.wMonth <= 3)
1692         *pBuff++ = '1';
1693       else if (udate.st.wMonth <= 6)
1694         *pBuff++ = '2';
1695       else if (udate.st.wMonth <= 9)
1696         *pBuff++ = '3';
1697       else
1698         *pBuff++ = '4';
1699       break;
1700
1701     case FMT_DATE_TIME_SYS:
1702       {
1703         /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1704         BSTR date = NULL;
1705         WCHAR *pDate;
1706         hRes = VarBstrFromDate(V_DATE(&vDate), lcid, VAR_TIMEVALUEONLY, &date);
1707         if (FAILED(hRes))
1708           goto VARIANT_FormatDate_Exit;
1709         pDate = date;
1710         while (*pDate)
1711           *pBuff++ = *pDate++;
1712         SysFreeString(date);
1713       }
1714       break;
1715
1716     case FMT_DATE_DAY:
1717       szPrintFmt = szPercent_d;
1718       dwVal = udate.st.wDay;
1719       break;
1720
1721     case FMT_DATE_DAY_0:
1722       szPrintFmt = szPercentZeroTwo_d;
1723       dwVal = udate.st.wDay;
1724       break;
1725
1726     case FMT_DATE_DAY_SHORT:
1727       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1728       TRACE("short day\n");
1729       localeValue = LOCALE_SABBREVDAYNAME1 + udate.st.wMonth - 1;
1730       defaultChar = '?';
1731       break;
1732
1733     case FMT_DATE_DAY_LONG:
1734       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1735       TRACE("long day\n");
1736       localeValue = LOCALE_SDAYNAME1 + udate.st.wMonth - 1;
1737       defaultChar = '?';
1738       break;
1739
1740     case FMT_DATE_SHORT:
1741       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1742       dwFmt = LOCALE_SSHORTDATE;
1743       break;
1744
1745     case FMT_DATE_LONG:
1746       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1747       dwFmt = LOCALE_SLONGDATE;
1748       break;
1749
1750     case FMT_DATE_MEDIUM:
1751       FIXME("Medium date treated as long date\n");
1752       dwFmt = LOCALE_SLONGDATE;
1753       break;
1754
1755     case FMT_DATE_DAY_WEEK:
1756       szPrintFmt = szPercent_d;
1757       if (pToken[1])
1758         dwVal = udate.st.wDayOfWeek + 2 - pToken[1];
1759       else
1760       {
1761         GetLocaleInfoW(lcid,LOCALE_RETURN_NUMBER|LOCALE_IFIRSTDAYOFWEEK,
1762                        (LPWSTR)&dwVal, sizeof(dwVal)/sizeof(WCHAR));
1763         dwVal = udate.st.wDayOfWeek + 1 - dwVal;
1764       }
1765       pToken++;
1766       break;
1767
1768     case FMT_DATE_WEEK_YEAR:
1769       szPrintFmt = szPercent_d;
1770       dwVal = udate.wDayOfYear / 7 + 1;
1771       pToken += 2;
1772       FIXME("Ignoring nFirstDay of %d, nFirstWeek of %d\n", pToken[0], pToken[1]);
1773       break;
1774
1775     case FMT_DATE_MON:
1776       szPrintFmt = szPercent_d;
1777       dwVal = udate.st.wMonth;
1778       break;
1779
1780     case FMT_DATE_MON_0:
1781       szPrintFmt = szPercentZeroTwo_d;
1782       dwVal = udate.st.wMonth;
1783       break;
1784
1785     case FMT_DATE_MON_SHORT:
1786       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1787       TRACE("short month\n");
1788       localeValue = LOCALE_SABBREVMONTHNAME1 + udate.st.wMonth - 1;
1789       defaultChar = '?';
1790       break;
1791
1792     case FMT_DATE_MON_LONG:
1793       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1794       TRACE("long month\n");
1795       localeValue = LOCALE_SMONTHNAME1 + udate.st.wMonth - 1;
1796       defaultChar = '?';
1797       break;
1798
1799     case FMT_DATE_YEAR_DOY:
1800       szPrintFmt = szPercent_d;
1801       dwVal = udate.wDayOfYear;
1802       break;
1803
1804     case FMT_DATE_YEAR_0:
1805       szPrintFmt = szPercentZeroTwo_d;
1806       dwVal = udate.st.wYear % 100;
1807       break;
1808
1809     case FMT_DATE_YEAR_LONG:
1810       szPrintFmt = szPercent_d;
1811       dwVal = udate.st.wYear;
1812       break;
1813
1814     case FMT_DATE_MIN:
1815       szPrintFmt = szPercent_d;
1816       dwVal = udate.st.wMinute;
1817       break;
1818
1819     case FMT_DATE_MIN_0:
1820       szPrintFmt = szPercentZeroTwo_d;
1821       dwVal = udate.st.wMinute;
1822       break;
1823
1824     case FMT_DATE_SEC:
1825       szPrintFmt = szPercent_d;
1826       dwVal = udate.st.wSecond;
1827       break;
1828
1829     case FMT_DATE_SEC_0:
1830       szPrintFmt = szPercentZeroTwo_d;
1831       dwVal = udate.st.wSecond;
1832       break;
1833
1834     case FMT_DATE_HOUR:
1835       szPrintFmt = szPercent_d;
1836       dwVal = udate.st.wHour;
1837       break;
1838
1839     case FMT_DATE_HOUR_0:
1840       szPrintFmt = szPercentZeroTwo_d;
1841       dwVal = udate.st.wHour;
1842       break;
1843
1844     case FMT_DATE_HOUR_12:
1845       szPrintFmt = szPercent_d;
1846       dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
1847       break;
1848
1849     case FMT_DATE_HOUR_12_0:
1850       szPrintFmt = szPercentZeroTwo_d;
1851       dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
1852       break;
1853
1854     case FMT_DATE_AMPM_SYS1:
1855     case FMT_DATE_AMPM_SYS2:
1856       localeValue = udate.st.wHour < 12 ? LOCALE_S1159 : LOCALE_S2359;
1857       defaultChar = '?';
1858       break;
1859
1860     case FMT_DATE_AMPM_UPPER:
1861       *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1862       *pBuff++ = 'M';
1863       break;
1864
1865     case FMT_DATE_A_UPPER:
1866       *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1867       break;
1868
1869     case FMT_DATE_AMPM_LOWER:
1870       *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1871       *pBuff++ = 'm';
1872       break;
1873
1874     case FMT_DATE_A_LOWER:
1875       *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1876       break;
1877
1878     default:
1879       ERR("Unknown token 0x%02x!\n", *pToken);
1880       hRes = E_INVALIDARG;
1881       goto VARIANT_FormatDate_Exit;
1882     }
1883     if (localeValue)
1884     {
1885       *pBuff = '\0';
1886       if (GetLocaleInfoW(lcid, localeValue, pBuff,
1887           sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1888       {
1889         TRACE("added %s\n", debugstr_w(pBuff));
1890         while (*pBuff)
1891           pBuff++;
1892       }
1893       else
1894       {
1895         TRACE("added %d %c\n", defaultChar, defaultChar);
1896         *pBuff++ = defaultChar;
1897       }
1898     }
1899     else if (dwFmt)
1900     {
1901       WCHAR fmt_buff[80];
1902
1903       if (!GetLocaleInfoW(lcid, dwFmt, fmt_buff, sizeof(fmt_buff)/sizeof(WCHAR)) ||
1904           !GetDateFormatW(lcid, 0, &udate.st, fmt_buff, pBuff,
1905                           sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1906       {
1907         hRes = E_INVALIDARG;
1908         goto VARIANT_FormatDate_Exit;
1909       }
1910       while (*pBuff)
1911         pBuff++;
1912     }
1913     else if (szPrintFmt)
1914     {
1915       sprintfW(pBuff, szPrintFmt, dwVal);
1916       while (*pBuff)
1917         pBuff++;
1918     }
1919     pToken++;
1920   }
1921
1922 VARIANT_FormatDate_Exit:
1923   *pBuff = '\0';
1924   TRACE("buff is %s\n", debugstr_w(buff));
1925   if (SUCCEEDED(hRes))
1926   {
1927     *pbstrOut = SysAllocString(buff);
1928     if (!*pbstrOut)
1929       hRes = E_OUTOFMEMORY;
1930   }
1931   return hRes;
1932 }
1933
1934 /* Format a variant using a string format */
1935 static HRESULT VARIANT_FormatString(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1936                                     LPBYTE rgbTok, ULONG dwFlags,
1937                                     BSTR *pbstrOut, LCID lcid)
1938 {
1939   static WCHAR szEmpty[] = { '\0' };
1940   WCHAR buff[256], *pBuff = buff;
1941   WCHAR *pSrc;
1942   FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1943   FMT_STRING_HEADER *strHeader;
1944   const BYTE* pToken = NULL;
1945   VARIANT vStr;
1946   int blanks_first;
1947   BOOL bUpper = FALSE;
1948   HRESULT hRes = S_OK;
1949
1950   TRACE("(%p->(%s%s),%s,%p,0x%08x,%p,0x%08x)\n", pVarIn, debugstr_VT(pVarIn),
1951         debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
1952         lcid);
1953
1954   V_VT(&vStr) = VT_EMPTY;
1955
1956   if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1957   {
1958     strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1959     V_BSTR(&vStr) = szEmpty;
1960   }
1961   else
1962   {
1963     hRes = VariantChangeTypeEx(&vStr, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1964     if (FAILED(hRes))
1965       return hRes;
1966
1967     if (V_BSTR(pVarIn)[0] == '\0')
1968       strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1969     else
1970       strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetPositive(header));
1971   }
1972   pSrc = V_BSTR(&vStr);
1973   if ((strHeader->flags & (FMT_FLAG_LT|FMT_FLAG_GT)) == FMT_FLAG_GT)
1974     bUpper = TRUE;
1975   blanks_first = strHeader->copy_chars - strlenW(pSrc);
1976   pToken = (const BYTE*)strHeader + sizeof(FMT_DATE_HEADER);
1977
1978   while (*pToken != FMT_GEN_END)
1979   {
1980     int dwCount = 0;
1981
1982     if (pToken - rgbTok > header->size)
1983     {
1984       ERR("Ran off the end of the format!\n");
1985       hRes = E_INVALIDARG;
1986       goto VARIANT_FormatString_Exit;
1987     }
1988
1989     switch (*pToken)
1990     {
1991     case FMT_GEN_COPY:
1992       TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1993       memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1994       pBuff += pToken[2];
1995       pToken += 2;
1996       break;
1997
1998     case FMT_STR_COPY_SPACE:
1999     case FMT_STR_COPY_SKIP:
2000       dwCount = pToken[1];
2001       if (*pToken == FMT_STR_COPY_SPACE && blanks_first > 0)
2002       {
2003         TRACE("insert %d initial spaces\n", blanks_first);
2004         while (dwCount > 0 && blanks_first > 0)
2005         {
2006           *pBuff++ = ' ';
2007           dwCount--;
2008           blanks_first--;
2009         }
2010       }
2011       TRACE("copy %d chars%s\n", dwCount,
2012             *pToken == FMT_STR_COPY_SPACE ? " with space" :"");
2013       while (dwCount > 0 && *pSrc)
2014       {
2015         if (bUpper)
2016           *pBuff++ = toupperW(*pSrc);
2017         else
2018           *pBuff++ = tolowerW(*pSrc);
2019         dwCount--;
2020         pSrc++;
2021       }
2022       if (*pToken == FMT_STR_COPY_SPACE && dwCount > 0)
2023       {
2024         TRACE("insert %d spaces\n", dwCount);
2025         while (dwCount-- > 0)
2026           *pBuff++ = ' ';
2027       }
2028       pToken++;
2029       break;
2030
2031     default:
2032       ERR("Unknown token 0x%02x!\n", *pToken);
2033       hRes = E_INVALIDARG;
2034       goto VARIANT_FormatString_Exit;
2035     }
2036     pToken++;
2037   }
2038
2039 VARIANT_FormatString_Exit:
2040   /* Copy out any remaining chars */
2041   while (*pSrc)
2042   {
2043     if (bUpper)
2044       *pBuff++ = toupperW(*pSrc);
2045     else
2046       *pBuff++ = tolowerW(*pSrc);
2047     pSrc++;
2048   }
2049   VariantClear(&vStr);
2050   *pBuff = '\0';
2051   TRACE("buff is %s\n", debugstr_w(buff));
2052   if (SUCCEEDED(hRes))
2053   {
2054     *pbstrOut = SysAllocString(buff);
2055     if (!*pbstrOut)
2056       hRes = E_OUTOFMEMORY;
2057   }
2058   return hRes;
2059 }
2060
2061 #define NUMBER_VTBITS (VTBIT_I1|VTBIT_UI1|VTBIT_I2|VTBIT_UI2| \
2062                        VTBIT_I4|VTBIT_UI4|VTBIT_I8|VTBIT_UI8| \
2063                        VTBIT_R4|VTBIT_R8|VTBIT_CY|VTBIT_DECIMAL| \
2064                        VTBIT_BOOL|VTBIT_INT|VTBIT_UINT)
2065
2066 /**********************************************************************
2067  *              VarFormatFromTokens [OLEAUT32.139]
2068  */
2069 HRESULT WINAPI VarFormatFromTokens(LPVARIANT pVarIn, LPOLESTR lpszFormat,
2070                                    LPBYTE rgbTok, ULONG dwFlags,
2071                                    BSTR *pbstrOut, LCID lcid)
2072 {
2073   FMT_SHORT_HEADER *header = (FMT_SHORT_HEADER *)rgbTok;
2074   VARIANT vTmp;
2075   HRESULT hres;
2076
2077   TRACE("(%p,%s,%p,%x,%p,0x%08x)\n", pVarIn, debugstr_w(lpszFormat),
2078           rgbTok, dwFlags, pbstrOut, lcid);
2079
2080   if (!pbstrOut)
2081     return E_INVALIDARG;
2082
2083   *pbstrOut = NULL;
2084
2085   if (!pVarIn || !rgbTok)
2086     return E_INVALIDARG;
2087
2088   if (V_VT(pVarIn) == VT_NULL)
2089     return S_OK;
2090
2091   if (*rgbTok == FMT_TO_STRING || header->type == FMT_TYPE_GENERAL)
2092   {
2093     /* According to MSDN, general format acts somewhat like the 'Str'
2094      * function in Visual Basic.
2095      */
2096 VarFormatFromTokens_AsStr:
2097     V_VT(&vTmp) = VT_EMPTY;
2098     hres = VariantChangeTypeEx(&vTmp, pVarIn, lcid, dwFlags, VT_BSTR);
2099     *pbstrOut = V_BSTR(&vTmp);
2100   }
2101   else
2102   {
2103     if (header->type == FMT_TYPE_NUMBER ||
2104         (header->type == FMT_TYPE_UNKNOWN && ((1 << V_TYPE(pVarIn)) & NUMBER_VTBITS)))
2105     {
2106       hres = VARIANT_FormatNumber(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2107     }
2108     else if (header->type == FMT_TYPE_DATE ||
2109              (header->type == FMT_TYPE_UNKNOWN && V_TYPE(pVarIn) == VT_DATE))
2110     {
2111       hres = VARIANT_FormatDate(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2112     }
2113     else if (header->type == FMT_TYPE_STRING || V_TYPE(pVarIn) == VT_BSTR)
2114     {
2115       hres = VARIANT_FormatString(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2116     }
2117     else
2118     {
2119       ERR("unrecognised format type 0x%02x\n", header->type);
2120       return E_INVALIDARG;
2121     }
2122     /* If the coercion failed, still try to create output, unless the
2123      * VAR_FORMAT_NOSUBSTITUTE flag is set.
2124      */
2125     if ((hres == DISP_E_OVERFLOW || hres == DISP_E_TYPEMISMATCH) &&
2126         !(dwFlags & VAR_FORMAT_NOSUBSTITUTE))
2127       goto VarFormatFromTokens_AsStr;
2128   }
2129
2130   return hres;
2131 }
2132
2133 /**********************************************************************
2134  *              VarFormat [OLEAUT32.87]
2135  *
2136  * Format a variant from a format string.
2137  *
2138  * PARAMS
2139  *  pVarIn     [I] Variant to format
2140  *  lpszFormat [I] Format string (see notes)
2141  *  nFirstDay  [I] First day of the week, (See VarTokenizeFormatString() for details)
2142  *  nFirstWeek [I] First week of the year (See VarTokenizeFormatString() for details)
2143  *  dwFlags    [I] Flags for the format (VAR_ flags from "oleauto.h")
2144  *  pbstrOut   [O] Destination for formatted string.
2145  *
2146  * RETURNS
2147  *  Success: S_OK. pbstrOut contains the formatted value.
2148  *  Failure: E_INVALIDARG, if any parameter is invalid.
2149  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2150  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2151  *
2152  * NOTES
2153  *  - See Variant-Formats for details concerning creating format strings.
2154  *  - This function uses LOCALE_USER_DEFAULT when calling VarTokenizeFormatString()
2155  *    and VarFormatFromTokens().
2156  */
2157 HRESULT WINAPI VarFormat(LPVARIANT pVarIn, LPOLESTR lpszFormat,
2158                          int nFirstDay, int nFirstWeek, ULONG dwFlags,
2159                          BSTR *pbstrOut)
2160 {
2161   BYTE buff[256];
2162   HRESULT hres;
2163
2164   TRACE("(%p->(%s%s),%s,%d,%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2165         debugstr_VF(pVarIn), debugstr_w(lpszFormat), nFirstDay, nFirstWeek,
2166         dwFlags, pbstrOut);
2167
2168   if (!pbstrOut)
2169     return E_INVALIDARG;
2170   *pbstrOut = NULL;
2171
2172   hres = VarTokenizeFormatString(lpszFormat, buff, sizeof(buff), nFirstDay,
2173                                  nFirstWeek, LOCALE_USER_DEFAULT, NULL);
2174   if (SUCCEEDED(hres))
2175     hres = VarFormatFromTokens(pVarIn, lpszFormat, buff, dwFlags,
2176                                pbstrOut, LOCALE_USER_DEFAULT);
2177   TRACE("returning 0x%08x, %s\n", hres, debugstr_w(*pbstrOut));
2178   return hres;
2179 }
2180
2181 /**********************************************************************
2182  *              VarFormatDateTime [OLEAUT32.97]
2183  *
2184  * Format a variant value as a date and/or time.
2185  *
2186  * PARAMS
2187  *  pVarIn    [I] Variant to format
2188  *  nFormat   [I] Format type (see notes)
2189  *  dwFlags   [I] Flags for the format (VAR_ flags from "oleauto.h")
2190  *  pbstrOut  [O] Destination for formatted string.
2191  *
2192  * RETURNS
2193  *  Success: S_OK. pbstrOut contains the formatted value.
2194  *  Failure: E_INVALIDARG, if any parameter is invalid.
2195  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2196  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2197  *
2198  * NOTES
2199  *  This function uses LOCALE_USER_DEFAULT when determining the date format
2200  *  characters to use.
2201  *  Possible values for the nFormat parameter are:
2202  *| Value  Meaning
2203  *| -----  -------
2204  *|   0    General date format
2205  *|   1    Long date format
2206  *|   2    Short date format
2207  *|   3    Long time format
2208  *|   4    Short time format
2209  */
2210 HRESULT WINAPI VarFormatDateTime(LPVARIANT pVarIn, INT nFormat, ULONG dwFlags, BSTR *pbstrOut)
2211 {
2212   static WCHAR szEmpty[] = { '\0' };
2213   const BYTE* lpFmt = NULL;
2214
2215   TRACE("(%p->(%s%s),%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2216         debugstr_VF(pVarIn), nFormat, dwFlags, pbstrOut);
2217
2218   if (!pVarIn || !pbstrOut || nFormat < 0 || nFormat > 4)
2219     return E_INVALIDARG;
2220
2221   switch (nFormat)
2222   {
2223   case 0: lpFmt = fmtGeneralDate; break;
2224   case 1: lpFmt = fmtLongDate; break;
2225   case 2: lpFmt = fmtShortDate; break;
2226   case 3: lpFmt = fmtLongTime; break;
2227   case 4: lpFmt = fmtShortTime; break;
2228   }
2229   return VarFormatFromTokens(pVarIn, szEmpty, (BYTE*)lpFmt, dwFlags,
2230                               pbstrOut, LOCALE_USER_DEFAULT);
2231 }
2232
2233 #define GETLOCALENUMBER(type,field) GetLocaleInfoW(LOCALE_USER_DEFAULT, \
2234                                                    type|LOCALE_RETURN_NUMBER, \
2235                                                    (LPWSTR)&numfmt.field, \
2236                                                    sizeof(numfmt.field)/sizeof(WCHAR))
2237
2238 /**********************************************************************
2239  *              VarFormatNumber [OLEAUT32.107]
2240  *
2241  * Format a variant value as a number.
2242  *
2243  * PARAMS
2244  *  pVarIn    [I] Variant to format
2245  *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
2246  *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2247  *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2248  *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2249  *  dwFlags   [I] Currently unused, set to zero
2250  *  pbstrOut  [O] Destination for formatted string.
2251  *
2252  * RETURNS
2253  *  Success: S_OK. pbstrOut contains the formatted value.
2254  *  Failure: E_INVALIDARG, if any parameter is invalid.
2255  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2256  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2257  *
2258  * NOTES
2259  *  This function uses LOCALE_USER_DEFAULT when determining the number format
2260  *  characters to use.
2261  */
2262 HRESULT WINAPI VarFormatNumber(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2263                                INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2264 {
2265   HRESULT hRet;
2266   VARIANT vStr;
2267
2268   TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2269         debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping, dwFlags, pbstrOut);
2270
2271   if (!pVarIn || !pbstrOut || nDigits > 9)
2272     return E_INVALIDARG;
2273
2274   *pbstrOut = NULL;
2275
2276   V_VT(&vStr) = VT_EMPTY;
2277   hRet = VariantCopyInd(&vStr, pVarIn);
2278
2279   if (SUCCEEDED(hRet))
2280     hRet = VariantChangeTypeEx(&vStr, &vStr, LCID_US, 0, VT_BSTR);
2281
2282   if (SUCCEEDED(hRet))
2283   {
2284     WCHAR buff[256], decimal[8], thousands[8];
2285     NUMBERFMTW numfmt;
2286
2287     /* Although MSDN makes it clear that the native versions of these functions
2288      * are implemented using VarTokenizeFormatString()/VarFormatFromTokens(),
2289      * using NLS gives us the same result.
2290      */
2291     if (nDigits < 0)
2292       GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2293     else
2294       numfmt.NumDigits = nDigits;
2295
2296     if (nLeading == -2)
2297       GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2298     else if (nLeading == -1)
2299       numfmt.LeadingZero = 1;
2300     else
2301       numfmt.LeadingZero = 0;
2302
2303     if (nGrouping == -2)
2304     {
2305       WCHAR grouping[16];
2306       grouping[2] = '\0';
2307       GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, grouping,
2308                      sizeof(grouping)/sizeof(WCHAR));
2309       numfmt.Grouping = grouping[2] == '2' ? 32 : grouping[0] - '0';
2310     }
2311     else if (nGrouping == -1)
2312       numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2313     else
2314       numfmt.Grouping = 0; /* 0 = No grouping */
2315
2316     if (nParens == -2)
2317       GETLOCALENUMBER(LOCALE_INEGNUMBER, NegativeOrder);
2318     else if (nParens == -1)
2319       numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2320     else
2321       numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2322
2323     numfmt.lpDecimalSep = decimal;
2324     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal,
2325                    sizeof(decimal)/sizeof(WCHAR));
2326     numfmt.lpThousandSep = thousands;
2327     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, thousands,
2328                    sizeof(thousands)/sizeof(WCHAR));
2329
2330     if (GetNumberFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
2331                          buff, sizeof(buff)/sizeof(WCHAR)))
2332     {
2333       *pbstrOut = SysAllocString(buff);
2334       if (!*pbstrOut)
2335         hRet = E_OUTOFMEMORY;
2336     }
2337     else
2338       hRet = DISP_E_TYPEMISMATCH;
2339
2340     SysFreeString(V_BSTR(&vStr));
2341   }
2342   return hRet;
2343 }
2344
2345 /**********************************************************************
2346  *              VarFormatPercent [OLEAUT32.117]
2347  *
2348  * Format a variant value as a percentage.
2349  *
2350  * PARAMS
2351  *  pVarIn    [I] Variant to format
2352  *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
2353  *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2354  *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2355  *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2356  *  dwFlags   [I] Currently unused, set to zero
2357  *  pbstrOut  [O] Destination for formatted string.
2358  *
2359  * RETURNS
2360  *  Success: S_OK. pbstrOut contains the formatted value.
2361  *  Failure: E_INVALIDARG, if any parameter is invalid.
2362  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2363  *           DISP_E_OVERFLOW, if overflow occurs during the conversion.
2364  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2365  *
2366  * NOTES
2367  *  This function uses LOCALE_USER_DEFAULT when determining the number format
2368  *  characters to use.
2369  */
2370 HRESULT WINAPI VarFormatPercent(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2371                                 INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2372 {
2373   static const WCHAR szPercent[] = { '%','\0' };
2374   static const WCHAR szPercentBracket[] = { '%',')','\0' };
2375   WCHAR buff[256];
2376   HRESULT hRet;
2377   VARIANT vDbl;
2378
2379   TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2380         debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping,
2381         dwFlags, pbstrOut);
2382
2383   if (!pVarIn || !pbstrOut || nDigits > 9)
2384     return E_INVALIDARG;
2385
2386   *pbstrOut = NULL;
2387
2388   V_VT(&vDbl) = VT_EMPTY;
2389   hRet = VariantCopyInd(&vDbl, pVarIn);
2390
2391   if (SUCCEEDED(hRet))
2392   {
2393     hRet = VariantChangeTypeEx(&vDbl, &vDbl, LOCALE_USER_DEFAULT, 0, VT_R8);
2394
2395     if (SUCCEEDED(hRet))
2396     {
2397       if (V_R8(&vDbl) > (R8_MAX / 100.0))
2398         return DISP_E_OVERFLOW;
2399
2400       V_R8(&vDbl) *= 100.0;
2401       hRet = VarFormatNumber(&vDbl, nDigits, nLeading, nParens,
2402                              nGrouping, dwFlags, pbstrOut);
2403
2404       if (SUCCEEDED(hRet))
2405       {
2406         DWORD dwLen = strlenW(*pbstrOut);
2407         BOOL bBracket = (*pbstrOut)[dwLen] == ')' ? TRUE : FALSE;
2408
2409         dwLen -= bBracket;
2410         memcpy(buff, *pbstrOut, dwLen * sizeof(WCHAR));
2411         strcpyW(buff + dwLen, bBracket ? szPercentBracket : szPercent);
2412         SysFreeString(*pbstrOut);
2413         *pbstrOut = SysAllocString(buff);
2414         if (!*pbstrOut)
2415           hRet = E_OUTOFMEMORY;
2416       }
2417     }
2418   }
2419   return hRet;
2420 }
2421
2422 /**********************************************************************
2423  *              VarFormatCurrency [OLEAUT32.127]
2424  *
2425  * Format a variant value as a currency.
2426  *
2427  * PARAMS
2428  *  pVarIn    [I] Variant to format
2429  *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
2430  *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2431  *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2432  *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2433  *  dwFlags   [I] Currently unused, set to zero
2434  *  pbstrOut  [O] Destination for formatted string.
2435  *
2436  * RETURNS
2437  *  Success: S_OK. pbstrOut contains the formatted value.
2438  *  Failure: E_INVALIDARG, if any parameter is invalid.
2439  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2440  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2441  *
2442  * NOTES
2443  *  This function uses LOCALE_USER_DEFAULT when determining the currency format
2444  *  characters to use.
2445  */
2446 HRESULT WINAPI VarFormatCurrency(LPVARIANT pVarIn, INT nDigits, INT nLeading,
2447                                  INT nParens, INT nGrouping, ULONG dwFlags,
2448                                  BSTR *pbstrOut)
2449 {
2450   HRESULT hRet;
2451   VARIANT vStr;
2452
2453   TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2454         debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping, dwFlags, pbstrOut);
2455
2456   if (!pVarIn || !pbstrOut || nDigits > 9)
2457     return E_INVALIDARG;
2458
2459   *pbstrOut = NULL;
2460
2461   V_VT(&vStr) = VT_EMPTY;
2462   hRet = VariantCopyInd(&vStr, pVarIn);
2463
2464   if (SUCCEEDED(hRet))
2465     hRet = VariantChangeTypeEx(&vStr, &vStr, LOCALE_USER_DEFAULT, 0, VT_BSTR);
2466
2467   if (SUCCEEDED(hRet))
2468   {
2469     WCHAR buff[256], decimal[8], thousands[8], currency[8];
2470     CURRENCYFMTW numfmt;
2471
2472     if (nDigits < 0)
2473       GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2474     else
2475       numfmt.NumDigits = nDigits;
2476
2477     if (nLeading == -2)
2478       GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2479     else if (nLeading == -1)
2480       numfmt.LeadingZero = 1;
2481     else
2482       numfmt.LeadingZero = 0;
2483
2484     if (nGrouping == -2)
2485     {
2486       WCHAR nGrouping[16];
2487       nGrouping[2] = '\0';
2488       GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, nGrouping,
2489                      sizeof(nGrouping)/sizeof(WCHAR));
2490       numfmt.Grouping = nGrouping[2] == '2' ? 32 : nGrouping[0] - '0';
2491     }
2492     else if (nGrouping == -1)
2493       numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2494     else
2495       numfmt.Grouping = 0; /* 0 = No grouping */
2496
2497     if (nParens == -2)
2498       GETLOCALENUMBER(LOCALE_INEGCURR, NegativeOrder);
2499     else if (nParens == -1)
2500       numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2501     else
2502       numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2503
2504     GETLOCALENUMBER(LOCALE_ICURRENCY, PositiveOrder);
2505
2506     numfmt.lpDecimalSep = decimal;
2507     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal,
2508                    sizeof(decimal)/sizeof(WCHAR));
2509     numfmt.lpThousandSep = thousands;
2510     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, thousands,
2511                    sizeof(thousands)/sizeof(WCHAR));
2512     numfmt.lpCurrencySymbol = currency;
2513     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, currency,
2514                    sizeof(currency)/sizeof(WCHAR));
2515
2516     /* use NLS as per VarFormatNumber() */
2517     if (GetCurrencyFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
2518                            buff, sizeof(buff)/sizeof(WCHAR)))
2519     {
2520       *pbstrOut = SysAllocString(buff);
2521       if (!*pbstrOut)
2522         hRet = E_OUTOFMEMORY;
2523     }
2524     else
2525       hRet = DISP_E_TYPEMISMATCH;
2526
2527     SysFreeString(V_BSTR(&vStr));
2528   }
2529   return hRet;
2530 }
2531
2532 /**********************************************************************
2533  *              VarMonthName [OLEAUT32.129]
2534  *
2535  * Print the specified month as localized name.
2536  *
2537  * PARAMS
2538  *  iMonth    [I] month number 1..12
2539  *  fAbbrev   [I] 0 - full name, !0 - abbreviated name
2540  *  dwFlags   [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
2541  *  pbstrOut  [O] Destination for month name
2542  *
2543  * RETURNS
2544  *  Success: S_OK. pbstrOut contains the name.
2545  *  Failure: E_INVALIDARG, if any parameter is invalid.
2546  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2547  */
2548 HRESULT WINAPI VarMonthName(INT iMonth, INT fAbbrev, ULONG dwFlags, BSTR *pbstrOut)
2549 {
2550   DWORD localeValue;
2551   INT size;
2552
2553   if ((iMonth < 1)  || (iMonth > 12))
2554     return E_INVALIDARG;
2555
2556   if (dwFlags)
2557     FIXME("Does not support dwFlags 0x%x, ignoring.\n", dwFlags);
2558
2559   if (fAbbrev)
2560         localeValue = LOCALE_SABBREVMONTHNAME1 + iMonth - 1;
2561   else
2562         localeValue = LOCALE_SMONTHNAME1 + iMonth - 1;
2563
2564   size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, NULL, 0);
2565   if (!size) {
2566     ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2567     return HRESULT_FROM_WIN32(GetLastError());
2568   }
2569   *pbstrOut = SysAllocStringLen(NULL,size - 1);
2570   if (!*pbstrOut)
2571     return E_OUTOFMEMORY;
2572   size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, *pbstrOut, size);
2573   if (!size) {
2574     ERR("GetLocaleInfo of 0x%x failed in 2nd stage?!\n", localeValue);
2575     SysFreeString(*pbstrOut);
2576     return HRESULT_FROM_WIN32(GetLastError());
2577   }
2578   return S_OK;
2579 }
2580
2581 /**********************************************************************
2582  *              VarWeekdayName [OLEAUT32.129]
2583  *
2584  * Print the specified weekday as localized name.
2585  *
2586  * PARAMS
2587  *  iWeekday  [I] day of week, 1..7, 1="the first day of the week"
2588  *  fAbbrev   [I] 0 - full name, !0 - abbreviated name
2589  *  iFirstDay [I] first day of week,
2590  *                0=system default, 1=Sunday, 2=Monday, .. (contrary to MSDN)
2591  *  dwFlags   [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
2592  *  pbstrOut  [O] Destination for weekday name.
2593  *
2594  * RETURNS
2595  *  Success: S_OK, pbstrOut contains the name.
2596  *  Failure: E_INVALIDARG, if any parameter is invalid.
2597  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2598  */
2599 HRESULT WINAPI VarWeekdayName(INT iWeekday, INT fAbbrev, INT iFirstDay,
2600                               ULONG dwFlags, BSTR *pbstrOut)
2601 {
2602   DWORD localeValue;
2603   INT size;
2604
2605   /* Windows XP oleaut32.dll doesn't allow iWekday==0, contrary to MSDN */
2606   if (iWeekday < 1 || iWeekday > 7)
2607     return E_INVALIDARG;
2608   if (iFirstDay < 0 || iFirstDay > 7)
2609     return E_INVALIDARG;
2610   if (!pbstrOut)
2611     return E_INVALIDARG;
2612
2613   if (dwFlags)
2614     FIXME("Does not support dwFlags 0x%x, ignoring.\n", dwFlags);
2615
2616   /* If we have to use the default firstDay, find which one it is */
2617   if (iFirstDay == 0) {
2618     DWORD firstDay;
2619     localeValue = LOCALE_RETURN_NUMBER | LOCALE_IFIRSTDAYOFWEEK;
2620     size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue,
2621                           (LPWSTR)&firstDay, sizeof(firstDay) / sizeof(WCHAR));
2622     if (!size) {
2623       ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2624       return HRESULT_FROM_WIN32(GetLastError());
2625     }
2626     iFirstDay = firstDay + 2;
2627   }
2628
2629   /* Determine what we need to return */
2630   localeValue = fAbbrev ? LOCALE_SABBREVDAYNAME1 : LOCALE_SDAYNAME1;
2631   localeValue += (7 + iWeekday - 1 + iFirstDay - 2) % 7;
2632
2633   /* Determine the size of the data, allocate memory and retrieve the data */
2634   size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue, NULL, 0);
2635   if (!size) {
2636     ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2637     return HRESULT_FROM_WIN32(GetLastError());
2638   }
2639   *pbstrOut = SysAllocStringLen(NULL, size - 1);
2640   if (!*pbstrOut)
2641     return E_OUTOFMEMORY;
2642   size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue, *pbstrOut, size);
2643   if (!size) {
2644     ERR("GetLocaleInfo 0x%x failed in 2nd stage?!\n", localeValue);
2645     SysFreeString(*pbstrOut);
2646     return HRESULT_FROM_WIN32(GetLastError());
2647   }
2648   return S_OK;
2649 }