Mark links to dir with FILE_ATTRIBUTE_REPARSE_POINT, so modern
[wine] / dlls / oleaut32 / varformat.c
1 /*
2  * Variant formatting functions
3  *
4  * Copyright 2003 Jon Griffiths
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  * NOTES
21  *  Since the formatting functions aren't properly documented, I used the
22  *  Visual Basic documentation as a guide to implementing these functions. This
23  *  means that some named or user-defined formats may work slightly differently.
24  *  Please submit a test case if you find a difference.
25  */
26
27 #include "config.h"
28
29 #include <string.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33
34 #define NONAMELESSUNION
35 #define NONAMELESSSTRUCT
36 #include "windef.h"
37 #include "winbase.h"
38 #include "wine/unicode.h"
39 #include "winerror.h"
40 #include "variant.h"
41 #include "wine/debug.h"
42
43 WINE_DEFAULT_DEBUG_CHANNEL(variant);
44
45 /* Make sure internal conversions to strings use the '.','+'/'-' and ','
46  * format chars from the US locale. This enables us to parse the created
47  * strings to determine the number of decimal places, exponent, etc.
48  */
49 #define LCID_US MAKELCID(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),SORT_DEFAULT)
50
51 static const WCHAR szPercent_d[] = { '%','d','\0' };
52 static const WCHAR szPercentZeroTwo_d[] = { '%','0','2','d','\0' };
53 static const WCHAR szPercentZeroFour_d[] = { '%','0','4','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  /* Fomat 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, lowercase, - sign */
279 #define FMT_NUM_EXP_POS_L   0x39 /* Scientific notation, uppercase, + 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 clockhourCopy len chars or skip if no char */
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 = (LPCNAMED_FORMAT)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   FMT_DATE_HEADER *date_header = (FMT_DATE_HEADER*)str_header;
527   BYTE* pOut = rgbTok + sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER);
528   BYTE* pLastHours = NULL;
529   BYTE fmt_number = 0;
530   DWORD fmt_state = 0;
531   LPCWSTR pFormat = lpszFormat;
532
533   TRACE("(%s,%p,%d,%d,%d,0x%08lx,%p)\n", debugstr_w(lpszFormat), rgbTok, cbTok,
534         nFirstDay, nFirstWeek, lcid, pcbActual);
535
536   if (!rgbTok ||
537       nFirstDay < 0 || nFirstDay > 7 || nFirstWeek < 0 || nFirstWeek > 3)
538     return E_INVALIDARG;
539
540   if (!lpszFormat || !*lpszFormat)
541   {
542     /* An empty string means 'general format' */
543     NEED_SPACE(sizeof(BYTE));
544     *rgbTok = FMT_TO_STRING;
545     if (pcbActual)
546       *pcbActual = FMT_TO_STRING;
547     return S_OK;
548   }
549
550   if (cbTok > 255)
551     cbTok = 255; /* Ensure we error instead of wrapping */
552
553   /* Named formats */
554   namedFmt = VARIANT_GetNamedFormat(lpszFormat);
555   if (namedFmt)
556   {
557     NEED_SPACE(namedFmt[0]);
558     memcpy(rgbTok, namedFmt, namedFmt[0]);
559     TRACE("Using pre-tokenised named format %s\n", debugstr_w(lpszFormat));
560     /* FIXME: pcbActual */
561     return S_OK;
562   }
563
564   /* Insert header */
565   NEED_SPACE(sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER));
566   memset(header, 0, sizeof(FMT_HEADER));
567   memset(str_header, 0, sizeof(FMT_STRING_HEADER));
568
569   header->starts[fmt_number] = sizeof(FMT_HEADER);
570
571   while (*pFormat)
572   {
573     /* --------------
574      * General tokens
575      * --------------
576      */
577     if (*pFormat == ';')
578     {
579       while (*pFormat == ';')
580       {
581         TRACE(";\n");
582         if (++fmt_number > 3)
583           return E_INVALIDARG; /* too many formats */
584         pFormat++;
585       }
586       if (*pFormat)
587       {
588         TRACE("New header\n");
589         NEED_SPACE(sizeof(BYTE) + sizeof(FMT_STRING_HEADER));
590         *pOut++ = FMT_GEN_END;
591
592         header->starts[fmt_number] = pOut - rgbTok;
593         str_header = (FMT_STRING_HEADER*)pOut;
594         num_header = (FMT_NUMBER_HEADER*)pOut;
595         date_header = (FMT_DATE_HEADER*)pOut;
596         memset(str_header, 0, sizeof(FMT_STRING_HEADER));
597         pOut += sizeof(FMT_STRING_HEADER);
598         fmt_state = 0;
599         pLastHours = NULL;
600       }
601     }
602     else if (*pFormat == '\\')
603     {
604       /* Escaped character */
605       if (pFormat[1])
606       {
607         NEED_SPACE(3 * sizeof(BYTE));
608         pFormat++;
609         *pOut++ = FMT_GEN_COPY;
610         *pOut++ = pFormat - lpszFormat;
611         *pOut++ = 0x1;
612         fmt_state |= FMT_STATE_OPEN_COPY;
613         TRACE("'\\'\n");
614       }
615       else
616         fmt_state &= ~FMT_STATE_OPEN_COPY;
617       pFormat++;
618     }
619     else if (*pFormat == '"')
620     {
621       /* Escaped string
622        * Note: Native encodes "" as a copy of length zero. That's just dumb, so
623        * here we avoid encoding anything in this case.
624        */
625       if (!pFormat[1])
626         pFormat++;
627       else if (pFormat[1] == '"')
628       {
629         pFormat += 2;
630       }
631       else
632       {
633         LPCWSTR start = ++pFormat;
634         while (*pFormat && *pFormat != '"')
635           pFormat++;
636         NEED_SPACE(3 * sizeof(BYTE));
637         *pOut++ = FMT_GEN_COPY;
638         *pOut++ = start - lpszFormat;
639         *pOut++ = pFormat - start;
640         if (*pFormat == '"')
641           pFormat++;
642         TRACE("Quoted string pos %d, len %d\n", pOut[-2], pOut[-1]);
643       }
644       fmt_state &= ~FMT_STATE_OPEN_COPY;
645     }
646     /* -------------
647      * Number tokens
648      * -------------
649      */
650     else if (*pFormat == '0' && COULD_BE(FMT_TYPE_NUMBER))
651     {
652       /* Number formats: Digit from number or '0' if no digits
653        * Other formats: Literal
654        * Types the format if found
655        */
656       header->type = FMT_TYPE_NUMBER;
657       NEED_SPACE(2 * sizeof(BYTE));
658       *pOut++ = FMT_NUM_COPY_ZERO;
659       *pOut = 0x0;
660       while (*pFormat == '0')
661       {
662         *pOut = *pOut + 1;
663         pFormat++;
664       }
665       if (fmt_state & FMT_STATE_WROTE_DECIMAL)
666         num_header->fractional += *pOut;
667       else
668         num_header->whole += *pOut;
669       TRACE("%d 0's\n", *pOut);
670       pOut++;
671       fmt_state &= ~FMT_STATE_OPEN_COPY;
672     }
673     else if (*pFormat == '#' && COULD_BE(FMT_TYPE_NUMBER))
674     {
675       /* Number formats: Digit from number or blank if no digits
676        * Other formats: Literal
677        * Types the format if found
678        */
679       header->type = FMT_TYPE_NUMBER;
680       NEED_SPACE(2 * sizeof(BYTE));
681       *pOut++ = FMT_NUM_COPY_SKIP;
682       *pOut = 0x0;
683       while (*pFormat == '#')
684       {
685         *pOut = *pOut + 1;
686         pFormat++;
687       }
688       if (fmt_state & FMT_STATE_WROTE_DECIMAL)
689         num_header->fractional += *pOut;
690       else
691         num_header->whole += *pOut;
692       TRACE("%d #'s\n", *pOut);
693       pOut++;
694       fmt_state &= ~FMT_STATE_OPEN_COPY;
695     }
696     else if (*pFormat == '.' && COULD_BE(FMT_TYPE_NUMBER) &&
697               !(fmt_state & FMT_STATE_WROTE_DECIMAL))
698     {
699       /* Number formats: Decimal separator when 1st seen, literal thereafter
700        * Other formats: Literal
701        * Types the format if found
702        */
703       header->type = FMT_TYPE_NUMBER;
704       NEED_SPACE(sizeof(BYTE));
705       *pOut++ = FMT_NUM_DECIMAL;
706       fmt_state |= FMT_STATE_WROTE_DECIMAL;
707       fmt_state &= ~FMT_STATE_OPEN_COPY;
708       pFormat++;
709       TRACE("decimal sep\n");
710     }
711     /* FIXME: E+ E- e+ e- => Exponent */
712     /* FIXME: %% => Divide by 1000 */
713     else if (*pFormat == ',' && header->type == FMT_TYPE_NUMBER)
714     {
715       /* Number formats: Use the thousands separator
716        * Other formats: Literal
717        */
718       num_header->flags |= FMT_FLAG_THOUSANDS;
719       pFormat++;
720       fmt_state &= ~FMT_STATE_OPEN_COPY;
721       TRACE("thousands sep\n");
722     }
723     /* -----------
724      * Date tokens
725      * -----------
726      */
727     else if (*pFormat == '/' && COULD_BE(FMT_TYPE_DATE))
728     {
729       /* Date formats: Date separator
730        * Other formats: Literal
731        * Types the format if found
732        */
733       header->type = FMT_TYPE_DATE;
734       NEED_SPACE(sizeof(BYTE));
735       *pOut++ = FMT_DATE_DATE_SEP;
736       pFormat++;
737       fmt_state &= ~FMT_STATE_OPEN_COPY;
738       TRACE("date sep\n");
739     }
740     else if (*pFormat == ':' && COULD_BE(FMT_TYPE_DATE))
741     {
742       /* Date formats: Time separator
743        * Other formats: Literal
744        * Types the format if found
745        */
746       header->type = FMT_TYPE_DATE;
747       NEED_SPACE(sizeof(BYTE));
748       *pOut++ = FMT_DATE_TIME_SEP;
749       pFormat++;
750       fmt_state &= ~FMT_STATE_OPEN_COPY;
751       TRACE("time sep\n");
752     }
753     else if ((*pFormat == 'a' || *pFormat == 'A') &&
754               !strncmpiW(pFormat, szAMPM, sizeof(szAMPM)/sizeof(WCHAR)))
755     {
756       /* Date formats: System AM/PM designation
757        * Other formats: Literal
758        * Types the format if found
759        */
760       header->type = FMT_TYPE_DATE;
761       NEED_SPACE(sizeof(BYTE));
762       pFormat += sizeof(szAMPM)/sizeof(WCHAR);
763       if (!strncmpW(pFormat, szampm, sizeof(szampm)/sizeof(WCHAR)))
764         *pOut++ = FMT_DATE_AMPM_SYS2;
765       else
766         *pOut++ = FMT_DATE_AMPM_SYS1;
767       if (pLastHours)
768         *pLastHours = *pLastHours + 2;
769       TRACE("ampm\n");
770     }
771     else if (*pFormat == 'a' && pFormat[1] == '/' &&
772               (pFormat[2] == 'p' || pFormat[2] == 'P'))
773     {
774       /* Date formats: lowercase a or p designation
775        * Other formats: Literal
776        * Types the format if found
777        */
778       header->type = FMT_TYPE_DATE;
779       NEED_SPACE(sizeof(BYTE));
780       pFormat += 3;
781       *pOut++ = FMT_DATE_A_LOWER;
782       if (pLastHours)
783         *pLastHours = *pLastHours + 2;
784       TRACE("a/p\n");
785     }
786     else if (*pFormat == 'A' && pFormat[1] == '/' &&
787               (pFormat[2] == 'p' || pFormat[2] == 'P'))
788     {
789       /* Date formats: Uppercase a or p designation
790        * Other formats: Literal
791        * Types the format if found
792        */
793       header->type = FMT_TYPE_DATE;
794       NEED_SPACE(sizeof(BYTE));
795       pFormat += 3;
796       *pOut++ = FMT_DATE_A_UPPER;
797       if (pLastHours)
798         *pLastHours = *pLastHours + 2;
799       TRACE("A/P\n");
800     }
801     else if (*pFormat == 'a' &&
802               !strncmpW(pFormat, szamSlashpm, sizeof(szamSlashpm)/sizeof(WCHAR)))
803     {
804       /* Date formats: lowercase AM or PM designation
805        * Other formats: Literal
806        * Types the format if found
807        */
808       header->type = FMT_TYPE_DATE;
809       NEED_SPACE(sizeof(BYTE));
810       pFormat += sizeof(szamSlashpm)/sizeof(WCHAR);
811       *pOut++ = FMT_DATE_AMPM_LOWER;
812       if (pLastHours)
813         *pLastHours = *pLastHours + 2;
814       TRACE("AM/PM\n");
815     }
816     else if (*pFormat == 'A' &&
817               !strncmpW(pFormat, szAMSlashPM, sizeof(szAMSlashPM)/sizeof(WCHAR)))
818     {
819       /* Date formats: Uppercase AM or PM designation
820        * Other formats: Literal
821        * Types the format if found
822        */
823       header->type = FMT_TYPE_DATE;
824       NEED_SPACE(sizeof(BYTE));
825       pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
826       *pOut++ = FMT_DATE_AMPM_UPPER;
827       TRACE("AM/PM\n");
828     }
829     else if (*pFormat == 'c' || *pFormat == 'C')
830     {
831       /* Date formats: General date format
832        * Other formats: Literal
833        * Types the format if found
834        */
835       header->type = FMT_TYPE_DATE;
836       NEED_SPACE(sizeof(BYTE));
837       pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
838       *pOut++ = FMT_DATE_GENERAL;
839       TRACE("gen date\n");
840     }
841     else if ((*pFormat == 'd' || *pFormat == 'D') && COULD_BE(FMT_TYPE_DATE))
842     {
843       /* Date formats: Day specifier
844        * Other formats: Literal
845        * Types the format if found
846        */
847       int count = -1;
848       header->type = FMT_TYPE_DATE;
849       while ((*pFormat == 'd' || *pFormat == 'D') && count < 6)
850       {
851         pFormat++;
852         count++;
853       }
854       NEED_SPACE(sizeof(BYTE));
855       *pOut++ = FMT_DATE_DAY + count;
856       fmt_state &= ~FMT_STATE_OPEN_COPY;
857       /* When we find the days token, reset the seen hours state so that
858        * 'mm' is again written as month when encountered.
859        */
860       fmt_state &= ~FMT_STATE_SEEN_HOURS;
861       TRACE("%d d's\n", count + 1);
862     }
863     else if ((*pFormat == 'h' || *pFormat == 'H') && COULD_BE(FMT_TYPE_DATE))
864     {
865       /* Date formats: Hour specifier
866        * Other formats: Literal
867        * Types the format if found
868        */
869       header->type = FMT_TYPE_DATE;
870       NEED_SPACE(sizeof(BYTE));
871       pFormat++;
872       /* Record the position of the hours specifier - if we encounter
873        * an am/pm specifier we will change the hours from 24 to 12.
874        */
875       pLastHours = pOut;
876       if (*pFormat == 'h' || *pFormat == 'H')
877       {
878         pFormat++;
879         *pOut++ = FMT_DATE_HOUR_0;
880         TRACE("hh\n");
881       }
882       else
883       {
884         *pOut++ = FMT_DATE_HOUR;
885         TRACE("h\n");
886       }
887       fmt_state &= ~FMT_STATE_OPEN_COPY;
888       /* Note that now we have seen an hours token, the next occurrence of
889        * 'mm' indicates minutes, not months.
890        */
891       fmt_state |= FMT_STATE_SEEN_HOURS;
892     }
893     else if ((*pFormat == 'm' || *pFormat == 'M') && COULD_BE(FMT_TYPE_DATE))
894     {
895       /* Date formats: Month specifier (or Minute specifier, after hour specifier)
896        * Other formats: Literal
897        * Types the format if found
898        */
899       int count = -1;
900       header->type = FMT_TYPE_DATE;
901       while ((*pFormat == 'm' || *pFormat == 'M') && count < 4)
902       {
903         pFormat++;
904         count++;
905       }
906       NEED_SPACE(sizeof(BYTE));
907       if (count <= 1 && fmt_state & FMT_STATE_SEEN_HOURS &&
908           !(fmt_state & FMT_STATE_WROTE_MINUTES))
909       {
910         /* We have seen an hours specifier and not yet written a minutes
911          * specifier. Write this as minutes and thereafter as months.
912          */
913         *pOut++ = count == 1 ? FMT_DATE_MIN_0 : FMT_DATE_MIN;
914         fmt_state |= FMT_STATE_WROTE_MINUTES; /* Hereafter write months */
915       }
916       else
917         *pOut++ = FMT_DATE_MON + count; /* Months */
918       fmt_state &= ~FMT_STATE_OPEN_COPY;
919       TRACE("%d m's\n", count + 1);
920     }
921     else if ((*pFormat == 'n' || *pFormat == 'N') && COULD_BE(FMT_TYPE_DATE))
922     {
923       /* Date formats: Minute specifier
924        * Other formats: Literal
925        * Types the format if found
926        */
927       header->type = FMT_TYPE_DATE;
928       NEED_SPACE(sizeof(BYTE));
929       pFormat++;
930       if (*pFormat == 'n' || *pFormat == 'N')
931       {
932         pFormat++;
933         *pOut++ = FMT_DATE_MIN_0;
934         TRACE("nn\n");
935       }
936       else
937       {
938         *pOut++ = FMT_DATE_MIN;
939         TRACE("n\n");
940       }
941       fmt_state &= ~FMT_STATE_OPEN_COPY;
942     }
943     else if ((*pFormat == 'q' || *pFormat == 'q') && COULD_BE(FMT_TYPE_DATE))
944     {
945       /* Date formats: Quarter specifier
946        * Other formats: Literal
947        * Types the format if found
948        */
949       header->type = FMT_TYPE_DATE;
950       NEED_SPACE(sizeof(BYTE));
951       *pOut++ = FMT_DATE_QUARTER;
952       pFormat++;
953       fmt_state &= ~FMT_STATE_OPEN_COPY;
954       TRACE("quarter\n");
955     }
956     else if ((*pFormat == 's' || *pFormat == 'S') && COULD_BE(FMT_TYPE_DATE))
957     {
958       /* Date formats: Second specifier
959        * Other formats: Literal
960        * Types the format if found
961        */
962       header->type = FMT_TYPE_DATE;
963       NEED_SPACE(sizeof(BYTE));
964       pFormat++;
965       if (*pFormat == 's' || *pFormat == 'S')
966       {
967         pFormat++;
968         *pOut++ = FMT_DATE_SEC_0;
969         TRACE("ss\n");
970       }
971       else
972       {
973         *pOut++ = FMT_DATE_SEC;
974         TRACE("s\n");
975       }
976       fmt_state &= ~FMT_STATE_OPEN_COPY;
977     }
978     else if ((*pFormat == 't' || *pFormat == 'T') &&
979               !strncmpiW(pFormat, szTTTTT, sizeof(szTTTTT)/sizeof(WCHAR)))
980     {
981       /* Date formats: System time specifier
982        * Other formats: Literal
983        * Types the format if found
984        */
985       header->type = FMT_TYPE_DATE;
986       pFormat += sizeof(szTTTTT)/sizeof(WCHAR);
987       NEED_SPACE(sizeof(BYTE));
988       *pOut++ = FMT_DATE_TIME_SYS;
989       fmt_state &= ~FMT_STATE_OPEN_COPY;
990     }
991     else if ((*pFormat == 'w' || *pFormat == 'W') && COULD_BE(FMT_TYPE_DATE))
992     {
993       /* Date formats: Week of the year/Day of the week
994        * Other formats: Literal
995        * Types the format if found
996        */
997       header->type = FMT_TYPE_DATE;
998       pFormat++;
999       if (*pFormat == 'w' || *pFormat == 'W')
1000       {
1001         NEED_SPACE(3 * sizeof(BYTE));
1002         pFormat++;
1003         *pOut++ = FMT_DATE_WEEK_YEAR;
1004         *pOut++ = nFirstDay;
1005         *pOut++ = nFirstWeek;
1006         TRACE("ww\n");
1007       }
1008       else
1009       {
1010         NEED_SPACE(2 * sizeof(BYTE));
1011         *pOut++ = FMT_DATE_DAY_WEEK;
1012         *pOut++ = nFirstDay;
1013         TRACE("w\n");
1014       }
1015
1016       fmt_state &= ~FMT_STATE_OPEN_COPY;
1017     }
1018     else if ((*pFormat == 'y' || *pFormat == 'Y') && COULD_BE(FMT_TYPE_DATE))
1019     {
1020       /* Date formats: Day of year/Year specifier
1021        * Other formats: Literal
1022        * Types the format if found
1023        */
1024       int count = -1;
1025       header->type = FMT_TYPE_DATE;
1026       while ((*pFormat == 'y' || *pFormat == 'Y') && count < 4)
1027       {
1028         pFormat++;
1029         count++;
1030       }
1031       if (count == 2)
1032       {
1033         count--; /* 'yyy' has no meaning, despite what MSDN says */
1034         pFormat--;
1035       }
1036       NEED_SPACE(sizeof(BYTE));
1037       *pOut++ = FMT_DATE_YEAR_DOY + count;
1038       fmt_state &= ~FMT_STATE_OPEN_COPY;
1039       TRACE("%d y's\n", count + 1);
1040     }
1041     /* -------------
1042      * String tokens
1043      * -------------
1044      */
1045     else if (*pFormat == '@' && COULD_BE(FMT_TYPE_STRING))
1046     {
1047       /* String formats: Character from string or space if no char
1048        * Other formats: Literal
1049        * Types the format if found
1050        */
1051       header->type = FMT_TYPE_STRING;
1052       NEED_SPACE(2 * sizeof(BYTE));
1053       *pOut++ = FMT_STR_COPY_SPACE;
1054       *pOut = 0x0;
1055       while (*pFormat == '@')
1056       {
1057         *pOut = *pOut + 1;
1058         str_header->copy_chars++;
1059         pFormat++;
1060       }
1061       TRACE("%d @'s\n", *pOut);
1062       pOut++;
1063       fmt_state &= ~FMT_STATE_OPEN_COPY;
1064     }
1065     else if (*pFormat == '&' && COULD_BE(FMT_TYPE_STRING))
1066     {
1067       /* String formats: Character from string or skip if no char
1068        * Other formats: Literal
1069        * Types the format if found
1070        */
1071       header->type = FMT_TYPE_STRING;
1072       NEED_SPACE(2 * sizeof(BYTE));
1073       *pOut++ = FMT_STR_COPY_SKIP;
1074       *pOut = 0x0;
1075       while (*pFormat == '&')
1076       {
1077         *pOut = *pOut + 1;
1078         str_header->copy_chars++;
1079         pFormat++;
1080       }
1081       TRACE("%d &'s\n", *pOut);
1082       pOut++;
1083       fmt_state &= ~FMT_STATE_OPEN_COPY;
1084     }
1085     else if ((*pFormat == '<' || *pFormat == '>') && COULD_BE(FMT_TYPE_STRING))
1086     {
1087       /* String formats: Use upper/lower case
1088        * Other formats: Literal
1089        * Types the format if found
1090        */
1091       header->type = FMT_TYPE_STRING;
1092       if (*pFormat == '<')
1093         str_header->flags |= FMT_FLAG_LT;
1094       else
1095         str_header->flags |= FMT_FLAG_GT;
1096       TRACE("to %s case\n", *pFormat == '<' ? "lower" : "upper");
1097       pFormat++;
1098       fmt_state &= ~FMT_STATE_OPEN_COPY;
1099     }
1100     else if (*pFormat == '!' && COULD_BE(FMT_TYPE_STRING))
1101     {
1102       /* String formats: Copy right to left
1103        * Other formats: Literal
1104        * Types the format if found
1105        */
1106       header->type = FMT_TYPE_STRING;
1107       str_header->flags |= FMT_FLAG_RTL;
1108       pFormat++;
1109       fmt_state &= ~FMT_STATE_OPEN_COPY;
1110       TRACE("copy right-to-left\n");
1111     }
1112     /* --------
1113      * Literals
1114      * --------
1115      */
1116     /* FIXME: [ seems to be ignored */
1117     else
1118     {
1119       if (*pFormat == '%' && header->type == FMT_TYPE_NUMBER)
1120       {
1121         /* Number formats: Percentage indicator, also a literal
1122          * Other formats: Literal
1123          * Doesn't type the format
1124          */
1125         num_header->flags |= FMT_FLAG_PERCENT;
1126       }
1127
1128       if (fmt_state & FMT_STATE_OPEN_COPY)
1129       {
1130         pOut[-1] = pOut[-1] + 1; /* Increase the length of the open copy */
1131         TRACE("extend copy (char '%c'), length now %d\n", *pFormat, pOut[-1]);
1132       }
1133       else
1134       {
1135         /* Create a new open copy */
1136         TRACE("New copy (char '%c')\n", *pFormat);
1137         NEED_SPACE(3 * sizeof(BYTE));
1138         *pOut++ = FMT_GEN_COPY;
1139         *pOut++ = pFormat - lpszFormat;
1140         *pOut++ = 0x1;
1141         fmt_state |= FMT_STATE_OPEN_COPY;
1142       }
1143       pFormat++;
1144     }
1145   }
1146
1147   *pOut++ = FMT_GEN_END;
1148
1149   header->size = pOut - rgbTok;
1150   if (pcbActual)
1151     *pcbActual = header->size;
1152
1153   return S_OK;
1154 }
1155
1156 /* Number formatting state flags */
1157 #define NUM_WROTE_DEC  0x01 /* Written the decimal separator */
1158
1159 /* Format a variant using a number format */
1160 static HRESULT VARIANT_FormatNumber(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1161                                     LPBYTE rgbTok, ULONG dwFlags,
1162                                     BSTR *pbstrOut, LCID lcid)
1163 {
1164   BYTE rgbDig[256];
1165   NUMPARSE np;
1166   int wholeNumberDigits, fractionalDigits, divisor10 = 0, multiplier10 = 0;
1167   WCHAR buff[256], *pBuff = buff;
1168   VARIANT vString, vBool;
1169   DWORD dwState = 0;
1170   FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1171   FMT_NUMBER_HEADER *numHeader;
1172   const BYTE* pToken = NULL;
1173   HRESULT hRes = S_OK;
1174
1175   TRACE("(%p->(%s%s),%s,%p,0x%08lx,%p,0x%08lx)\n", pVarIn, debugstr_VT(pVarIn),
1176         debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
1177         lcid);
1178
1179   V_VT(&vString) = VT_EMPTY;
1180   V_VT(&vBool) = VT_BOOL;
1181
1182   if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1183   {
1184     wholeNumberDigits = fractionalDigits = 0;
1185     numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNull(header));
1186     V_BOOL(&vBool) = VARIANT_FALSE;
1187   }
1188   else
1189   {
1190     /* Get a number string from pVarIn, and parse it */
1191     hRes = VariantChangeTypeEx(&vString, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1192     if (FAILED(hRes))
1193       return hRes;
1194
1195     np.cDig = sizeof(rgbDig);
1196     np.dwInFlags = NUMPRS_STD;
1197     hRes = VarParseNumFromStr(V_BSTR(&vString), LCID_US, 0, &np, rgbDig);
1198     if (FAILED(hRes))
1199       return hRes;
1200
1201     if (np.nPwr10 < 0)
1202     {
1203       if (-np.nPwr10 >= np.cDig)
1204       {
1205         /* A real number < +/- 1.0 e.g. 0.1024 or 0.01024 */
1206         wholeNumberDigits = 0;
1207         fractionalDigits = np.cDig;
1208         divisor10 = -np.nPwr10;
1209       }
1210       else
1211       {
1212         /* An exactly represented real number e.g. 1.024 */
1213         wholeNumberDigits = np.cDig + np.nPwr10;
1214         fractionalDigits = np.cDig - wholeNumberDigits;
1215         divisor10 = np.cDig - wholeNumberDigits;
1216       }
1217     }
1218     else if (np.nPwr10 == 0)
1219     {
1220       /* An exactly represented whole number e.g. 1024 */
1221       wholeNumberDigits = np.cDig;
1222       fractionalDigits = 0;
1223     }
1224     else /* np.nPwr10 > 0 */
1225     {
1226       /* A whole number followed by nPwr10 0's e.g. 102400 */
1227       wholeNumberDigits = np.cDig;
1228       fractionalDigits = 0;
1229       multiplier10 = np.nPwr10;
1230     }
1231
1232     /* Figure out which format to use */
1233     if (np.dwOutFlags & NUMPRS_NEG)
1234     {
1235       numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNegative(header));
1236       V_BOOL(&vBool) = VARIANT_TRUE;
1237     }
1238     else if (wholeNumberDigits == 1 && !fractionalDigits && !multiplier10 &&
1239               !divisor10 && rgbDig[0] == 0)
1240     {
1241       numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetZero(header));
1242       V_BOOL(&vBool) = VARIANT_FALSE;
1243     }
1244     else
1245     {
1246       numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetPositive(header));
1247       V_BOOL(&vBool) = VARIANT_TRUE;
1248     }
1249
1250     TRACE("num header: flags = 0x%x, mult=%d, div=%d, whole=%d, fract=%d\n",
1251           numHeader->flags, numHeader->multiplier, numHeader->divisor,
1252           numHeader->whole, numHeader->fractional);
1253
1254     if (numHeader->flags & FMT_FLAG_PERCENT &&
1255         !(wholeNumberDigits == 1 && !fractionalDigits && !multiplier10 &&
1256         !divisor10 && rgbDig[0] == 0))
1257     {
1258        /* *100 for %'s. Try to 'steal' fractional digits if we can */
1259       TRACE("Fraction - multiply by 100\n");
1260       if (!fractionalDigits)
1261          multiplier10 += 2;
1262       else
1263       {
1264         fractionalDigits--;
1265         wholeNumberDigits++;
1266         if (!fractionalDigits)
1267           multiplier10++;
1268         else
1269         {
1270           fractionalDigits--;
1271           wholeNumberDigits++;
1272         }
1273       }
1274     }
1275     TRACE("cDig %d; nPwr10 %d, whole %d, frac %d ", np.cDig,
1276           np.nPwr10, wholeNumberDigits, fractionalDigits);
1277     TRACE("mult %d; div %d\n", multiplier10, divisor10);
1278
1279   }
1280   pToken = (const BYTE*)numHeader + sizeof(FMT_NUMBER_HEADER);
1281
1282   while (SUCCEEDED(hRes) && *pToken != FMT_GEN_END)
1283   {
1284     WCHAR defaultChar = '?';
1285     DWORD boolFlag, localeValue = 0;
1286
1287     if (pToken - rgbTok > header->size)
1288     {
1289       ERR("Ran off the end of the format!\n");
1290       hRes = E_INVALIDARG;
1291       goto VARIANT_FormatNumber_Exit;
1292     }
1293
1294     switch (*pToken)
1295     {
1296     case FMT_GEN_COPY:
1297       TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1298       memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1299       pBuff += pToken[2];
1300       pToken += 2;
1301       break;
1302
1303     case FMT_GEN_INLINE:
1304       pToken += 2;
1305       TRACE("copy %s\n", debugstr_a(pToken));
1306       while (*pToken)
1307         *pBuff++ = *pToken++;
1308       break;
1309
1310     case FMT_NUM_YES_NO:
1311       boolFlag = VAR_BOOLYESNO;
1312       goto VARIANT_FormatNumber_Bool;
1313
1314     case FMT_NUM_ON_OFF:
1315       boolFlag = VAR_BOOLONOFF;
1316       goto VARIANT_FormatNumber_Bool;
1317
1318     case FMT_NUM_TRUE_FALSE:
1319       boolFlag = VAR_LOCALBOOL;
1320
1321 VARIANT_FormatNumber_Bool:
1322       {
1323         BSTR boolStr = NULL;
1324
1325         if (pToken[1] != FMT_GEN_END)
1326         {
1327           ERR("Boolean token not at end of format!\n");
1328           hRes = E_INVALIDARG;
1329           goto VARIANT_FormatNumber_Exit;
1330         }
1331         hRes = VarBstrFromBool(V_BOOL(&vBool), lcid, boolFlag, &boolStr);
1332         if (SUCCEEDED(hRes))
1333         {
1334           strcpyW(pBuff, boolStr);
1335           SysFreeString(boolStr);
1336           while (*pBuff)
1337             pBuff++;
1338         }
1339       }
1340       break;
1341
1342     case FMT_NUM_DECIMAL:
1343       TRACE("write decimal separator\n");
1344       localeValue = LOCALE_SDECIMAL;
1345       defaultChar = '.';
1346       dwState |= NUM_WROTE_DEC;
1347       break;
1348
1349     case FMT_NUM_CURRENCY:
1350       TRACE("write currency symbol\n");
1351       localeValue = LOCALE_SCURRENCY;
1352       defaultChar = '$';
1353       break;
1354
1355     case FMT_NUM_EXP_POS_U:
1356     case FMT_NUM_EXP_POS_L:
1357     case FMT_NUM_EXP_NEG_U:
1358     case FMT_NUM_EXP_NEG_L:
1359       if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_NEG_L)
1360         *pBuff++ = 'e';
1361       else
1362         *pBuff++ = 'E';
1363       if (divisor10)
1364       {
1365         *pBuff++ = '-';
1366         sprintfW(pBuff, szPercentZeroStar_d, pToken[1], divisor10);
1367       }
1368       else
1369       {
1370         if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_POS_U)
1371           *pBuff++ = '+';
1372         sprintfW(pBuff, szPercentZeroStar_d, pToken[1], multiplier10);
1373       }
1374       while (*pBuff)
1375         pBuff++;
1376       pToken++;
1377       break;
1378
1379     case FMT_NUM_COPY_SKIP:
1380       if (dwState & NUM_WROTE_DEC)
1381       {
1382         int count;
1383
1384         TRACE("write %d fractional digits or skip\n", pToken[1]);
1385
1386         for (count = 0; count < fractionalDigits; count++)
1387           pBuff[count] = '0' + rgbDig[wholeNumberDigits + count];
1388         pBuff += fractionalDigits;
1389       }
1390       else
1391       {
1392         int count;
1393
1394         TRACE("write %d digits or skip\n", pToken[1]);
1395
1396         if (wholeNumberDigits > 1 || rgbDig[0] > 0)
1397         {
1398           TRACE("write %d whole number digits\n", wholeNumberDigits);
1399           for (count = 0; count < wholeNumberDigits; count++)
1400             *pBuff++ = '0' + rgbDig[count];
1401           TRACE("write %d whole trailing 0's\n", multiplier10);
1402           for (count = 0; count < multiplier10; count++)
1403             *pBuff++ = '0'; /* Write trailing zeros for multiplied values */
1404         }
1405       }
1406       pToken++;
1407       break;
1408
1409     case FMT_NUM_COPY_ZERO:
1410       if (dwState & NUM_WROTE_DEC)
1411       {
1412         int count;
1413
1414         TRACE("write %d fractional digits or 0's\n", pToken[1]);
1415
1416         for (count = 0; count < fractionalDigits; count++)
1417           pBuff[count] = '0' + rgbDig[wholeNumberDigits + count];
1418         pBuff += fractionalDigits;
1419         if (pToken[1] > fractionalDigits)
1420         {
1421           count = pToken[1] - fractionalDigits;
1422           while (count--)
1423             *pBuff++ = '0'; /* Write trailing zeros for missing digits */
1424         }
1425       }
1426       else
1427       {
1428         int count;
1429
1430         TRACE("write %d digits or 0's\n", pToken[1]);
1431
1432         if (pToken[1] > (wholeNumberDigits + multiplier10))
1433         {
1434           count = pToken[1] - (wholeNumberDigits + multiplier10);
1435           TRACE("write %d leading zeros\n", count);
1436           while(count--)
1437             *pBuff++ = '0'; /* Write leading zeros for missing digits */
1438         }
1439         TRACE("write %d whole number digits\n", wholeNumberDigits);
1440         for (count = 0; count < wholeNumberDigits; count++)
1441           *pBuff++ = '0' + rgbDig[count];
1442         TRACE("write %d whole trailing 0's\n", multiplier10);
1443         for (count = 0; count < multiplier10; count++)
1444           *pBuff++ = '0'; /* Write trailing zeros for multiplied values */
1445       }
1446       pToken++;
1447       break;
1448
1449     default:
1450       ERR("Unknown token 0x%02x!\n", *pToken);
1451       hRes = E_INVALIDARG;
1452       goto VARIANT_FormatNumber_Exit;
1453     }
1454     if (localeValue)
1455     {
1456       if (GetLocaleInfoW(lcid, localeValue, pBuff, 
1457                          sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1458       {
1459         TRACE("added %s\n", debugstr_w(pBuff));
1460         while (*pBuff)
1461           pBuff++;
1462       }
1463       else
1464       {
1465         TRACE("added %d '%c'\n", defaultChar, defaultChar);
1466         *pBuff++ = defaultChar;
1467       }
1468     }
1469     pToken++;
1470   }
1471
1472 VARIANT_FormatNumber_Exit:
1473   VariantClear(&vString);
1474   *pBuff = '\0';
1475   TRACE("buff is %s\n", debugstr_w(buff));
1476   if (SUCCEEDED(hRes))
1477   {
1478     *pbstrOut = SysAllocString(buff);
1479     if (!*pbstrOut)
1480       hRes = E_OUTOFMEMORY;
1481   }
1482   return hRes;
1483 }
1484
1485 /* Format a variant using a date format */
1486 static HRESULT VARIANT_FormatDate(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1487                                   LPBYTE rgbTok, ULONG dwFlags,
1488                                   BSTR *pbstrOut, LCID lcid)
1489 {
1490   WCHAR buff[256], *pBuff = buff;
1491   VARIANT vDate;
1492   UDATE udate;
1493   FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1494   FMT_DATE_HEADER *dateHeader;
1495   const BYTE* pToken = NULL;
1496   HRESULT hRes;
1497
1498   TRACE("(%p->(%s%s),%s,%p,0x%08lx,%p,0x%08lx)\n", pVarIn, debugstr_VT(pVarIn),
1499         debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
1500         lcid);
1501
1502   V_VT(&vDate) = VT_EMPTY;
1503
1504   if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1505   {
1506     dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetNegative(header));
1507     V_DATE(&vDate) = 0;
1508   }
1509   else
1510   {
1511     USHORT usFlags = dwFlags & VARIANT_CALENDAR_HIJRI ? VAR_CALENDAR_HIJRI : 0;
1512
1513     hRes = VariantChangeTypeEx(&vDate, pVarIn, LCID_US, usFlags, VT_DATE);
1514     if (FAILED(hRes))
1515       return hRes;
1516     dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetPositive(header));
1517   }
1518
1519   hRes = VarUdateFromDate(V_DATE(&vDate), 0 /* FIXME: flags? */, &udate);
1520   if (FAILED(hRes))
1521     return hRes;
1522   pToken = (const BYTE*)dateHeader + sizeof(FMT_DATE_HEADER);
1523
1524   while (*pToken != FMT_GEN_END)
1525   {
1526     DWORD dwVal = 0, localeValue = 0, dwFmt = 0;
1527     LPCWSTR szPrintFmt = NULL;
1528     WCHAR defaultChar = '?';
1529
1530     if (pToken - rgbTok > header->size)
1531     {
1532       ERR("Ran off the end of the format!\n");
1533       hRes = E_INVALIDARG;
1534       goto VARIANT_FormatDate_Exit;
1535     }
1536
1537     switch (*pToken)
1538     {
1539     case FMT_GEN_COPY:
1540       TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1541       memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1542       pBuff += pToken[2];
1543       pToken += 2;
1544       break;
1545
1546     case FMT_DATE_TIME_SEP:
1547       TRACE("time separator\n");
1548       localeValue = LOCALE_STIME;
1549       defaultChar = ':';
1550       break;
1551
1552     case FMT_DATE_DATE_SEP:
1553       TRACE("date separator\n");
1554       localeValue = LOCALE_SDATE;
1555       defaultChar = '/';
1556       break;
1557
1558     case FMT_DATE_GENERAL:
1559       {
1560         BSTR date = NULL;
1561         WCHAR *pDate = date;
1562         hRes = VarBstrFromDate(V_DATE(&vDate), lcid, 0, pbstrOut);
1563         if (FAILED(hRes))
1564           goto VARIANT_FormatDate_Exit;
1565         while (*pDate)
1566           *pBuff++ = *pDate++;
1567         SysFreeString(date);
1568       }
1569       break;
1570
1571     case FMT_DATE_QUARTER:
1572       if (udate.st.wMonth <= 3)
1573         *pBuff++ = '1';
1574       else if (udate.st.wMonth <= 6)
1575         *pBuff++ = '2';
1576       else if (udate.st.wMonth <= 9)
1577         *pBuff++ = '3';
1578       else
1579         *pBuff++ = '4';
1580       break;
1581
1582     case FMT_DATE_TIME_SYS:
1583       {
1584         /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1585         BSTR date = NULL;
1586         WCHAR *pDate = date;
1587         hRes = VarBstrFromDate(V_DATE(&vDate), lcid, VAR_TIMEVALUEONLY, pbstrOut);
1588         if (FAILED(hRes))
1589           goto VARIANT_FormatDate_Exit;
1590         while (*pDate)
1591           *pBuff++ = *pDate++;
1592         SysFreeString(date);
1593       }
1594       break;
1595
1596     case FMT_DATE_DAY:
1597       szPrintFmt = szPercent_d;
1598       dwVal = udate.st.wDay;
1599       break;
1600
1601     case FMT_DATE_DAY_0:
1602       szPrintFmt = szPercentZeroTwo_d;
1603       dwVal = udate.st.wDay;
1604       break;
1605
1606     case FMT_DATE_DAY_SHORT:
1607       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1608       TRACE("short day\n");
1609       localeValue = LOCALE_SABBREVDAYNAME1 + udate.st.wMonth - 1;
1610       defaultChar = '?';
1611       break;
1612
1613     case FMT_DATE_DAY_LONG:
1614       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1615       TRACE("long day\n");
1616       localeValue = LOCALE_SDAYNAME1 + udate.st.wMonth - 1;
1617       defaultChar = '?';
1618       break;
1619
1620     case FMT_DATE_SHORT:
1621       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1622       dwFmt = LOCALE_SSHORTDATE;
1623       break;
1624
1625     case FMT_DATE_LONG:
1626       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1627       dwFmt = LOCALE_SLONGDATE;
1628       break;
1629
1630     case FMT_DATE_MEDIUM:
1631       FIXME("Medium date treated as long date\n");
1632       dwFmt = LOCALE_SLONGDATE;
1633       break;
1634
1635     case FMT_DATE_DAY_WEEK:
1636       szPrintFmt = szPercent_d;
1637       if (pToken[1])
1638         dwVal = udate.st.wDayOfWeek + 2 - pToken[1];
1639       else
1640       {
1641         GetLocaleInfoW(lcid,LOCALE_RETURN_NUMBER|LOCALE_IFIRSTDAYOFWEEK,
1642                        (LPWSTR)&dwVal, sizeof(dwVal)/sizeof(WCHAR));
1643         dwVal = udate.st.wDayOfWeek + 1 - dwVal;
1644       }
1645       pToken++;
1646       break;
1647
1648     case FMT_DATE_WEEK_YEAR:
1649       szPrintFmt = szPercent_d;
1650       dwVal = udate.wDayOfYear / 7 + 1;
1651       pToken += 2;
1652       FIXME("Ignoring nFirstDay of %d, nFirstWeek of %d\n", pToken[0], pToken[1]);
1653       break;
1654
1655     case FMT_DATE_MON:
1656       szPrintFmt = szPercent_d;
1657       dwVal = udate.st.wMonth;
1658       break;
1659
1660     case FMT_DATE_MON_0:
1661       szPrintFmt = szPercentZeroTwo_d;
1662       dwVal = udate.st.wMonth;
1663       break;
1664
1665     case FMT_DATE_MON_SHORT:
1666       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1667       TRACE("short month\n");
1668       localeValue = LOCALE_SABBREVMONTHNAME1 + udate.st.wMonth - 1;
1669       defaultChar = '?';
1670       break;
1671
1672     case FMT_DATE_MON_LONG:
1673       /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1674       TRACE("long month\n");
1675       localeValue = LOCALE_SMONTHNAME1 + udate.st.wMonth - 1;
1676       defaultChar = '?';
1677       break;
1678
1679     case FMT_DATE_YEAR_DOY:
1680       szPrintFmt = szPercent_d;
1681       dwVal = udate.wDayOfYear;
1682       break;
1683
1684     case FMT_DATE_YEAR_0:
1685       szPrintFmt = szPercentZeroTwo_d;
1686       dwVal = udate.st.wYear % 100;
1687       break;
1688
1689     case FMT_DATE_YEAR_LONG:
1690       szPrintFmt = szPercent_d;
1691       dwVal = udate.st.wYear;
1692       break;
1693
1694     case FMT_DATE_MIN:
1695       szPrintFmt = szPercent_d;
1696       dwVal = udate.st.wMinute;
1697       break;
1698
1699     case FMT_DATE_MIN_0:
1700       szPrintFmt = szPercentZeroTwo_d;
1701       dwVal = udate.st.wMinute;
1702       break;
1703
1704     case FMT_DATE_SEC:
1705       szPrintFmt = szPercent_d;
1706       dwVal = udate.st.wSecond;
1707       break;
1708
1709     case FMT_DATE_SEC_0:
1710       szPrintFmt = szPercentZeroTwo_d;
1711       dwVal = udate.st.wSecond;
1712       break;
1713
1714     case FMT_DATE_HOUR:
1715       szPrintFmt = szPercent_d;
1716       dwVal = udate.st.wHour;
1717       break;
1718
1719     case FMT_DATE_HOUR_0:
1720       szPrintFmt = szPercentZeroTwo_d;
1721       dwVal = udate.st.wHour;
1722       break;
1723
1724     case FMT_DATE_HOUR_12:
1725       szPrintFmt = szPercent_d;
1726       dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
1727       break;
1728
1729     case FMT_DATE_HOUR_12_0:
1730       szPrintFmt = szPercentZeroTwo_d;
1731       dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
1732       break;
1733
1734     case FMT_DATE_AMPM_SYS1:
1735     case FMT_DATE_AMPM_SYS2:
1736       localeValue = udate.st.wHour < 12 ? LOCALE_S1159 : LOCALE_S2359;
1737       defaultChar = '?';
1738       break;
1739
1740     case FMT_DATE_AMPM_UPPER:
1741       *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1742       *pBuff++ = 'M';
1743       break;
1744
1745     case FMT_DATE_A_UPPER:
1746       *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1747       break;
1748
1749     case FMT_DATE_AMPM_LOWER:
1750       *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1751       *pBuff++ = 'm';
1752       break;
1753
1754     case FMT_DATE_A_LOWER:
1755       *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1756       break;
1757
1758     default:
1759       ERR("Unknown token 0x%02x!\n", *pToken);
1760       hRes = E_INVALIDARG;
1761       goto VARIANT_FormatDate_Exit;
1762     }
1763     if (localeValue)
1764     {
1765       *pBuff = '\0';
1766       if (GetLocaleInfoW(lcid, localeValue, pBuff,
1767           sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1768       {
1769         TRACE("added %s\n", debugstr_w(pBuff));
1770         while (*pBuff)
1771           pBuff++;
1772       }
1773       else
1774       {
1775         TRACE("added %d %c\n", defaultChar, defaultChar);
1776         *pBuff++ = defaultChar;
1777       }
1778     }
1779     else if (dwFmt)
1780     {
1781       WCHAR fmt_buff[80];
1782
1783       if (!GetLocaleInfoW(lcid, dwFmt, fmt_buff, sizeof(fmt_buff)/sizeof(WCHAR)) ||
1784           !GetDateFormatW(lcid, 0, &udate.st, fmt_buff, pBuff,
1785                           sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1786       {
1787         hRes = E_INVALIDARG;
1788         goto VARIANT_FormatDate_Exit;
1789       }
1790       while (*pBuff)
1791         pBuff++;
1792     }
1793     else if (szPrintFmt)
1794     {
1795       sprintfW(pBuff, szPrintFmt, dwVal);
1796       while (*pBuff)
1797         pBuff++;
1798     }
1799     pToken++;
1800   }
1801
1802 VARIANT_FormatDate_Exit:
1803   *pBuff = '\0';
1804   TRACE("buff is %s\n", debugstr_w(buff));
1805   if (SUCCEEDED(hRes))
1806   {
1807     *pbstrOut = SysAllocString(buff);
1808     if (!*pbstrOut)
1809       hRes = E_OUTOFMEMORY;
1810   }
1811   return hRes;
1812 }
1813
1814 /* Format a variant using a string format */
1815 static HRESULT VARIANT_FormatString(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1816                                     LPBYTE rgbTok, ULONG dwFlags,
1817                                     BSTR *pbstrOut, LCID lcid)
1818 {
1819   static const WCHAR szEmpty[] = { '\0' };
1820   WCHAR buff[256], *pBuff = buff;
1821   WCHAR *pSrc;
1822   FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1823   FMT_STRING_HEADER *strHeader;
1824   const BYTE* pToken = NULL;
1825   VARIANT vStr;
1826   int blanks_first;
1827   BOOL bUpper = FALSE;
1828   HRESULT hRes = S_OK;
1829
1830   TRACE("(%p->(%s%s),%s,%p,0x%08lx,%p,0x%08lx)\n", pVarIn, debugstr_VT(pVarIn),
1831         debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
1832         lcid);
1833
1834   V_VT(&vStr) = VT_EMPTY;
1835
1836   if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1837   {
1838     strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1839     V_BSTR(&vStr) = (WCHAR*)szEmpty;
1840   }
1841   else
1842   {
1843     hRes = VariantChangeTypeEx(&vStr, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1844     if (FAILED(hRes))
1845       return hRes;
1846
1847     if (V_BSTR(pVarIn)[0] == '\0')
1848       strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1849     else
1850       strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetPositive(header));
1851   }
1852   pSrc = V_BSTR(&vStr);
1853   if ((strHeader->flags & (FMT_FLAG_LT|FMT_FLAG_GT)) == FMT_FLAG_GT)
1854     bUpper = TRUE;
1855   blanks_first = strHeader->copy_chars - strlenW(pSrc);
1856   pToken = (const BYTE*)strHeader + sizeof(FMT_DATE_HEADER);
1857
1858   while (*pToken != FMT_GEN_END)
1859   {
1860     int dwCount = 0;
1861
1862     if (pToken - rgbTok > header->size)
1863     {
1864       ERR("Ran off the end of the format!\n");
1865       hRes = E_INVALIDARG;
1866       goto VARIANT_FormatString_Exit;
1867     }
1868
1869     switch (*pToken)
1870     {
1871     case FMT_GEN_COPY:
1872       TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1873       memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1874       pBuff += pToken[2];
1875       pToken += 2;
1876       break;
1877
1878     case FMT_STR_COPY_SPACE:
1879     case FMT_STR_COPY_SKIP:
1880       dwCount = pToken[1];
1881       if (*pToken == FMT_STR_COPY_SPACE && blanks_first > 0)
1882       {
1883         TRACE("insert %d initial spaces\n", blanks_first);
1884         while (dwCount > 0 && blanks_first > 0)
1885         {
1886           *pBuff++ = ' ';
1887           dwCount--;
1888           blanks_first--;
1889         }
1890       }
1891       TRACE("copy %d chars%s\n", dwCount,
1892             *pToken == FMT_STR_COPY_SPACE ? " with space" :"");
1893       while (dwCount > 0 && *pSrc)
1894       {
1895         if (bUpper)
1896           *pBuff++ = toupperW(*pSrc);
1897         else
1898           *pBuff++ = tolowerW(*pSrc);
1899         dwCount--;
1900         pSrc++;
1901       }
1902       if (*pToken == FMT_STR_COPY_SPACE && dwCount > 0)
1903       {
1904         TRACE("insert %d spaces\n", dwCount);
1905         while (dwCount-- > 0)
1906           *pBuff++ = ' ';
1907       }
1908       pToken++;
1909       break;
1910
1911     default:
1912       ERR("Unknown token 0x%02x!\n", *pToken);
1913       hRes = E_INVALIDARG;
1914       goto VARIANT_FormatString_Exit;
1915     }
1916     pToken++;
1917   }
1918
1919 VARIANT_FormatString_Exit:
1920   /* Copy out any remaining chars */
1921   while (*pSrc)
1922   {
1923     if (bUpper)
1924       *pBuff++ = toupperW(*pSrc);
1925     else
1926       *pBuff++ = tolowerW(*pSrc);
1927     pSrc++;
1928   }
1929   VariantClear(&vStr);
1930   *pBuff = '\0';
1931   TRACE("buff is %s\n", debugstr_w(buff));
1932   if (SUCCEEDED(hRes))
1933   {
1934     *pbstrOut = SysAllocString(buff);
1935     if (!*pbstrOut)
1936       hRes = E_OUTOFMEMORY;
1937   }
1938   return hRes;
1939 }
1940
1941 #define NUMBER_VTBITS (VTBIT_I1|VTBIT_UI1|VTBIT_I2|VTBIT_UI2| \
1942                        VTBIT_I4|VTBIT_UI4|VTBIT_I8|VTBIT_UI8| \
1943                        VTBIT_R4|VTBIT_R8|VTBIT_CY|VTBIT_DECIMAL| \
1944                        (1<<VT_BOOL)|(1<<VT_INT)|(1<<VT_UINT))
1945
1946 /**********************************************************************
1947  *              VarFormatFromTokens [OLEAUT32.139]
1948  */
1949 HRESULT WINAPI VarFormatFromTokens(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1950                                    LPBYTE rgbTok, ULONG dwFlags,
1951                                    BSTR *pbstrOut, LCID lcid)
1952 {
1953   FMT_SHORT_HEADER *header = (FMT_SHORT_HEADER *)rgbTok;
1954   VARIANT vTmp;
1955   HRESULT hres;
1956
1957   TRACE("(%p,%s,%p,%lx,%p,0x%08lx)\n", pVarIn, debugstr_w(lpszFormat),
1958           rgbTok, dwFlags, pbstrOut, lcid);
1959
1960   if (!pbstrOut)
1961     return E_INVALIDARG;
1962
1963   *pbstrOut = NULL;
1964
1965   if (!pVarIn || !rgbTok)
1966     return E_INVALIDARG;
1967
1968   if (*rgbTok == FMT_TO_STRING || header->type == FMT_TYPE_GENERAL)
1969   {
1970     /* According to MSDN, general format acts somewhat like the 'Str'
1971      * function in Visual Basic.
1972      */
1973 VarFormatFromTokens_AsStr:
1974     V_VT(&vTmp) = VT_EMPTY;
1975     hres = VariantChangeTypeEx(&vTmp, pVarIn, lcid, dwFlags, VT_BSTR);
1976     *pbstrOut = V_BSTR(&vTmp);
1977   }
1978   else
1979   {
1980     if (header->type == FMT_TYPE_NUMBER ||
1981         (header->type == FMT_TYPE_UNKNOWN && ((1 << V_TYPE(pVarIn)) & NUMBER_VTBITS)))
1982     {
1983       hres = VARIANT_FormatNumber(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
1984     }
1985     else if (header->type == FMT_TYPE_DATE ||
1986              (header->type == FMT_TYPE_UNKNOWN && V_TYPE(pVarIn) == VT_DATE))
1987     {
1988       hres = VARIANT_FormatDate(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
1989     }
1990     else if (header->type == FMT_TYPE_STRING || V_TYPE(pVarIn) == VT_BSTR)
1991     {
1992       hres = VARIANT_FormatString(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
1993     }
1994     else
1995     {
1996       ERR("unrecognised format type 0x%02x\n", header->type);
1997       return E_INVALIDARG;
1998     }
1999     /* If the coercion failed, still try to create output, unless the
2000      * VAR_FORMAT_NOSUBSTITUTE flag is set.
2001      */
2002     if ((hres == DISP_E_OVERFLOW || hres == DISP_E_TYPEMISMATCH) &&
2003         !(dwFlags & VAR_FORMAT_NOSUBSTITUTE))
2004       goto VarFormatFromTokens_AsStr;
2005   }
2006
2007   return hres;
2008 }
2009
2010 /**********************************************************************
2011  *              VarFormat [OLEAUT32.87]
2012  *
2013  * Format a variant from a format string.
2014  *
2015  * PARAMS
2016  *  pVarIn     [I] Variant to format
2017  *  lpszFormat [I] Format string (see notes)
2018  *  nFirstDay  [I] First day of the week, (See VarTokenizeFormatString() for details)
2019  *  nFirstWeek [I] First week of the year (See VarTokenizeFormatString() for details)
2020  *  dwFlags    [I] Flags for the format (VAR_ flags from "oleauto.h")
2021  *  pbstrOut   [O] Destination for formatted string.
2022  *
2023  * RETURNS
2024  *  Success: S_OK. pbstrOut contains the formatted value.
2025  *  Failure: E_INVALIDARG, if any parameter is invalid.
2026  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2027  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2028  *
2029  * NOTES
2030  *  - See Variant-Formats for details concerning creating format strings.
2031  *  - This function uses LOCALE_USER_DEFAULT when calling VarTokenizeFormatString()
2032  *    and VarFormatFromTokens().
2033  */
2034 HRESULT WINAPI VarFormat(LPVARIANT pVarIn, LPOLESTR lpszFormat,
2035                          int nFirstDay, int nFirstWeek, ULONG dwFlags,
2036                          BSTR *pbstrOut)
2037 {
2038   BYTE buff[256];
2039   HRESULT hres;
2040
2041   TRACE("(%p->(%s%s),%s,%d,%d,0x%08lx,%p)\n", pVarIn, debugstr_VT(pVarIn),
2042         debugstr_VF(pVarIn), debugstr_w(lpszFormat), nFirstDay, nFirstWeek,
2043         dwFlags, pbstrOut);
2044
2045   if (!pbstrOut)
2046     return E_INVALIDARG;
2047   *pbstrOut = NULL;
2048
2049   hres = VarTokenizeFormatString(lpszFormat, buff, sizeof(buff), nFirstDay,
2050                                  nFirstWeek, LOCALE_USER_DEFAULT, NULL);
2051   if (SUCCEEDED(hres))
2052     hres = VarFormatFromTokens(pVarIn, lpszFormat, buff, dwFlags,
2053                                pbstrOut, LOCALE_USER_DEFAULT);
2054   TRACE("returning 0x%08lx, %s\n", hres, debugstr_w(*pbstrOut));
2055   return hres;
2056 }
2057
2058 /**********************************************************************
2059  *              VarFormatDateTime [OLEAUT32.97]
2060  *
2061  * Format a variant value as a date and/or time.
2062  *
2063  * PARAMS
2064  *  pVarIn    [I] Variant to format
2065  *  nFormat   [I] Format type (see notes)
2066  *  dwFlags   [I] Flags for the format (VAR_ flags from "oleauto.h")
2067  *  pbstrOut  [O] Destination for formatted string.
2068  *
2069  * RETURNS
2070  *  Success: S_OK. pbstrOut contains the formatted value.
2071  *  Failure: E_INVALIDARG, if any parameter is invalid.
2072  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2073  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2074  *
2075  * NOTES
2076  *  This function uses LOCALE_USER_DEFAULT when determining the date format
2077  *  characters to use.
2078  *  Possible values for the nFormat parameter are:
2079  *| Value  Meaning
2080  *| -----  -------
2081  *|   0    General date format
2082  *|   1    Long date format
2083  *|   2    Short date format
2084  *|   3    Long time format
2085  *|   4    Short time format
2086  */
2087 HRESULT WINAPI VarFormatDateTime(LPVARIANT pVarIn, INT nFormat, ULONG dwFlags, BSTR *pbstrOut)
2088 {
2089   static const WCHAR szEmpty[] = { '\0' };
2090   const BYTE* lpFmt = NULL;
2091
2092   TRACE("(%p->(%s%s),%d,0x%08lx,%p)\n", pVarIn, debugstr_VT(pVarIn),
2093         debugstr_VF(pVarIn), nFormat, dwFlags, pbstrOut);
2094
2095   if (!pVarIn || !pbstrOut || nFormat < 0 || nFormat > 4)
2096     return E_INVALIDARG;
2097
2098   switch (nFormat)
2099   {
2100   case 0: lpFmt = fmtGeneralDate; break;
2101   case 1: lpFmt = fmtLongDate; break;
2102   case 2: lpFmt = fmtShortDate; break;
2103   case 3: lpFmt = fmtLongTime; break;
2104   case 4: lpFmt = fmtShortTime; break;
2105   }
2106   return VarFormatFromTokens(pVarIn, (LPWSTR)szEmpty, (BYTE*)lpFmt, dwFlags,
2107                               pbstrOut, LOCALE_USER_DEFAULT);
2108 }
2109
2110 #define GETLOCALENUMBER(type,field) GetLocaleInfoW(LOCALE_USER_DEFAULT, \
2111                                                    type|LOCALE_RETURN_NUMBER, \
2112                                                    (LPWSTR)&numfmt.field, \
2113                                                    sizeof(numfmt.field)/sizeof(WCHAR))
2114
2115 /**********************************************************************
2116  *              VarFormatNumber [OLEAUT32.107]
2117  *
2118  * Format a variant value as a number.
2119  *
2120  * PARAMS
2121  *  pVarIn    [I] Variant to format
2122  *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
2123  *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2124  *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2125  *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2126  *  dwFlags   [I] Currently unused, set to zero
2127  *  pbstrOut  [O] Destination for formatted string.
2128  *
2129  * RETURNS
2130  *  Success: S_OK. pbstrOut contains the formatted value.
2131  *  Failure: E_INVALIDARG, if any parameter is invalid.
2132  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2133  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2134  *
2135  * NOTES
2136  *  This function uses LOCALE_USER_DEFAULT when determining the number format
2137  *  characters to use.
2138  */
2139 HRESULT WINAPI VarFormatNumber(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2140                                INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2141 {
2142   HRESULT hRet;
2143   VARIANT vStr;
2144
2145   TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08lx,%p)\n", pVarIn, debugstr_VT(pVarIn),
2146         debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping, dwFlags, pbstrOut);
2147
2148   if (!pVarIn || !pbstrOut || nDigits > 9)
2149     return E_INVALIDARG;
2150
2151   *pbstrOut = NULL;
2152
2153   V_VT(&vStr) = VT_EMPTY;
2154   hRet = VariantCopyInd(&vStr, pVarIn);
2155
2156   if (SUCCEEDED(hRet))
2157     hRet = VariantChangeTypeEx(&vStr, &vStr, LOCALE_USER_DEFAULT, 0, VT_BSTR);
2158
2159   if (SUCCEEDED(hRet))
2160   {
2161     WCHAR buff[256], decimal[8], thousands[8];
2162     NUMBERFMTW numfmt;
2163
2164     /* Although MSDN makes it clear that the native versions of these functions
2165      * are implemented using VarTokenizeFormatString()/VarFormatFromTokens(),
2166      * using NLS gives us the same result.
2167      */
2168     if (nDigits < 0)
2169       GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2170     else
2171       numfmt.NumDigits = nDigits;
2172
2173     if (nLeading == -2)
2174       GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2175     else if (nLeading == -1)
2176       numfmt.LeadingZero = 1;
2177     else
2178       numfmt.LeadingZero = 0;
2179
2180     if (nGrouping == -2)
2181     {
2182       WCHAR grouping[16];
2183       grouping[2] = '\0';
2184       GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, grouping,
2185                      sizeof(grouping)/sizeof(WCHAR));
2186       numfmt.Grouping = grouping[2] == '2' ? 32 : grouping[0] - '0';
2187     }
2188     else if (nGrouping == -1)
2189       numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2190     else
2191       numfmt.Grouping = 0; /* 0 = No grouping */
2192
2193     if (nParens == -2)
2194       GETLOCALENUMBER(LOCALE_INEGNUMBER, NegativeOrder);
2195     else if (nParens == -1)
2196       numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2197     else
2198       numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2199
2200     numfmt.lpDecimalSep = decimal;
2201     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal,
2202                    sizeof(decimal)/sizeof(WCHAR));
2203     numfmt.lpThousandSep = thousands;
2204     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, thousands,
2205                    sizeof(thousands)/sizeof(WCHAR));
2206
2207     if (GetNumberFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
2208                          buff, sizeof(buff)/sizeof(WCHAR)))
2209     {
2210       *pbstrOut = SysAllocString(buff);
2211       if (!*pbstrOut)
2212         hRet = E_OUTOFMEMORY;
2213     }
2214     else
2215       hRet = DISP_E_TYPEMISMATCH;
2216
2217     SysFreeString(V_BSTR(&vStr));
2218   }
2219   return hRet;
2220 }
2221
2222 /**********************************************************************
2223  *              VarFormatPercent [OLEAUT32.117]
2224  *
2225  * Format a variant value as a percentage.
2226  *
2227  * PARAMS
2228  *  pVarIn    [I] Variant to format
2229  *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
2230  *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2231  *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2232  *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2233  *  dwFlags   [I] Currently unused, set to zero
2234  *  pbstrOut  [O] Destination for formatted string.
2235  *
2236  * RETURNS
2237  *  Success: S_OK. pbstrOut contains the formatted value.
2238  *  Failure: E_INVALIDARG, if any parameter is invalid.
2239  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2240  *           DISP_E_OVERFLOW, if overflow occurs during the conversion.
2241  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2242  *
2243  * NOTES
2244  *  This function uses LOCALE_USER_DEFAULT when determining the number format
2245  *  characters to use.
2246  */
2247 HRESULT WINAPI VarFormatPercent(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2248                                 INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2249 {
2250   static const WCHAR szPercent[] = { '%','\0' };
2251   static const WCHAR szPercentBracket[] = { '%',')','\0' };
2252   WCHAR buff[256];
2253   HRESULT hRet;
2254   VARIANT vDbl;
2255
2256   TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08lx,%p)\n", pVarIn, debugstr_VT(pVarIn),
2257         debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping,
2258         dwFlags, pbstrOut);
2259
2260   if (!pVarIn || !pbstrOut || nDigits > 9)
2261     return E_INVALIDARG;
2262
2263   *pbstrOut = NULL;
2264
2265   V_VT(&vDbl) = VT_EMPTY;
2266   hRet = VariantCopyInd(&vDbl, pVarIn);
2267
2268   if (SUCCEEDED(hRet))
2269   {
2270     hRet = VariantChangeTypeEx(&vDbl, &vDbl, LOCALE_USER_DEFAULT, 0, VT_R8);
2271
2272     if (SUCCEEDED(hRet))
2273     {
2274       if (V_R8(&vDbl) > (R8_MAX / 100.0))
2275         return DISP_E_OVERFLOW;
2276
2277       V_R8(&vDbl) *= 100.0;
2278       hRet = VarFormatNumber(&vDbl, nDigits, nLeading, nParens,
2279                              nGrouping, dwFlags, pbstrOut);
2280
2281       if (SUCCEEDED(hRet))
2282       {
2283         DWORD dwLen = strlenW(*pbstrOut);
2284         BOOL bBracket = (*pbstrOut)[dwLen] == ')' ? TRUE : FALSE;
2285
2286         dwLen -= bBracket;
2287         memcpy(buff, *pbstrOut, dwLen * sizeof(WCHAR));
2288         strcpyW(buff + dwLen, bBracket ? szPercentBracket : szPercent);
2289         SysFreeString(*pbstrOut);
2290         *pbstrOut = SysAllocString(buff);
2291         if (!*pbstrOut)
2292           hRet = E_OUTOFMEMORY;
2293       }
2294     }
2295   }
2296   return hRet;
2297 }
2298
2299 /**********************************************************************
2300  *              VarFormatCurrency [OLEAUT32.127]
2301  *
2302  * Format a variant value as a currency.
2303  *
2304  * PARAMS
2305  *  pVarIn    [I] Variant to format
2306  *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
2307  *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2308  *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2309  *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2310  *  dwFlags   [I] Currently unused, set to zero
2311  *  pbstrOut  [O] Destination for formatted string.
2312  *
2313  * RETURNS
2314  *  Success: S_OK. pbstrOut contains the formatted value.
2315  *  Failure: E_INVALIDARG, if any parameter is invalid.
2316  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2317  *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2318  *
2319  * NOTES
2320  *  This function uses LOCALE_USER_DEFAULT when determining the currency format
2321  *  characters to use.
2322  */
2323 HRESULT WINAPI VarFormatCurrency(LPVARIANT pVarIn, INT nDigits, INT nLeading,
2324                                  INT nParens, INT nGrouping, ULONG dwFlags,
2325                                  BSTR *pbstrOut)
2326 {
2327   HRESULT hRet;
2328   VARIANT vStr;
2329
2330   TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08lx,%p)\n", pVarIn, debugstr_VT(pVarIn),
2331         debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping, dwFlags, pbstrOut);
2332
2333   if (!pVarIn || !pbstrOut || nDigits > 9)
2334     return E_INVALIDARG;
2335
2336   *pbstrOut = NULL;
2337
2338   V_VT(&vStr) = VT_EMPTY;
2339   hRet = VariantCopyInd(&vStr, pVarIn);
2340
2341   if (SUCCEEDED(hRet))
2342     hRet = VariantChangeTypeEx(&vStr, &vStr, LOCALE_USER_DEFAULT, 0, VT_BSTR);
2343
2344   if (SUCCEEDED(hRet))
2345   {
2346     WCHAR buff[256], decimal[8], thousands[8], currency[8];
2347     CURRENCYFMTW numfmt;
2348
2349     if (nDigits < 0)
2350       GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2351     else
2352       numfmt.NumDigits = nDigits;
2353
2354     if (nLeading == -2)
2355       GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2356     else if (nLeading == -1)
2357       numfmt.LeadingZero = 1;
2358     else
2359       numfmt.LeadingZero = 0;
2360
2361     if (nGrouping == -2)
2362     {
2363       WCHAR nGrouping[16];
2364       nGrouping[2] = '\0';
2365       GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, nGrouping,
2366                      sizeof(nGrouping)/sizeof(WCHAR));
2367       numfmt.Grouping = nGrouping[2] == '2' ? 32 : nGrouping[0] - '0';
2368     }
2369     else if (nGrouping == -1)
2370       numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2371     else
2372       numfmt.Grouping = 0; /* 0 = No grouping */
2373
2374     if (nParens == -2)
2375       GETLOCALENUMBER(LOCALE_INEGCURR, NegativeOrder);
2376     else if (nParens == -1)
2377       numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2378     else
2379       numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2380
2381     GETLOCALENUMBER(LOCALE_ICURRENCY, PositiveOrder);
2382
2383     numfmt.lpDecimalSep = decimal;
2384     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal,
2385                    sizeof(decimal)/sizeof(WCHAR));
2386     numfmt.lpThousandSep = thousands;
2387     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, thousands,
2388                    sizeof(thousands)/sizeof(WCHAR));
2389     numfmt.lpCurrencySymbol = currency;
2390     GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, currency,
2391                    sizeof(currency)/sizeof(WCHAR));
2392
2393     /* use NLS as per VarFormatNumber() */
2394     if (GetCurrencyFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
2395                            buff, sizeof(buff)/sizeof(WCHAR)))
2396     {
2397       *pbstrOut = SysAllocString(buff);
2398       if (!*pbstrOut)
2399         hRet = E_OUTOFMEMORY;
2400     }
2401     else
2402       hRet = DISP_E_TYPEMISMATCH;
2403
2404     SysFreeString(V_BSTR(&vStr));
2405   }
2406   return hRet;
2407 }
2408
2409 /**********************************************************************
2410  *              VarMonthName [OLEAUT32.129]
2411  *
2412  * Print the specified month as localized name.
2413  *
2414  * PARAMS
2415  *  iMonth    [I] month number 1..12
2416  *  fAbbrev   [I] 0 - full name, !0 - abbreviated name
2417  *  dwFlags   [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
2418  *  pbstrOut  [O] Destination for month name
2419  *
2420  * RETURNS
2421  *  Success: S_OK. pbstrOut contains the name.
2422  *  Failure: E_INVALIDARG, if any parameter is invalid.
2423  *           E_OUTOFMEMORY, if enough memory cannot be allocated.
2424  */
2425 HRESULT WINAPI VarMonthName(INT iMonth, INT fAbbrev, ULONG dwFlags, BSTR *pbstrOut)
2426 {
2427   DWORD localeValue;
2428   INT size;
2429   WCHAR *str;
2430
2431   if ((iMonth < 1)  || (iMonth > 12))
2432     return E_INVALIDARG;
2433
2434   if (dwFlags)
2435     FIXME("Does not support dwFlags 0x%lx, ignoring.\n", dwFlags);
2436
2437   if (fAbbrev)
2438         localeValue = LOCALE_SABBREVMONTHNAME1 + iMonth - 1;
2439   else
2440         localeValue = LOCALE_SMONTHNAME1 + iMonth - 1;
2441
2442   size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, NULL, 0);
2443   if (!size) {
2444     FIXME("GetLocaleInfo 0x%lx failed.\n", localeValue);
2445     return E_INVALIDARG;
2446   }
2447   str = HeapAlloc(GetProcessHeap(),0,sizeof(WCHAR)*size);
2448   if (!str)
2449     return E_OUTOFMEMORY;
2450   size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, str, size);
2451   if (!size) {
2452     FIXME("GetLocaleInfo of 0x%lx failed in 2nd stage?!\n", localeValue);
2453     HeapFree(GetProcessHeap(),0,str);
2454     return E_INVALIDARG;
2455   }
2456   *pbstrOut = SysAllocString(str);
2457   HeapFree(GetProcessHeap(),0,str);
2458   if (!*pbstrOut)
2459     return E_OUTOFMEMORY;
2460   return S_OK;
2461 }