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