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