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