ole32: Add more traces to the storage methods.
[wine/multimedia.git] / dlls / oleaut32 / varformat.c
blob5d220fa382d7735a2be6350b0547fde7a847ea50
1 /*
2 * Variant formatting functions
4 * Copyright 2008 Damjan Jovanovic
5 * Copyright 2003 Jon Griffiths
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 * NOTES
22 * Since the formatting functions aren't properly documented, I used the
23 * Visual Basic documentation as a guide to implementing these functions. This
24 * means that some named or user-defined formats may work slightly differently.
25 * Please submit a test case if you find a difference.
28 #include "config.h"
30 #include <string.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <stdio.h>
35 #include "windef.h"
36 #include "winbase.h"
37 #include "wine/unicode.h"
38 #include "winerror.h"
39 #include "variant.h"
40 #include "wine/debug.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(variant);
44 /* Make sure internal conversions to strings use the '.','+'/'-' and ','
45 * format chars from the US locale. This enables us to parse the created
46 * strings to determine the number of decimal places, exponent, etc.
48 #define LCID_US MAKELCID(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),SORT_DEFAULT)
50 static const WCHAR szPercent_d[] = { '%','d','\0' };
51 static const WCHAR szPercentZeroTwo_d[] = { '%','0','2','d','\0' };
52 static const WCHAR szPercentZeroStar_d[] = { '%','0','*','d','\0' };
54 #if 0
55 #define dump_tokens(rgb) do { \
56 int i_; TRACE("Tokens->{\n"); \
57 for (i_ = 0; i_ < rgb[0]; i_++) \
58 TRACE("%s0x%02x", i_?",":"",rgb[i_]); \
59 TRACE(" }\n"); \
60 } while(0)
61 #endif
63 /******************************************************************************
64 * Variant-Formats {OLEAUT32}
66 * NOTES
67 * When formatting a variant a variety of format strings may be used to generate
68 * different kinds of formatted output. A format string consists of either a named
69 * format, or a user-defined format.
71 * The following named formats are defined:
72 *| Name Description
73 *| ---- -----------
74 *| General Date Display Date, and time for non-integer values
75 *| Short Date Short date format as defined by locale settings
76 *| Medium Date Medium date format as defined by locale settings
77 *| Long Date Long date format as defined by locale settings
78 *| Short Time Short Time format as defined by locale settings
79 *| Medium Time Medium time format as defined by locale settings
80 *| Long Time Long time format as defined by locale settings
81 *| True/False Localised text of "True" or "False"
82 *| Yes/No Localised text of "Yes" or "No"
83 *| On/Off Localised text of "On" or "Off"
84 *| General Number No thousands separator. No decimal points for integers
85 *| Currency General currency format using localised characters
86 *| Fixed At least one whole and two fractional digits
87 *| Standard Same as 'Fixed', but including decimal separators
88 *| Percent Multiply by 100 and display a trailing '%' character
89 *| Scientific Display with exponent
91 * User-defined formats consist of a combination of tokens and literal
92 * characters. Literal characters are copied unmodified to the formatted
93 * output at the position they occupy in the format string. Any character
94 * that is not recognised as a token is treated as a literal. A literal can
95 * also be specified by preceding it with a backslash character
96 * (e.g. "\L\i\t\e\r\a\l") or enclosing it in double quotes.
98 * A user-defined format can have up to 4 sections, depending on the type of
99 * format. The following table lists sections and their meaning:
100 *| Format Type Sections Meaning
101 *| ----------- -------- -------
102 *| Number 1 Use the same format for all numbers
103 *| Number 2 Use format 1 for positive and 2 for negative numbers
104 *| Number 3 Use format 1 for positive, 2 for zero, and 3
105 *| for negative numbers.
106 *| Number 4 Use format 1 for positive, 2 for zero, 3 for
107 *| negative, and 4 for null numbers.
108 *| String 1 Use the same format for all strings
109 *| String 2 Use format 2 for null and empty strings, otherwise
110 *| use format 1.
111 *| Date 1 Use the same format for all dates
113 * The formatting tokens fall into several categories depending on the type
114 * of formatted output. For more information on each type, see
115 * VarFormat-Dates(), VarFormat-Strings() and VarFormat-Numbers().
117 * SEE ALSO
118 * VarTokenizeFormatString(), VarFormatFromTokens(), VarFormat(),
119 * VarFormatDateTime(), VarFormatNumber(), VarFormatCurrency().
122 /******************************************************************************
123 * VarFormat-Strings {OLEAUT32}
125 * NOTES
126 * When formatting a variant as a string, it is first converted to a VT_BSTR.
127 * The user-format string defines which characters are copied into which
128 * positions in the output string. Literals may be inserted in the format
129 * string. When creating the formatted string, excess characters in the string
130 * (those not consumed by a token) are appended to the end of the output. If
131 * there are more tokens than characters in the string to format, spaces will
132 * be inserted at the start of the string if the '@' token was used.
134 * By default strings are converted to lowercase, or uppercase if the '>' token
135 * is encountered. This applies to the whole string: it is not possible to
136 * generate a mixed-case output string.
138 * In user-defined string formats, the following tokens are recognised:
139 *| Token Description
140 *| ----- -----------
141 *| '@' Copy a char from the source, or a space if no chars are left.
142 *| '&' Copy a char from the source, or write nothing if no chars are left.
143 *| '<' Output the whole string as lower-case (the default).
144 *| '>' Output the whole string as upper-case.
145 *| '!' MSDN indicates that this character should cause right-to-left
146 *| copying, however tests show that it is tokenised but not processed.
150 * Common format definitions
153 /* Format types */
154 #define FMT_TYPE_UNKNOWN 0x0
155 #define FMT_TYPE_GENERAL 0x1
156 #define FMT_TYPE_NUMBER 0x2
157 #define FMT_TYPE_DATE 0x3
158 #define FMT_TYPE_STRING 0x4
160 #define FMT_TO_STRING 0x0 /* If header->size == this, act like VB's Str() fn */
162 typedef struct tagFMT_SHORT_HEADER
164 BYTE size; /* Size of tokenised block (including header), or FMT_TO_STRING */
165 BYTE type; /* Allowable types (FMT_TYPE_*) */
166 BYTE offset[1]; /* Offset of the first (and only) format section */
167 } FMT_SHORT_HEADER;
169 typedef struct tagFMT_HEADER
171 BYTE size; /* Total size of the whole tokenised block (including header) */
172 BYTE type; /* Allowable types (FMT_TYPE_*) */
173 BYTE starts[4]; /* Offset of each of the 4 format sections, or 0 if none */
174 } FMT_HEADER;
176 #define FmtGetPositive(x) (x->starts[0])
177 #define FmtGetNegative(x) (x->starts[1] ? x->starts[1] : x->starts[0])
178 #define FmtGetZero(x) (x->starts[2] ? x->starts[2] : x->starts[0])
179 #define FmtGetNull(x) (x->starts[3] ? x->starts[3] : x->starts[0])
182 * String formats
185 #define FMT_FLAG_LT 0x1 /* Has '<' (lower case) */
186 #define FMT_FLAG_GT 0x2 /* Has '>' (upper case) */
187 #define FMT_FLAG_RTL 0x4 /* Has '!' (Copy right to left) */
189 typedef struct tagFMT_STRING_HEADER
191 BYTE flags; /* LT, GT, RTL */
192 BYTE unknown1;
193 BYTE unknown2;
194 BYTE copy_chars; /* Number of chars to be copied */
195 BYTE unknown3;
196 } FMT_STRING_HEADER;
199 * Number formats
202 #define FMT_FLAG_PERCENT 0x1 /* Has '%' (Percentage) */
203 #define FMT_FLAG_EXPONENT 0x2 /* Has 'e' (Exponent/Scientific notation) */
204 #define FMT_FLAG_THOUSANDS 0x4 /* Has ',' (Standard use of the thousands separator) */
205 #define FMT_FLAG_BOOL 0x20 /* Boolean format */
207 typedef struct tagFMT_NUMBER_HEADER
209 BYTE flags; /* PERCENT, EXPONENT, THOUSANDS, BOOL */
210 BYTE multiplier; /* Multiplier, 100 for percentages */
211 BYTE divisor; /* Divisor, 1000 if '%%' was used */
212 BYTE whole; /* Number of digits before the decimal point */
213 BYTE fractional; /* Number of digits after the decimal point */
214 } FMT_NUMBER_HEADER;
217 * Date Formats
219 typedef struct tagFMT_DATE_HEADER
221 BYTE flags;
222 BYTE unknown1;
223 BYTE unknown2;
224 BYTE unknown3;
225 BYTE unknown4;
226 } FMT_DATE_HEADER;
229 * Format token values
231 #define FMT_GEN_COPY 0x00 /* \n, "lit" => 0,pos,len: Copy len chars from input+pos */
232 #define FMT_GEN_INLINE 0x01 /* => 1,len,[chars]: Copy len chars from token stream */
233 #define FMT_GEN_END 0x02 /* \0,; => 2: End of the tokenised format */
234 #define FMT_DATE_TIME_SEP 0x03 /* Time separator char */
235 #define FMT_DATE_DATE_SEP 0x04 /* Date separator char */
236 #define FMT_DATE_GENERAL 0x05 /* General format date */
237 #define FMT_DATE_QUARTER 0x06 /* Quarter of the year from 1-4 */
238 #define FMT_DATE_TIME_SYS 0x07 /* System long time format */
239 #define FMT_DATE_DAY 0x08 /* Day with no leading 0 */
240 #define FMT_DATE_DAY_0 0x09 /* Day with leading 0 */
241 #define FMT_DATE_DAY_SHORT 0x0A /* Short day name */
242 #define FMT_DATE_DAY_LONG 0x0B /* Long day name */
243 #define FMT_DATE_SHORT 0x0C /* Short date format */
244 #define FMT_DATE_LONG 0x0D /* Long date format */
245 #define FMT_DATE_MEDIUM 0x0E /* Medium date format */
246 #define FMT_DATE_DAY_WEEK 0x0F /* First day of the week */
247 #define FMT_DATE_WEEK_YEAR 0x10 /* First week of the year */
248 #define FMT_DATE_MON 0x11 /* Month with no leading 0 */
249 #define FMT_DATE_MON_0 0x12 /* Month with leading 0 */
250 #define FMT_DATE_MON_SHORT 0x13 /* Short month name */
251 #define FMT_DATE_MON_LONG 0x14 /* Long month name */
252 #define FMT_DATE_YEAR_DOY 0x15 /* Day of the year with no leading 0 */
253 #define FMT_DATE_YEAR_0 0x16 /* 2 digit year with leading 0 */
254 /* NOTE: token 0x17 is not defined, 'yyy' is not valid */
255 #define FMT_DATE_YEAR_LONG 0x18 /* 4 digit year */
256 #define FMT_DATE_MIN 0x1A /* Minutes with no leading 0 */
257 #define FMT_DATE_MIN_0 0x1B /* Minutes with leading 0 */
258 #define FMT_DATE_SEC 0x1C /* Seconds with no leading 0 */
259 #define FMT_DATE_SEC_0 0x1D /* Seconds with leading 0 */
260 #define FMT_DATE_HOUR 0x1E /* Hours with no leading 0 */
261 #define FMT_DATE_HOUR_0 0x1F /* Hours with leading 0 */
262 #define FMT_DATE_HOUR_12 0x20 /* Hours with no leading 0, 12 hour clock */
263 #define FMT_DATE_HOUR_12_0 0x21 /* Hours with leading 0, 12 hour clock */
264 #define FMT_DATE_TIME_UNK2 0x23 /* same as FMT_DATE_HOUR_0, for "short time" format */
265 /* FIXME: probably missing some here */
266 #define FMT_DATE_AMPM_SYS1 0x2E /* AM/PM as defined by system settings */
267 #define FMT_DATE_AMPM_UPPER 0x2F /* Upper-case AM or PM */
268 #define FMT_DATE_A_UPPER 0x30 /* Upper-case A or P */
269 #define FMT_DATE_AMPM_SYS2 0x31 /* AM/PM as defined by system settings */
270 #define FMT_DATE_AMPM_LOWER 0x32 /* Lower-case AM or PM */
271 #define FMT_DATE_A_LOWER 0x33 /* Lower-case A or P */
272 #define FMT_NUM_COPY_ZERO 0x34 /* Copy 1 digit or 0 if no digit */
273 #define FMT_NUM_COPY_SKIP 0x35 /* Copy 1 digit or skip if no digit */
274 #define FMT_NUM_DECIMAL 0x36 /* Decimal separator */
275 #define FMT_NUM_EXP_POS_U 0x37 /* Scientific notation, uppercase, + sign */
276 #define FMT_NUM_EXP_NEG_U 0x38 /* Scientific notation, uppercase, - sign */
277 #define FMT_NUM_EXP_POS_L 0x39 /* Scientific notation, lowercase, + sign */
278 #define FMT_NUM_EXP_NEG_L 0x3A /* Scientific notation, lowercase, - sign */
279 #define FMT_NUM_CURRENCY 0x3B /* Currency symbol */
280 #define FMT_NUM_TRUE_FALSE 0x3D /* Convert to "True" or "False" */
281 #define FMT_NUM_YES_NO 0x3E /* Convert to "Yes" or "No" */
282 #define FMT_NUM_ON_OFF 0x3F /* Convert to "On" or "Off" */
283 #define FMT_STR_COPY_SPACE 0x40 /* Copy len chars with space if no char */
284 #define FMT_STR_COPY_SKIP 0x41 /* Copy len chars or skip if no char */
286 /* Named Formats and their tokenised values */
287 static const WCHAR szGeneralDate[] = { 'G','e','n','e','r','a','l',' ','D','a','t','e','\0' };
288 static const BYTE fmtGeneralDate[0x0a] =
290 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
291 0x0,0x0,0x0,0x0,0x0,
292 FMT_DATE_GENERAL,FMT_GEN_END
295 static const WCHAR szShortDate[] = { 'S','h','o','r','t',' ','D','a','t','e','\0' };
296 static const BYTE fmtShortDate[0x0a] =
298 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
299 0x0,0x0,0x0,0x0,0x0,
300 FMT_DATE_SHORT,FMT_GEN_END
303 static const WCHAR szMediumDate[] = { 'M','e','d','i','u','m',' ','D','a','t','e','\0' };
304 static const BYTE fmtMediumDate[0x0a] =
306 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
307 0x0,0x0,0x0,0x0,0x0,
308 FMT_DATE_MEDIUM,FMT_GEN_END
311 static const WCHAR szLongDate[] = { 'L','o','n','g',' ','D','a','t','e','\0' };
312 static const BYTE fmtLongDate[0x0a] =
314 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
315 0x0,0x0,0x0,0x0,0x0,
316 FMT_DATE_LONG,FMT_GEN_END
319 static const WCHAR szShortTime[] = { 'S','h','o','r','t',' ','T','i','m','e','\0' };
320 static const BYTE fmtShortTime[0x0c] =
322 0x0c,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
323 0x0,0x0,0x0,0x0,0x0,
324 FMT_DATE_TIME_UNK2,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,FMT_GEN_END
327 static const WCHAR szMediumTime[] = { 'M','e','d','i','u','m',' ','T','i','m','e','\0' };
328 static const BYTE fmtMediumTime[0x11] =
330 0x11,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
331 0x0,0x0,0x0,0x0,0x0,
332 FMT_DATE_HOUR_12_0,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,
333 FMT_GEN_INLINE,0x01,' ','\0',FMT_DATE_AMPM_SYS1,FMT_GEN_END
336 static const WCHAR szLongTime[] = { 'L','o','n','g',' ','T','i','m','e','\0' };
337 static const BYTE fmtLongTime[0x0d] =
339 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
340 0x0,0x0,0x0,0x0,0x0,
341 FMT_DATE_TIME_SYS,FMT_GEN_END
344 static const WCHAR szTrueFalse[] = { 'T','r','u','e','/','F','a','l','s','e','\0' };
345 static const BYTE fmtTrueFalse[0x0d] =
347 0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
348 FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
349 FMT_NUM_TRUE_FALSE,FMT_GEN_END
352 static const WCHAR szYesNo[] = { 'Y','e','s','/','N','o','\0' };
353 static const BYTE fmtYesNo[0x0d] =
355 0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
356 FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
357 FMT_NUM_YES_NO,FMT_GEN_END
360 static const WCHAR szOnOff[] = { 'O','n','/','O','f','f','\0' };
361 static const BYTE fmtOnOff[0x0d] =
363 0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
364 FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
365 FMT_NUM_ON_OFF,FMT_GEN_END
368 static const WCHAR szGeneralNumber[] = { 'G','e','n','e','r','a','l',' ','N','u','m','b','e','r','\0' };
369 static const BYTE fmtGeneralNumber[sizeof(FMT_HEADER)] =
371 sizeof(FMT_HEADER),FMT_TYPE_GENERAL,sizeof(FMT_HEADER),0x0,0x0,0x0
374 static const WCHAR szCurrency[] = { 'C','u','r','r','e','n','c','y','\0' };
375 static const BYTE fmtCurrency[0x26] =
377 0x26,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x12,0x0,0x0,
378 /* Positive numbers */
379 FMT_FLAG_THOUSANDS,0xcc,0x0,0x1,0x2,
380 FMT_NUM_CURRENCY,FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,
381 FMT_GEN_END,
382 /* Negative numbers */
383 FMT_FLAG_THOUSANDS,0xcc,0x0,0x1,0x2,
384 FMT_GEN_INLINE,0x1,'(','\0',FMT_NUM_CURRENCY,FMT_NUM_COPY_ZERO,0x1,
385 FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_INLINE,0x1,')','\0',
386 FMT_GEN_END
389 static const WCHAR szFixed[] = { 'F','i','x','e','d','\0' };
390 static const BYTE fmtFixed[0x11] =
392 0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
393 0x0,0x0,0x0,0x1,0x2,
394 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
397 static const WCHAR szStandard[] = { 'S','t','a','n','d','a','r','d','\0' };
398 static const BYTE fmtStandard[0x11] =
400 0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
401 FMT_FLAG_THOUSANDS,0x0,0x0,0x1,0x2,
402 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
405 static const WCHAR szPercent[] = { 'P','e','r','c','e','n','t','\0' };
406 static const BYTE fmtPercent[0x15] =
408 0x15,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
409 FMT_FLAG_PERCENT,0x1,0x0,0x1,0x2,
410 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,
411 FMT_GEN_INLINE,0x1,'%','\0',FMT_GEN_END
414 static const WCHAR szScientific[] = { 'S','c','i','e','n','t','i','f','i','c','\0' };
415 static const BYTE fmtScientific[0x13] =
417 0x13,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
418 FMT_FLAG_EXPONENT,0x0,0x0,0x1,0x2,
419 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_NUM_EXP_POS_U,0x2,FMT_GEN_END
422 typedef struct tagNAMED_FORMAT
424 LPCWSTR name;
425 const BYTE* format;
426 } NAMED_FORMAT;
428 /* Format name to tokenised format. Must be kept sorted by name */
429 static const NAMED_FORMAT VARIANT_NamedFormats[] =
431 { szCurrency, fmtCurrency },
432 { szFixed, fmtFixed },
433 { szGeneralDate, fmtGeneralDate },
434 { szGeneralNumber, fmtGeneralNumber },
435 { szLongDate, fmtLongDate },
436 { szLongTime, fmtLongTime },
437 { szMediumDate, fmtMediumDate },
438 { szMediumTime, fmtMediumTime },
439 { szOnOff, fmtOnOff },
440 { szPercent, fmtPercent },
441 { szScientific, fmtScientific },
442 { szShortDate, fmtShortDate },
443 { szShortTime, fmtShortTime },
444 { szStandard, fmtStandard },
445 { szTrueFalse, fmtTrueFalse },
446 { szYesNo, fmtYesNo }
448 typedef const NAMED_FORMAT *LPCNAMED_FORMAT;
450 static int FormatCompareFn(const void *l, const void *r)
452 return strcmpiW(((LPCNAMED_FORMAT)l)->name, ((LPCNAMED_FORMAT)r)->name);
455 static inline const BYTE *VARIANT_GetNamedFormat(LPCWSTR lpszFormat)
457 NAMED_FORMAT key;
458 LPCNAMED_FORMAT fmt;
460 key.name = lpszFormat;
461 fmt = bsearch(&key, VARIANT_NamedFormats,
462 sizeof(VARIANT_NamedFormats)/sizeof(NAMED_FORMAT),
463 sizeof(NAMED_FORMAT), FormatCompareFn);
464 return fmt ? fmt->format : NULL;
467 /* Return an error if the token for the value will not fit in the destination */
468 #define NEED_SPACE(x) if (cbTok < (int)(x)) return TYPE_E_BUFFERTOOSMALL; cbTok -= (x)
470 /* Non-zero if the format is unknown or a given type */
471 #define COULD_BE(typ) ((!fmt_number && header->type==FMT_TYPE_UNKNOWN)||header->type==typ)
473 /* State during tokenising */
474 #define FMT_STATE_OPEN_COPY 0x1 /* Last token written was a copy */
475 #define FMT_STATE_WROTE_DECIMAL 0x2 /* Already wrote a decimal separator */
476 #define FMT_STATE_SEEN_HOURS 0x4 /* See the hh specifier */
477 #define FMT_STATE_WROTE_MINUTES 0x8 /* Wrote minutes */
479 /**********************************************************************
480 * VarTokenizeFormatString [OLEAUT32.140]
482 * Convert a format string into tokenised form.
484 * PARAMS
485 * lpszFormat [I] Format string to tokenise
486 * rgbTok [O] Destination for tokenised format
487 * cbTok [I] Size of rgbTok in bytes
488 * nFirstDay [I] First day of the week (1-7, or 0 for current system default)
489 * nFirstWeek [I] How to treat the first week (see notes)
490 * lcid [I] Locale Id of the format string
491 * pcbActual [O] If non-NULL, filled with the first token generated
493 * RETURNS
494 * Success: S_OK. rgbTok contains the tokenised format.
495 * Failure: E_INVALIDARG, if any argument is invalid.
496 * TYPE_E_BUFFERTOOSMALL, if rgbTok is not large enough.
498 * NOTES
499 * Valid values for the nFirstWeek parameter are:
500 *| Value Meaning
501 *| ----- -------
502 *| 0 Use the current system default
503 *| 1 The first week is that containing Jan 1
504 *| 2 Four or more days of the first week are in the current year
505 *| 3 The first week is 7 days long
506 * See Variant-Formats(), VarFormatFromTokens().
508 HRESULT WINAPI VarTokenizeFormatString(LPOLESTR lpszFormat, LPBYTE rgbTok,
509 int cbTok, int nFirstDay, int nFirstWeek,
510 LCID lcid, int *pcbActual)
512 /* Note: none of these strings should be NUL terminated */
513 static const WCHAR szTTTTT[] = { 't','t','t','t','t' };
514 static const WCHAR szAMPM[] = { 'A','M','P','M' };
515 static const WCHAR szampm[] = { 'a','m','p','m' };
516 static const WCHAR szAMSlashPM[] = { 'A','M','/','P','M' };
517 static const WCHAR szamSlashpm[] = { 'a','m','/','p','m' };
518 const BYTE *namedFmt;
519 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
520 FMT_STRING_HEADER *str_header = (FMT_STRING_HEADER*)(rgbTok + sizeof(FMT_HEADER));
521 FMT_NUMBER_HEADER *num_header = (FMT_NUMBER_HEADER*)str_header;
522 BYTE* pOut = rgbTok + sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER);
523 BYTE* pLastHours = NULL;
524 BYTE fmt_number = 0;
525 DWORD fmt_state = 0;
526 LPCWSTR pFormat = lpszFormat;
528 TRACE("(%s,%p,%d,%d,%d,0x%08x,%p)\n", debugstr_w(lpszFormat), rgbTok, cbTok,
529 nFirstDay, nFirstWeek, lcid, pcbActual);
531 if (!rgbTok ||
532 nFirstDay < 0 || nFirstDay > 7 || nFirstWeek < 0 || nFirstWeek > 3)
533 return E_INVALIDARG;
535 if (!lpszFormat || !*lpszFormat)
537 /* An empty string means 'general format' */
538 NEED_SPACE(sizeof(BYTE));
539 *rgbTok = FMT_TO_STRING;
540 if (pcbActual)
541 *pcbActual = FMT_TO_STRING;
542 return S_OK;
545 if (cbTok > 255)
546 cbTok = 255; /* Ensure we error instead of wrapping */
548 /* Named formats */
549 namedFmt = VARIANT_GetNamedFormat(lpszFormat);
550 if (namedFmt)
552 NEED_SPACE(namedFmt[0]);
553 memcpy(rgbTok, namedFmt, namedFmt[0]);
554 TRACE("Using pre-tokenised named format %s\n", debugstr_w(lpszFormat));
555 /* FIXME: pcbActual */
556 return S_OK;
559 /* Insert header */
560 NEED_SPACE(sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER));
561 memset(header, 0, sizeof(FMT_HEADER));
562 memset(str_header, 0, sizeof(FMT_STRING_HEADER));
564 header->starts[fmt_number] = sizeof(FMT_HEADER);
566 while (*pFormat)
568 /* --------------
569 * General tokens
570 * --------------
572 if (*pFormat == ';')
574 while (*pFormat == ';')
576 TRACE(";\n");
577 if (++fmt_number > 3)
578 return E_INVALIDARG; /* too many formats */
579 pFormat++;
581 if (*pFormat)
583 TRACE("New header\n");
584 NEED_SPACE(sizeof(BYTE) + sizeof(FMT_STRING_HEADER));
585 *pOut++ = FMT_GEN_END;
587 header->starts[fmt_number] = pOut - rgbTok;
588 str_header = (FMT_STRING_HEADER*)pOut;
589 num_header = (FMT_NUMBER_HEADER*)pOut;
590 memset(str_header, 0, sizeof(FMT_STRING_HEADER));
591 pOut += sizeof(FMT_STRING_HEADER);
592 fmt_state = 0;
593 pLastHours = NULL;
596 else if (*pFormat == '\\')
598 /* Escaped character */
599 if (pFormat[1])
601 NEED_SPACE(3 * sizeof(BYTE));
602 pFormat++;
603 *pOut++ = FMT_GEN_COPY;
604 *pOut++ = pFormat - lpszFormat;
605 *pOut++ = 0x1;
606 fmt_state |= FMT_STATE_OPEN_COPY;
607 TRACE("'\\'\n");
609 else
610 fmt_state &= ~FMT_STATE_OPEN_COPY;
611 pFormat++;
613 else if (*pFormat == '"')
615 /* Escaped string
616 * Note: Native encodes "" as a copy of length zero. That's just dumb, so
617 * here we avoid encoding anything in this case.
619 if (!pFormat[1])
620 pFormat++;
621 else if (pFormat[1] == '"')
623 pFormat += 2;
625 else
627 LPCWSTR start = ++pFormat;
628 while (*pFormat && *pFormat != '"')
629 pFormat++;
630 NEED_SPACE(3 * sizeof(BYTE));
631 *pOut++ = FMT_GEN_COPY;
632 *pOut++ = start - lpszFormat;
633 *pOut++ = pFormat - start;
634 if (*pFormat == '"')
635 pFormat++;
636 TRACE("Quoted string pos %d, len %d\n", pOut[-2], pOut[-1]);
638 fmt_state &= ~FMT_STATE_OPEN_COPY;
640 /* -------------
641 * Number tokens
642 * -------------
644 else if (*pFormat == '0' && COULD_BE(FMT_TYPE_NUMBER))
646 /* Number formats: Digit from number or '0' if no digits
647 * Other formats: Literal
648 * Types the format if found
650 header->type = FMT_TYPE_NUMBER;
651 NEED_SPACE(2 * sizeof(BYTE));
652 *pOut++ = FMT_NUM_COPY_ZERO;
653 *pOut = 0x0;
654 while (*pFormat == '0')
656 *pOut = *pOut + 1;
657 pFormat++;
659 if (fmt_state & FMT_STATE_WROTE_DECIMAL)
660 num_header->fractional += *pOut;
661 else
662 num_header->whole += *pOut;
663 TRACE("%d 0's\n", *pOut);
664 pOut++;
665 fmt_state &= ~FMT_STATE_OPEN_COPY;
667 else if (*pFormat == '#' && COULD_BE(FMT_TYPE_NUMBER))
669 /* Number formats: Digit from number or blank if no digits
670 * Other formats: Literal
671 * Types the format if found
673 header->type = FMT_TYPE_NUMBER;
674 NEED_SPACE(2 * sizeof(BYTE));
675 *pOut++ = FMT_NUM_COPY_SKIP;
676 *pOut = 0x0;
677 while (*pFormat == '#')
679 *pOut = *pOut + 1;
680 pFormat++;
682 if (fmt_state & FMT_STATE_WROTE_DECIMAL)
683 num_header->fractional += *pOut;
684 else
685 num_header->whole += *pOut;
686 TRACE("%d #'s\n", *pOut);
687 pOut++;
688 fmt_state &= ~FMT_STATE_OPEN_COPY;
690 else if (*pFormat == '.' && COULD_BE(FMT_TYPE_NUMBER) &&
691 !(fmt_state & FMT_STATE_WROTE_DECIMAL))
693 /* Number formats: Decimal separator when 1st seen, literal thereafter
694 * Other formats: Literal
695 * Types the format if found
697 header->type = FMT_TYPE_NUMBER;
698 NEED_SPACE(sizeof(BYTE));
699 *pOut++ = FMT_NUM_DECIMAL;
700 fmt_state |= FMT_STATE_WROTE_DECIMAL;
701 fmt_state &= ~FMT_STATE_OPEN_COPY;
702 pFormat++;
703 TRACE("decimal sep\n");
705 else if ((*pFormat == 'e' || *pFormat == 'E') && (pFormat[1] == '-' ||
706 pFormat[1] == '+') && header->type == FMT_TYPE_NUMBER)
708 /* Number formats: Exponent specifier
709 * Other formats: Literal
711 num_header->flags |= FMT_FLAG_EXPONENT;
712 NEED_SPACE(2 * sizeof(BYTE));
713 if (*pFormat == 'e') {
714 if (pFormat[1] == '+')
715 *pOut = FMT_NUM_EXP_POS_L;
716 else
717 *pOut = FMT_NUM_EXP_NEG_L;
718 } else {
719 if (pFormat[1] == '+')
720 *pOut = FMT_NUM_EXP_POS_U;
721 else
722 *pOut = FMT_NUM_EXP_NEG_U;
724 pFormat += 2;
725 *++pOut = 0x0;
726 while (*pFormat == '0')
728 *pOut = *pOut + 1;
729 pFormat++;
731 pOut++;
732 TRACE("exponent\n");
734 /* FIXME: %% => Divide by 1000 */
735 else if (*pFormat == ',' && header->type == FMT_TYPE_NUMBER)
737 /* Number formats: Use the thousands separator
738 * Other formats: Literal
740 num_header->flags |= FMT_FLAG_THOUSANDS;
741 pFormat++;
742 fmt_state &= ~FMT_STATE_OPEN_COPY;
743 TRACE("thousands sep\n");
745 /* -----------
746 * Date tokens
747 * -----------
749 else if (*pFormat == '/' && COULD_BE(FMT_TYPE_DATE))
751 /* Date formats: Date separator
752 * Other formats: Literal
753 * Types the format if found
755 header->type = FMT_TYPE_DATE;
756 NEED_SPACE(sizeof(BYTE));
757 *pOut++ = FMT_DATE_DATE_SEP;
758 pFormat++;
759 fmt_state &= ~FMT_STATE_OPEN_COPY;
760 TRACE("date sep\n");
762 else if (*pFormat == ':' && COULD_BE(FMT_TYPE_DATE))
764 /* Date formats: Time separator
765 * Other formats: Literal
766 * Types the format if found
768 header->type = FMT_TYPE_DATE;
769 NEED_SPACE(sizeof(BYTE));
770 *pOut++ = FMT_DATE_TIME_SEP;
771 pFormat++;
772 fmt_state &= ~FMT_STATE_OPEN_COPY;
773 TRACE("time sep\n");
775 else if ((*pFormat == 'a' || *pFormat == 'A') &&
776 !strncmpiW(pFormat, szAMPM, sizeof(szAMPM)/sizeof(WCHAR)))
778 /* Date formats: System AM/PM designation
779 * Other formats: Literal
780 * Types the format if found
782 header->type = FMT_TYPE_DATE;
783 NEED_SPACE(sizeof(BYTE));
784 pFormat += sizeof(szAMPM)/sizeof(WCHAR);
785 if (!strncmpW(pFormat, szampm, sizeof(szampm)/sizeof(WCHAR)))
786 *pOut++ = FMT_DATE_AMPM_SYS2;
787 else
788 *pOut++ = FMT_DATE_AMPM_SYS1;
789 if (pLastHours)
790 *pLastHours = *pLastHours + 2;
791 TRACE("ampm\n");
793 else if (*pFormat == 'a' && pFormat[1] == '/' &&
794 (pFormat[2] == 'p' || pFormat[2] == 'P'))
796 /* Date formats: lowercase a or p designation
797 * Other formats: Literal
798 * Types the format if found
800 header->type = FMT_TYPE_DATE;
801 NEED_SPACE(sizeof(BYTE));
802 pFormat += 3;
803 *pOut++ = FMT_DATE_A_LOWER;
804 if (pLastHours)
805 *pLastHours = *pLastHours + 2;
806 TRACE("a/p\n");
808 else if (*pFormat == 'A' && pFormat[1] == '/' &&
809 (pFormat[2] == 'p' || pFormat[2] == 'P'))
811 /* Date formats: Uppercase a or p designation
812 * Other formats: Literal
813 * Types the format if found
815 header->type = FMT_TYPE_DATE;
816 NEED_SPACE(sizeof(BYTE));
817 pFormat += 3;
818 *pOut++ = FMT_DATE_A_UPPER;
819 if (pLastHours)
820 *pLastHours = *pLastHours + 2;
821 TRACE("A/P\n");
823 else if (*pFormat == 'a' &&
824 !strncmpW(pFormat, szamSlashpm, sizeof(szamSlashpm)/sizeof(WCHAR)))
826 /* Date formats: lowercase AM or PM designation
827 * Other formats: Literal
828 * Types the format if found
830 header->type = FMT_TYPE_DATE;
831 NEED_SPACE(sizeof(BYTE));
832 pFormat += sizeof(szamSlashpm)/sizeof(WCHAR);
833 *pOut++ = FMT_DATE_AMPM_LOWER;
834 if (pLastHours)
835 *pLastHours = *pLastHours + 2;
836 TRACE("AM/PM\n");
838 else if (*pFormat == 'A' &&
839 !strncmpW(pFormat, szAMSlashPM, sizeof(szAMSlashPM)/sizeof(WCHAR)))
841 /* Date formats: Uppercase AM or PM designation
842 * Other formats: Literal
843 * Types the format if found
845 header->type = FMT_TYPE_DATE;
846 NEED_SPACE(sizeof(BYTE));
847 pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
848 *pOut++ = FMT_DATE_AMPM_UPPER;
849 TRACE("AM/PM\n");
851 else if ((*pFormat == 'c' || *pFormat == 'C') && COULD_BE(FMT_TYPE_DATE))
853 /* Date formats: General date format
854 * Other formats: Literal
855 * Types the format if found
857 header->type = FMT_TYPE_DATE;
858 NEED_SPACE(sizeof(BYTE));
859 pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
860 *pOut++ = FMT_DATE_GENERAL;
861 TRACE("gen date\n");
863 else if ((*pFormat == 'd' || *pFormat == 'D') && COULD_BE(FMT_TYPE_DATE))
865 /* Date formats: Day specifier
866 * Other formats: Literal
867 * Types the format if found
869 int count = -1;
870 header->type = FMT_TYPE_DATE;
871 while ((*pFormat == 'd' || *pFormat == 'D') && count < 6)
873 pFormat++;
874 count++;
876 NEED_SPACE(sizeof(BYTE));
877 *pOut++ = FMT_DATE_DAY + count;
878 fmt_state &= ~FMT_STATE_OPEN_COPY;
879 /* When we find the days token, reset the seen hours state so that
880 * 'mm' is again written as month when encountered.
882 fmt_state &= ~FMT_STATE_SEEN_HOURS;
883 TRACE("%d d's\n", count + 1);
885 else if ((*pFormat == 'h' || *pFormat == 'H') && COULD_BE(FMT_TYPE_DATE))
887 /* Date formats: Hour specifier
888 * Other formats: Literal
889 * Types the format if found
891 header->type = FMT_TYPE_DATE;
892 NEED_SPACE(sizeof(BYTE));
893 pFormat++;
894 /* Record the position of the hours specifier - if we encounter
895 * an am/pm specifier we will change the hours from 24 to 12.
897 pLastHours = pOut;
898 if (*pFormat == 'h' || *pFormat == 'H')
900 pFormat++;
901 *pOut++ = FMT_DATE_HOUR_0;
902 TRACE("hh\n");
904 else
906 *pOut++ = FMT_DATE_HOUR;
907 TRACE("h\n");
909 fmt_state &= ~FMT_STATE_OPEN_COPY;
910 /* Note that now we have seen an hours token, the next occurrence of
911 * 'mm' indicates minutes, not months.
913 fmt_state |= FMT_STATE_SEEN_HOURS;
915 else if ((*pFormat == 'm' || *pFormat == 'M') && COULD_BE(FMT_TYPE_DATE))
917 /* Date formats: Month specifier (or Minute specifier, after hour specifier)
918 * Other formats: Literal
919 * Types the format if found
921 int count = -1;
922 header->type = FMT_TYPE_DATE;
923 while ((*pFormat == 'm' || *pFormat == 'M') && count < 4)
925 pFormat++;
926 count++;
928 NEED_SPACE(sizeof(BYTE));
929 if (count <= 1 && fmt_state & FMT_STATE_SEEN_HOURS &&
930 !(fmt_state & FMT_STATE_WROTE_MINUTES))
932 /* We have seen an hours specifier and not yet written a minutes
933 * specifier. Write this as minutes and thereafter as months.
935 *pOut++ = count == 1 ? FMT_DATE_MIN_0 : FMT_DATE_MIN;
936 fmt_state |= FMT_STATE_WROTE_MINUTES; /* Hereafter write months */
938 else
939 *pOut++ = FMT_DATE_MON + count; /* Months */
940 fmt_state &= ~FMT_STATE_OPEN_COPY;
941 TRACE("%d m's\n", count + 1);
943 else if ((*pFormat == 'n' || *pFormat == 'N') && COULD_BE(FMT_TYPE_DATE))
945 /* Date formats: Minute specifier
946 * Other formats: Literal
947 * Types the format if found
949 header->type = FMT_TYPE_DATE;
950 NEED_SPACE(sizeof(BYTE));
951 pFormat++;
952 if (*pFormat == 'n' || *pFormat == 'N')
954 pFormat++;
955 *pOut++ = FMT_DATE_MIN_0;
956 TRACE("nn\n");
958 else
960 *pOut++ = FMT_DATE_MIN;
961 TRACE("n\n");
963 fmt_state &= ~FMT_STATE_OPEN_COPY;
965 else if ((*pFormat == 'q' || *pFormat == 'Q') && COULD_BE(FMT_TYPE_DATE))
967 /* Date formats: Quarter specifier
968 * Other formats: Literal
969 * Types the format if found
971 header->type = FMT_TYPE_DATE;
972 NEED_SPACE(sizeof(BYTE));
973 *pOut++ = FMT_DATE_QUARTER;
974 pFormat++;
975 fmt_state &= ~FMT_STATE_OPEN_COPY;
976 TRACE("quarter\n");
978 else if ((*pFormat == 's' || *pFormat == 'S') && COULD_BE(FMT_TYPE_DATE))
980 /* Date formats: Second specifier
981 * Other formats: Literal
982 * Types the format if found
984 header->type = FMT_TYPE_DATE;
985 NEED_SPACE(sizeof(BYTE));
986 pFormat++;
987 if (*pFormat == 's' || *pFormat == 'S')
989 pFormat++;
990 *pOut++ = FMT_DATE_SEC_0;
991 TRACE("ss\n");
993 else
995 *pOut++ = FMT_DATE_SEC;
996 TRACE("s\n");
998 fmt_state &= ~FMT_STATE_OPEN_COPY;
1000 else if ((*pFormat == 't' || *pFormat == 'T') &&
1001 !strncmpiW(pFormat, szTTTTT, sizeof(szTTTTT)/sizeof(WCHAR)))
1003 /* Date formats: System time specifier
1004 * Other formats: Literal
1005 * Types the format if found
1007 header->type = FMT_TYPE_DATE;
1008 pFormat += sizeof(szTTTTT)/sizeof(WCHAR);
1009 NEED_SPACE(sizeof(BYTE));
1010 *pOut++ = FMT_DATE_TIME_SYS;
1011 fmt_state &= ~FMT_STATE_OPEN_COPY;
1013 else if ((*pFormat == 'w' || *pFormat == 'W') && COULD_BE(FMT_TYPE_DATE))
1015 /* Date formats: Week of the year/Day of the week
1016 * Other formats: Literal
1017 * Types the format if found
1019 header->type = FMT_TYPE_DATE;
1020 pFormat++;
1021 if (*pFormat == 'w' || *pFormat == 'W')
1023 NEED_SPACE(3 * sizeof(BYTE));
1024 pFormat++;
1025 *pOut++ = FMT_DATE_WEEK_YEAR;
1026 *pOut++ = nFirstDay;
1027 *pOut++ = nFirstWeek;
1028 TRACE("ww\n");
1030 else
1032 NEED_SPACE(2 * sizeof(BYTE));
1033 *pOut++ = FMT_DATE_DAY_WEEK;
1034 *pOut++ = nFirstDay;
1035 TRACE("w\n");
1038 fmt_state &= ~FMT_STATE_OPEN_COPY;
1040 else if ((*pFormat == 'y' || *pFormat == 'Y') && COULD_BE(FMT_TYPE_DATE))
1042 /* Date formats: Day of year/Year specifier
1043 * Other formats: Literal
1044 * Types the format if found
1046 int count = -1;
1047 header->type = FMT_TYPE_DATE;
1048 while ((*pFormat == 'y' || *pFormat == 'Y') && count < 4)
1050 pFormat++;
1051 count++;
1053 if (count == 2)
1055 count--; /* 'yyy' has no meaning, despite what MSDN says */
1056 pFormat--;
1058 NEED_SPACE(sizeof(BYTE));
1059 *pOut++ = FMT_DATE_YEAR_DOY + count;
1060 fmt_state &= ~FMT_STATE_OPEN_COPY;
1061 TRACE("%d y's\n", count + 1);
1063 /* -------------
1064 * String tokens
1065 * -------------
1067 else if (*pFormat == '@' && COULD_BE(FMT_TYPE_STRING))
1069 /* String formats: Character from string or space if no char
1070 * Other formats: Literal
1071 * Types the format if found
1073 header->type = FMT_TYPE_STRING;
1074 NEED_SPACE(2 * sizeof(BYTE));
1075 *pOut++ = FMT_STR_COPY_SPACE;
1076 *pOut = 0x0;
1077 while (*pFormat == '@')
1079 *pOut = *pOut + 1;
1080 str_header->copy_chars++;
1081 pFormat++;
1083 TRACE("%d @'s\n", *pOut);
1084 pOut++;
1085 fmt_state &= ~FMT_STATE_OPEN_COPY;
1087 else if (*pFormat == '&' && COULD_BE(FMT_TYPE_STRING))
1089 /* String formats: Character from string or skip if no char
1090 * Other formats: Literal
1091 * Types the format if found
1093 header->type = FMT_TYPE_STRING;
1094 NEED_SPACE(2 * sizeof(BYTE));
1095 *pOut++ = FMT_STR_COPY_SKIP;
1096 *pOut = 0x0;
1097 while (*pFormat == '&')
1099 *pOut = *pOut + 1;
1100 str_header->copy_chars++;
1101 pFormat++;
1103 TRACE("%d &'s\n", *pOut);
1104 pOut++;
1105 fmt_state &= ~FMT_STATE_OPEN_COPY;
1107 else if ((*pFormat == '<' || *pFormat == '>') && COULD_BE(FMT_TYPE_STRING))
1109 /* String formats: Use upper/lower case
1110 * Other formats: Literal
1111 * Types the format if found
1113 header->type = FMT_TYPE_STRING;
1114 if (*pFormat == '<')
1115 str_header->flags |= FMT_FLAG_LT;
1116 else
1117 str_header->flags |= FMT_FLAG_GT;
1118 TRACE("to %s case\n", *pFormat == '<' ? "lower" : "upper");
1119 pFormat++;
1120 fmt_state &= ~FMT_STATE_OPEN_COPY;
1122 else if (*pFormat == '!' && COULD_BE(FMT_TYPE_STRING))
1124 /* String formats: Copy right to left
1125 * Other formats: Literal
1126 * Types the format if found
1128 header->type = FMT_TYPE_STRING;
1129 str_header->flags |= FMT_FLAG_RTL;
1130 pFormat++;
1131 fmt_state &= ~FMT_STATE_OPEN_COPY;
1132 TRACE("copy right-to-left\n");
1134 /* --------
1135 * Literals
1136 * --------
1138 /* FIXME: [ seems to be ignored */
1139 else
1141 if (*pFormat == '%' && header->type == FMT_TYPE_NUMBER)
1143 /* Number formats: Percentage indicator, also a literal
1144 * Other formats: Literal
1145 * Doesn't type the format
1147 num_header->flags |= FMT_FLAG_PERCENT;
1150 if (fmt_state & FMT_STATE_OPEN_COPY)
1152 pOut[-1] = pOut[-1] + 1; /* Increase the length of the open copy */
1153 TRACE("extend copy (char '%c'), length now %d\n", *pFormat, pOut[-1]);
1155 else
1157 /* Create a new open copy */
1158 TRACE("New copy (char '%c')\n", *pFormat);
1159 NEED_SPACE(3 * sizeof(BYTE));
1160 *pOut++ = FMT_GEN_COPY;
1161 *pOut++ = pFormat - lpszFormat;
1162 *pOut++ = 0x1;
1163 fmt_state |= FMT_STATE_OPEN_COPY;
1165 pFormat++;
1169 *pOut++ = FMT_GEN_END;
1171 header->size = pOut - rgbTok;
1172 if (pcbActual)
1173 *pcbActual = header->size;
1175 return S_OK;
1178 /* Number formatting state flags */
1179 #define NUM_WROTE_DEC 0x01 /* Written the decimal separator */
1180 #define NUM_WRITE_ON 0x02 /* Started to write the number */
1181 #define NUM_WROTE_SIGN 0x04 /* Written the negative sign */
1183 /* Format a variant using a number format */
1184 static HRESULT VARIANT_FormatNumber(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1185 LPBYTE rgbTok, ULONG dwFlags,
1186 BSTR *pbstrOut, LCID lcid)
1188 BYTE rgbDig[256], *prgbDig;
1189 NUMPARSE np;
1190 int have_int, need_int = 0, have_frac, need_frac, exponent = 0, pad = 0;
1191 WCHAR buff[256], *pBuff = buff;
1192 WCHAR thousandSeparator[32];
1193 VARIANT vString, vBool;
1194 DWORD dwState = 0;
1195 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1196 FMT_NUMBER_HEADER *numHeader;
1197 const BYTE* pToken = NULL;
1198 HRESULT hRes = S_OK;
1200 TRACE("(%s,%s,%p,0x%08x,%p,0x%08x)\n", debugstr_variant(pVarIn), debugstr_w(lpszFormat),
1201 rgbTok, dwFlags, pbstrOut, lcid);
1203 V_VT(&vString) = VT_EMPTY;
1204 V_VT(&vBool) = VT_BOOL;
1206 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1208 have_int = have_frac = 0;
1209 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNull(header));
1210 V_BOOL(&vBool) = VARIANT_FALSE;
1212 else
1214 /* Get a number string from pVarIn, and parse it */
1215 hRes = VariantChangeTypeEx(&vString, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1216 if (FAILED(hRes))
1217 return hRes;
1219 np.cDig = sizeof(rgbDig);
1220 np.dwInFlags = NUMPRS_STD;
1221 hRes = VarParseNumFromStr(V_BSTR(&vString), LCID_US, 0, &np, rgbDig);
1222 if (FAILED(hRes))
1223 return hRes;
1225 have_int = np.cDig;
1226 have_frac = 0;
1227 exponent = np.nPwr10;
1229 /* Figure out which format to use */
1230 if (np.dwOutFlags & NUMPRS_NEG)
1232 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNegative(header));
1233 V_BOOL(&vBool) = VARIANT_TRUE;
1235 else if (have_int == 1 && !exponent && rgbDig[0] == 0)
1237 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetZero(header));
1238 V_BOOL(&vBool) = VARIANT_FALSE;
1240 else
1242 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetPositive(header));
1243 V_BOOL(&vBool) = VARIANT_TRUE;
1246 TRACE("num header: flags = 0x%x, mult=%d, div=%d, whole=%d, fract=%d\n",
1247 numHeader->flags, numHeader->multiplier, numHeader->divisor,
1248 numHeader->whole, numHeader->fractional);
1250 need_int = numHeader->whole;
1251 need_frac = numHeader->fractional;
1253 if (numHeader->flags & FMT_FLAG_PERCENT &&
1254 !(have_int == 1 && !exponent && rgbDig[0] == 0))
1255 exponent += 2;
1257 if (numHeader->flags & FMT_FLAG_EXPONENT)
1259 /* Exponent format: length of the integral number part is fixed and
1260 specified by the format. */
1261 pad = need_int - have_int;
1262 exponent -= pad;
1263 if (pad < 0)
1265 have_int = need_int;
1266 have_frac -= pad;
1267 pad = 0;
1270 else
1272 /* Convert the exponent */
1273 pad = max(exponent, -have_int);
1274 exponent -= pad;
1275 if (pad < 0)
1277 have_int += pad;
1278 have_frac = -pad;
1279 pad = 0;
1281 if(exponent < 0 && exponent > (-256 + have_int + have_frac))
1283 /* Remove exponent notation */
1284 memmove(rgbDig - exponent, rgbDig, have_int + have_frac);
1285 ZeroMemory(rgbDig, -exponent);
1286 have_frac -= exponent;
1287 exponent = 0;
1291 /* Rounding the number */
1292 if (have_frac > need_frac)
1294 prgbDig = &rgbDig[have_int + need_frac];
1295 have_frac = need_frac;
1296 if (*prgbDig >= 5)
1298 while (prgbDig-- > rgbDig && *prgbDig == 9)
1299 *prgbDig = 0;
1300 if (prgbDig < rgbDig)
1302 /* We reached the first digit and that was also a 9 */
1303 rgbDig[0] = 1;
1304 if (numHeader->flags & FMT_FLAG_EXPONENT)
1305 exponent++;
1306 else
1308 rgbDig[have_int + need_frac] = 0;
1309 if (exponent < 0)
1310 exponent++;
1311 else
1312 have_int++;
1315 else
1316 (*prgbDig)++;
1318 /* We converted trailing digits to zeroes => have_frac has changed */
1319 while (have_frac > 0 && rgbDig[have_int + have_frac - 1] == 0)
1320 have_frac--;
1322 TRACE("have_int=%d,need_int=%d,have_frac=%d,need_frac=%d,pad=%d,exp=%d\n",
1323 have_int, need_int, have_frac, need_frac, pad, exponent);
1326 if (numHeader->flags & FMT_FLAG_THOUSANDS)
1328 if (!GetLocaleInfoW(lcid, LOCALE_STHOUSAND, thousandSeparator,
1329 sizeof(thousandSeparator)/sizeof(WCHAR)))
1331 thousandSeparator[0] = ',';
1332 thousandSeparator[1] = 0;
1336 pToken = (const BYTE*)numHeader + sizeof(FMT_NUMBER_HEADER);
1337 prgbDig = rgbDig;
1339 while (SUCCEEDED(hRes) && *pToken != FMT_GEN_END)
1341 WCHAR defaultChar = '?';
1342 DWORD boolFlag, localeValue = 0;
1343 BOOL shouldAdvance = TRUE;
1345 if (pToken - rgbTok > header->size)
1347 ERR("Ran off the end of the format!\n");
1348 hRes = E_INVALIDARG;
1349 goto VARIANT_FormatNumber_Exit;
1352 switch (*pToken)
1354 case FMT_GEN_COPY:
1355 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1356 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1357 pBuff += pToken[2];
1358 pToken += 2;
1359 break;
1361 case FMT_GEN_INLINE:
1362 pToken += 2;
1363 TRACE("copy %s\n", debugstr_a((LPCSTR)pToken));
1364 while (*pToken)
1365 *pBuff++ = *pToken++;
1366 break;
1368 case FMT_NUM_YES_NO:
1369 boolFlag = VAR_BOOLYESNO;
1370 goto VARIANT_FormatNumber_Bool;
1372 case FMT_NUM_ON_OFF:
1373 boolFlag = VAR_BOOLONOFF;
1374 goto VARIANT_FormatNumber_Bool;
1376 case FMT_NUM_TRUE_FALSE:
1377 boolFlag = VAR_LOCALBOOL;
1379 VARIANT_FormatNumber_Bool:
1381 BSTR boolStr = NULL;
1383 if (pToken[1] != FMT_GEN_END)
1385 ERR("Boolean token not at end of format!\n");
1386 hRes = E_INVALIDARG;
1387 goto VARIANT_FormatNumber_Exit;
1389 hRes = VarBstrFromBool(V_BOOL(&vBool), lcid, boolFlag, &boolStr);
1390 if (SUCCEEDED(hRes))
1392 strcpyW(pBuff, boolStr);
1393 SysFreeString(boolStr);
1394 while (*pBuff)
1395 pBuff++;
1398 break;
1400 case FMT_NUM_DECIMAL:
1401 if ((np.dwOutFlags & NUMPRS_NEG) && !(dwState & NUM_WROTE_SIGN) && !header->starts[1])
1403 /* last chance for a negative sign in the .# case */
1404 TRACE("write negative sign\n");
1405 localeValue = LOCALE_SNEGATIVESIGN;
1406 defaultChar = '-';
1407 dwState |= NUM_WROTE_SIGN;
1408 shouldAdvance = FALSE;
1409 break;
1411 TRACE("write decimal separator\n");
1412 localeValue = LOCALE_SDECIMAL;
1413 defaultChar = '.';
1414 dwState |= NUM_WROTE_DEC;
1415 break;
1417 case FMT_NUM_CURRENCY:
1418 TRACE("write currency symbol\n");
1419 localeValue = LOCALE_SCURRENCY;
1420 defaultChar = '$';
1421 break;
1423 case FMT_NUM_EXP_POS_U:
1424 case FMT_NUM_EXP_POS_L:
1425 case FMT_NUM_EXP_NEG_U:
1426 case FMT_NUM_EXP_NEG_L:
1427 if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_NEG_L)
1428 *pBuff++ = 'e';
1429 else
1430 *pBuff++ = 'E';
1431 if (exponent < 0)
1433 *pBuff++ = '-';
1434 sprintfW(pBuff, szPercentZeroStar_d, pToken[1], -exponent);
1436 else
1438 if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_POS_U)
1439 *pBuff++ = '+';
1440 sprintfW(pBuff, szPercentZeroStar_d, pToken[1], exponent);
1442 while (*pBuff)
1443 pBuff++;
1444 pToken++;
1445 break;
1447 case FMT_NUM_COPY_ZERO:
1448 dwState |= NUM_WRITE_ON;
1449 /* Fall through */
1451 case FMT_NUM_COPY_SKIP:
1452 TRACE("write %d %sdigits or %s\n", pToken[1],
1453 dwState & NUM_WROTE_DEC ? "fractional " : "",
1454 *pToken == FMT_NUM_COPY_ZERO ? "0" : "skip");
1456 if (dwState & NUM_WROTE_DEC)
1458 int count, i;
1460 if (!(numHeader->flags & FMT_FLAG_EXPONENT) && exponent < 0)
1462 /* Pad with 0 before writing the fractional digits */
1463 pad = max(exponent, -pToken[1]);
1464 exponent -= pad;
1465 count = min(have_frac, pToken[1] + pad);
1466 for (i = 0; i > pad; i--)
1467 *pBuff++ = '0';
1469 else
1470 count = min(have_frac, pToken[1]);
1472 pad += pToken[1] - count;
1473 have_frac -= count;
1474 while (count--)
1475 *pBuff++ = '0' + *prgbDig++;
1476 if (*pToken == FMT_NUM_COPY_ZERO)
1478 for (; pad > 0; pad--)
1479 *pBuff++ = '0'; /* Write zeros for missing trailing digits */
1482 else
1484 int count, count_max, position;
1486 if ((np.dwOutFlags & NUMPRS_NEG) && !(dwState & NUM_WROTE_SIGN) && !header->starts[1])
1488 TRACE("write negative sign\n");
1489 localeValue = LOCALE_SNEGATIVESIGN;
1490 defaultChar = '-';
1491 dwState |= NUM_WROTE_SIGN;
1492 shouldAdvance = FALSE;
1493 break;
1496 position = have_int + pad;
1497 if (dwState & NUM_WRITE_ON)
1498 position = max(position, need_int);
1499 need_int -= pToken[1];
1500 count_max = have_int + pad - need_int;
1501 if (count_max < 0)
1502 count_max = 0;
1503 if (dwState & NUM_WRITE_ON)
1505 count = pToken[1] - count_max;
1506 TRACE("write %d leading zeros\n", count);
1507 while (count-- > 0)
1509 *pBuff++ = '0';
1510 if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1511 position > 1 && (--position % 3) == 0)
1513 int k;
1514 TRACE("write thousand separator\n");
1515 for (k = 0; thousandSeparator[k]; k++)
1516 *pBuff++ = thousandSeparator[k];
1520 if (*pToken == FMT_NUM_COPY_ZERO || have_int > 1 ||
1521 (have_int > 0 && *prgbDig > 0))
1523 count = min(count_max, have_int);
1524 count_max -= count;
1525 have_int -= count;
1526 TRACE("write %d whole number digits\n", count);
1527 while (count--)
1529 dwState |= NUM_WRITE_ON;
1530 *pBuff++ = '0' + *prgbDig++;
1531 if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1532 position > 1 && (--position % 3) == 0)
1534 int k;
1535 TRACE("write thousand separator\n");
1536 for (k = 0; thousandSeparator[k]; k++)
1537 *pBuff++ = thousandSeparator[k];
1541 count = min(count_max, pad);
1542 pad -= count;
1543 TRACE("write %d whole trailing 0's\n", count);
1544 while (count--)
1546 *pBuff++ = '0';
1547 if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
1548 position > 1 && (--position % 3) == 0)
1550 int k;
1551 TRACE("write thousand separator\n");
1552 for (k = 0; thousandSeparator[k]; k++)
1553 *pBuff++ = thousandSeparator[k];
1557 pToken++;
1558 break;
1560 default:
1561 ERR("Unknown token 0x%02x!\n", *pToken);
1562 hRes = E_INVALIDARG;
1563 goto VARIANT_FormatNumber_Exit;
1565 if (localeValue)
1567 if (GetLocaleInfoW(lcid, localeValue, pBuff,
1568 sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1570 TRACE("added %s\n", debugstr_w(pBuff));
1571 while (*pBuff)
1572 pBuff++;
1574 else
1576 TRACE("added %d '%c'\n", defaultChar, defaultChar);
1577 *pBuff++ = defaultChar;
1580 if (shouldAdvance)
1581 pToken++;
1584 VARIANT_FormatNumber_Exit:
1585 VariantClear(&vString);
1586 *pBuff = '\0';
1587 TRACE("buff is %s\n", debugstr_w(buff));
1588 if (SUCCEEDED(hRes))
1590 *pbstrOut = SysAllocString(buff);
1591 if (!*pbstrOut)
1592 hRes = E_OUTOFMEMORY;
1594 return hRes;
1597 /* Format a variant using a date format */
1598 static HRESULT VARIANT_FormatDate(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1599 LPBYTE rgbTok, ULONG dwFlags,
1600 BSTR *pbstrOut, LCID lcid)
1602 WCHAR buff[256], *pBuff = buff;
1603 VARIANT vDate;
1604 UDATE udate;
1605 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1606 FMT_DATE_HEADER *dateHeader;
1607 const BYTE* pToken = NULL;
1608 HRESULT hRes;
1610 TRACE("(%s,%s,%p,0x%08x,%p,0x%08x)\n", debugstr_variant(pVarIn),
1611 debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut, lcid);
1613 V_VT(&vDate) = VT_EMPTY;
1615 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1617 dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetNegative(header));
1618 V_DATE(&vDate) = 0;
1620 else
1622 USHORT usFlags = dwFlags & VARIANT_CALENDAR_HIJRI ? VAR_CALENDAR_HIJRI : 0;
1624 hRes = VariantChangeTypeEx(&vDate, pVarIn, LCID_US, usFlags, VT_DATE);
1625 if (FAILED(hRes))
1626 return hRes;
1627 dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetPositive(header));
1630 hRes = VarUdateFromDate(V_DATE(&vDate), 0 /* FIXME: flags? */, &udate);
1631 if (FAILED(hRes))
1632 return hRes;
1633 pToken = (const BYTE*)dateHeader + sizeof(FMT_DATE_HEADER);
1635 while (*pToken != FMT_GEN_END)
1637 DWORD dwVal = 0, localeValue = 0, dwFmt = 0;
1638 LPCWSTR szPrintFmt = NULL;
1639 WCHAR defaultChar = '?';
1641 if (pToken - rgbTok > header->size)
1643 ERR("Ran off the end of the format!\n");
1644 hRes = E_INVALIDARG;
1645 goto VARIANT_FormatDate_Exit;
1648 switch (*pToken)
1650 case FMT_GEN_COPY:
1651 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1652 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1653 pBuff += pToken[2];
1654 pToken += 2;
1655 break;
1657 case FMT_GEN_INLINE:
1658 pToken += 2;
1659 TRACE("copy %s\n", debugstr_a((LPCSTR)pToken));
1660 while (*pToken)
1661 *pBuff++ = *pToken++;
1662 break;
1664 case FMT_DATE_TIME_SEP:
1665 TRACE("time separator\n");
1666 localeValue = LOCALE_STIME;
1667 defaultChar = ':';
1668 break;
1670 case FMT_DATE_DATE_SEP:
1671 TRACE("date separator\n");
1672 localeValue = LOCALE_SDATE;
1673 defaultChar = '/';
1674 break;
1676 case FMT_DATE_GENERAL:
1678 BSTR date = NULL;
1679 WCHAR *pDate;
1680 hRes = VarBstrFromDate(V_DATE(&vDate), lcid, 0, &date);
1681 if (FAILED(hRes))
1682 goto VARIANT_FormatDate_Exit;
1683 pDate = date;
1684 while (*pDate)
1685 *pBuff++ = *pDate++;
1686 SysFreeString(date);
1688 break;
1690 case FMT_DATE_QUARTER:
1691 if (udate.st.wMonth <= 3)
1692 *pBuff++ = '1';
1693 else if (udate.st.wMonth <= 6)
1694 *pBuff++ = '2';
1695 else if (udate.st.wMonth <= 9)
1696 *pBuff++ = '3';
1697 else
1698 *pBuff++ = '4';
1699 break;
1701 case FMT_DATE_TIME_SYS:
1703 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1704 BSTR date = NULL;
1705 WCHAR *pDate;
1706 hRes = VarBstrFromDate(V_DATE(&vDate), lcid, VAR_TIMEVALUEONLY, &date);
1707 if (FAILED(hRes))
1708 goto VARIANT_FormatDate_Exit;
1709 pDate = date;
1710 while (*pDate)
1711 *pBuff++ = *pDate++;
1712 SysFreeString(date);
1714 break;
1716 case FMT_DATE_DAY:
1717 szPrintFmt = szPercent_d;
1718 dwVal = udate.st.wDay;
1719 break;
1721 case FMT_DATE_DAY_0:
1722 szPrintFmt = szPercentZeroTwo_d;
1723 dwVal = udate.st.wDay;
1724 break;
1726 case FMT_DATE_DAY_SHORT:
1727 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1728 TRACE("short day\n");
1729 localeValue = LOCALE_SABBREVDAYNAME1 + (udate.st.wDayOfWeek + 6)%7;
1730 defaultChar = '?';
1731 break;
1733 case FMT_DATE_DAY_LONG:
1734 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1735 TRACE("long day\n");
1736 localeValue = LOCALE_SDAYNAME1 + (udate.st.wDayOfWeek + 6)%7;
1737 defaultChar = '?';
1738 break;
1740 case FMT_DATE_SHORT:
1741 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1742 dwFmt = LOCALE_SSHORTDATE;
1743 break;
1745 case FMT_DATE_LONG:
1746 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1747 dwFmt = LOCALE_SLONGDATE;
1748 break;
1750 case FMT_DATE_MEDIUM:
1751 FIXME("Medium date treated as long date\n");
1752 dwFmt = LOCALE_SLONGDATE;
1753 break;
1755 case FMT_DATE_DAY_WEEK:
1756 szPrintFmt = szPercent_d;
1757 if (pToken[1])
1758 dwVal = udate.st.wDayOfWeek + 2 - pToken[1];
1759 else
1761 GetLocaleInfoW(lcid,LOCALE_RETURN_NUMBER|LOCALE_IFIRSTDAYOFWEEK,
1762 (LPWSTR)&dwVal, sizeof(dwVal)/sizeof(WCHAR));
1763 dwVal = udate.st.wDayOfWeek + 1 - dwVal;
1765 pToken++;
1766 break;
1768 case FMT_DATE_WEEK_YEAR:
1769 szPrintFmt = szPercent_d;
1770 dwVal = udate.wDayOfYear / 7 + 1;
1771 pToken += 2;
1772 FIXME("Ignoring nFirstDay of %d, nFirstWeek of %d\n", pToken[0], pToken[1]);
1773 break;
1775 case FMT_DATE_MON:
1776 szPrintFmt = szPercent_d;
1777 dwVal = udate.st.wMonth;
1778 break;
1780 case FMT_DATE_MON_0:
1781 szPrintFmt = szPercentZeroTwo_d;
1782 dwVal = udate.st.wMonth;
1783 break;
1785 case FMT_DATE_MON_SHORT:
1786 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1787 TRACE("short month\n");
1788 localeValue = LOCALE_SABBREVMONTHNAME1 + udate.st.wMonth - 1;
1789 defaultChar = '?';
1790 break;
1792 case FMT_DATE_MON_LONG:
1793 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1794 TRACE("long month\n");
1795 localeValue = LOCALE_SMONTHNAME1 + udate.st.wMonth - 1;
1796 defaultChar = '?';
1797 break;
1799 case FMT_DATE_YEAR_DOY:
1800 szPrintFmt = szPercent_d;
1801 dwVal = udate.wDayOfYear;
1802 break;
1804 case FMT_DATE_YEAR_0:
1805 szPrintFmt = szPercentZeroTwo_d;
1806 dwVal = udate.st.wYear % 100;
1807 break;
1809 case FMT_DATE_YEAR_LONG:
1810 szPrintFmt = szPercent_d;
1811 dwVal = udate.st.wYear;
1812 break;
1814 case FMT_DATE_MIN:
1815 szPrintFmt = szPercent_d;
1816 dwVal = udate.st.wMinute;
1817 break;
1819 case FMT_DATE_MIN_0:
1820 szPrintFmt = szPercentZeroTwo_d;
1821 dwVal = udate.st.wMinute;
1822 break;
1824 case FMT_DATE_SEC:
1825 szPrintFmt = szPercent_d;
1826 dwVal = udate.st.wSecond;
1827 break;
1829 case FMT_DATE_SEC_0:
1830 szPrintFmt = szPercentZeroTwo_d;
1831 dwVal = udate.st.wSecond;
1832 break;
1834 case FMT_DATE_HOUR:
1835 szPrintFmt = szPercent_d;
1836 dwVal = udate.st.wHour;
1837 break;
1839 case FMT_DATE_HOUR_0:
1840 case FMT_DATE_TIME_UNK2:
1841 szPrintFmt = szPercentZeroTwo_d;
1842 dwVal = udate.st.wHour;
1843 break;
1845 case FMT_DATE_HOUR_12:
1846 szPrintFmt = szPercent_d;
1847 dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
1848 break;
1850 case FMT_DATE_HOUR_12_0:
1851 szPrintFmt = szPercentZeroTwo_d;
1852 dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
1853 break;
1855 case FMT_DATE_AMPM_SYS1:
1856 case FMT_DATE_AMPM_SYS2:
1857 localeValue = udate.st.wHour < 12 ? LOCALE_S1159 : LOCALE_S2359;
1858 defaultChar = '?';
1859 break;
1861 case FMT_DATE_AMPM_UPPER:
1862 *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1863 *pBuff++ = 'M';
1864 break;
1866 case FMT_DATE_A_UPPER:
1867 *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1868 break;
1870 case FMT_DATE_AMPM_LOWER:
1871 *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1872 *pBuff++ = 'm';
1873 break;
1875 case FMT_DATE_A_LOWER:
1876 *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1877 break;
1879 default:
1880 ERR("Unknown token 0x%02x!\n", *pToken);
1881 hRes = E_INVALIDARG;
1882 goto VARIANT_FormatDate_Exit;
1884 if (localeValue)
1886 *pBuff = '\0';
1887 if (GetLocaleInfoW(lcid, localeValue, pBuff,
1888 sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1890 TRACE("added %s\n", debugstr_w(pBuff));
1891 while (*pBuff)
1892 pBuff++;
1894 else
1896 TRACE("added %d %c\n", defaultChar, defaultChar);
1897 *pBuff++ = defaultChar;
1900 else if (dwFmt)
1902 WCHAR fmt_buff[80];
1904 if (!GetLocaleInfoW(lcid, dwFmt, fmt_buff, sizeof(fmt_buff)/sizeof(WCHAR)) ||
1905 !get_date_format(lcid, 0, &udate.st, fmt_buff, pBuff,
1906 sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1908 hRes = E_INVALIDARG;
1909 goto VARIANT_FormatDate_Exit;
1911 while (*pBuff)
1912 pBuff++;
1914 else if (szPrintFmt)
1916 sprintfW(pBuff, szPrintFmt, dwVal);
1917 while (*pBuff)
1918 pBuff++;
1920 pToken++;
1923 VARIANT_FormatDate_Exit:
1924 *pBuff = '\0';
1925 TRACE("buff is %s\n", debugstr_w(buff));
1926 if (SUCCEEDED(hRes))
1928 *pbstrOut = SysAllocString(buff);
1929 if (!*pbstrOut)
1930 hRes = E_OUTOFMEMORY;
1932 return hRes;
1935 /* Format a variant using a string format */
1936 static HRESULT VARIANT_FormatString(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1937 LPBYTE rgbTok, ULONG dwFlags,
1938 BSTR *pbstrOut, LCID lcid)
1940 static WCHAR szEmpty[] = { '\0' };
1941 WCHAR buff[256], *pBuff = buff;
1942 WCHAR *pSrc;
1943 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1944 FMT_STRING_HEADER *strHeader;
1945 const BYTE* pToken = NULL;
1946 VARIANT vStr;
1947 int blanks_first;
1948 BOOL bUpper = FALSE;
1949 HRESULT hRes = S_OK;
1951 TRACE("%s,%s,%p,0x%08x,%p,0x%08x)\n", debugstr_variant(pVarIn), debugstr_w(lpszFormat),
1952 rgbTok, dwFlags, pbstrOut, lcid);
1954 V_VT(&vStr) = VT_EMPTY;
1956 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1958 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1959 V_BSTR(&vStr) = szEmpty;
1961 else
1963 hRes = VariantChangeTypeEx(&vStr, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1964 if (FAILED(hRes))
1965 return hRes;
1967 if (V_BSTR(&vStr)[0] == '\0')
1968 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1969 else
1970 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetPositive(header));
1972 pSrc = V_BSTR(&vStr);
1973 if ((strHeader->flags & (FMT_FLAG_LT|FMT_FLAG_GT)) == FMT_FLAG_GT)
1974 bUpper = TRUE;
1975 blanks_first = strHeader->copy_chars - strlenW(pSrc);
1976 pToken = (const BYTE*)strHeader + sizeof(FMT_DATE_HEADER);
1978 while (*pToken != FMT_GEN_END)
1980 int dwCount = 0;
1982 if (pToken - rgbTok > header->size)
1984 ERR("Ran off the end of the format!\n");
1985 hRes = E_INVALIDARG;
1986 goto VARIANT_FormatString_Exit;
1989 switch (*pToken)
1991 case FMT_GEN_COPY:
1992 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1993 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1994 pBuff += pToken[2];
1995 pToken += 2;
1996 break;
1998 case FMT_STR_COPY_SPACE:
1999 case FMT_STR_COPY_SKIP:
2000 dwCount = pToken[1];
2001 if (*pToken == FMT_STR_COPY_SPACE && blanks_first > 0)
2003 TRACE("insert %d initial spaces\n", blanks_first);
2004 while (dwCount > 0 && blanks_first > 0)
2006 *pBuff++ = ' ';
2007 dwCount--;
2008 blanks_first--;
2011 TRACE("copy %d chars%s\n", dwCount,
2012 *pToken == FMT_STR_COPY_SPACE ? " with space" :"");
2013 while (dwCount > 0 && *pSrc)
2015 if (bUpper)
2016 *pBuff++ = toupperW(*pSrc);
2017 else
2018 *pBuff++ = tolowerW(*pSrc);
2019 dwCount--;
2020 pSrc++;
2022 if (*pToken == FMT_STR_COPY_SPACE && dwCount > 0)
2024 TRACE("insert %d spaces\n", dwCount);
2025 while (dwCount-- > 0)
2026 *pBuff++ = ' ';
2028 pToken++;
2029 break;
2031 default:
2032 ERR("Unknown token 0x%02x!\n", *pToken);
2033 hRes = E_INVALIDARG;
2034 goto VARIANT_FormatString_Exit;
2036 pToken++;
2039 VARIANT_FormatString_Exit:
2040 /* Copy out any remaining chars */
2041 while (*pSrc)
2043 if (bUpper)
2044 *pBuff++ = toupperW(*pSrc);
2045 else
2046 *pBuff++ = tolowerW(*pSrc);
2047 pSrc++;
2049 VariantClear(&vStr);
2050 *pBuff = '\0';
2051 TRACE("buff is %s\n", debugstr_w(buff));
2052 if (SUCCEEDED(hRes))
2054 *pbstrOut = SysAllocString(buff);
2055 if (!*pbstrOut)
2056 hRes = E_OUTOFMEMORY;
2058 return hRes;
2061 #define NUMBER_VTBITS (VTBIT_I1|VTBIT_UI1|VTBIT_I2|VTBIT_UI2| \
2062 VTBIT_I4|VTBIT_UI4|VTBIT_I8|VTBIT_UI8| \
2063 VTBIT_R4|VTBIT_R8|VTBIT_CY|VTBIT_DECIMAL| \
2064 VTBIT_BOOL|VTBIT_INT|VTBIT_UINT)
2066 /**********************************************************************
2067 * VarFormatFromTokens [OLEAUT32.139]
2069 HRESULT WINAPI VarFormatFromTokens(LPVARIANT pVarIn, LPOLESTR lpszFormat,
2070 LPBYTE rgbTok, ULONG dwFlags,
2071 BSTR *pbstrOut, LCID lcid)
2073 FMT_SHORT_HEADER *header = (FMT_SHORT_HEADER *)rgbTok;
2074 VARIANT vTmp;
2075 HRESULT hres;
2077 TRACE("(%p,%s,%p,%x,%p,0x%08x)\n", pVarIn, debugstr_w(lpszFormat),
2078 rgbTok, dwFlags, pbstrOut, lcid);
2080 if (!pbstrOut)
2081 return E_INVALIDARG;
2083 *pbstrOut = NULL;
2085 if (!pVarIn || !rgbTok)
2086 return E_INVALIDARG;
2088 if (V_VT(pVarIn) == VT_NULL)
2089 return S_OK;
2091 if (*rgbTok == FMT_TO_STRING || header->type == FMT_TYPE_GENERAL)
2093 /* According to MSDN, general format acts somewhat like the 'Str'
2094 * function in Visual Basic.
2096 VarFormatFromTokens_AsStr:
2097 V_VT(&vTmp) = VT_EMPTY;
2098 hres = VariantChangeTypeEx(&vTmp, pVarIn, lcid, dwFlags, VT_BSTR);
2099 *pbstrOut = V_BSTR(&vTmp);
2101 else
2103 if (header->type == FMT_TYPE_NUMBER ||
2104 (header->type == FMT_TYPE_UNKNOWN && ((1 << V_TYPE(pVarIn)) & NUMBER_VTBITS)))
2106 hres = VARIANT_FormatNumber(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2108 else if (header->type == FMT_TYPE_DATE ||
2109 (header->type == FMT_TYPE_UNKNOWN && V_TYPE(pVarIn) == VT_DATE))
2111 hres = VARIANT_FormatDate(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2113 else if (header->type == FMT_TYPE_STRING || V_TYPE(pVarIn) == VT_BSTR)
2115 hres = VARIANT_FormatString(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2117 else
2119 ERR("unrecognised format type 0x%02x\n", header->type);
2120 return E_INVALIDARG;
2122 /* If the coercion failed, still try to create output, unless the
2123 * VAR_FORMAT_NOSUBSTITUTE flag is set.
2125 if ((hres == DISP_E_OVERFLOW || hres == DISP_E_TYPEMISMATCH) &&
2126 !(dwFlags & VAR_FORMAT_NOSUBSTITUTE))
2127 goto VarFormatFromTokens_AsStr;
2130 return hres;
2133 /**********************************************************************
2134 * VarFormat [OLEAUT32.87]
2136 * Format a variant from a format string.
2138 * PARAMS
2139 * pVarIn [I] Variant to format
2140 * lpszFormat [I] Format string (see notes)
2141 * nFirstDay [I] First day of the week, (See VarTokenizeFormatString() for details)
2142 * nFirstWeek [I] First week of the year (See VarTokenizeFormatString() for details)
2143 * dwFlags [I] Flags for the format (VAR_ flags from "oleauto.h")
2144 * pbstrOut [O] Destination for formatted string.
2146 * RETURNS
2147 * Success: S_OK. pbstrOut contains the formatted value.
2148 * Failure: E_INVALIDARG, if any parameter is invalid.
2149 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2150 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2152 * NOTES
2153 * - See Variant-Formats for details concerning creating format strings.
2154 * - This function uses LOCALE_USER_DEFAULT when calling VarTokenizeFormatString()
2155 * and VarFormatFromTokens().
2157 HRESULT WINAPI VarFormat(LPVARIANT pVarIn, LPOLESTR lpszFormat,
2158 int nFirstDay, int nFirstWeek, ULONG dwFlags,
2159 BSTR *pbstrOut)
2161 BYTE buff[256];
2162 HRESULT hres;
2164 TRACE("(%s,%s,%d,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), debugstr_w(lpszFormat),
2165 nFirstDay, nFirstWeek, dwFlags, pbstrOut);
2167 if (!pbstrOut)
2168 return E_INVALIDARG;
2169 *pbstrOut = NULL;
2171 hres = VarTokenizeFormatString(lpszFormat, buff, sizeof(buff), nFirstDay,
2172 nFirstWeek, LOCALE_USER_DEFAULT, NULL);
2173 if (SUCCEEDED(hres))
2174 hres = VarFormatFromTokens(pVarIn, lpszFormat, buff, dwFlags,
2175 pbstrOut, LOCALE_USER_DEFAULT);
2176 TRACE("returning 0x%08x, %s\n", hres, debugstr_w(*pbstrOut));
2177 return hres;
2180 /**********************************************************************
2181 * VarFormatDateTime [OLEAUT32.97]
2183 * Format a variant value as a date and/or time.
2185 * PARAMS
2186 * pVarIn [I] Variant to format
2187 * nFormat [I] Format type (see notes)
2188 * dwFlags [I] Flags for the format (VAR_ flags from "oleauto.h")
2189 * pbstrOut [O] Destination for formatted string.
2191 * RETURNS
2192 * Success: S_OK. pbstrOut contains the formatted value.
2193 * Failure: E_INVALIDARG, if any parameter is invalid.
2194 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2195 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2197 * NOTES
2198 * This function uses LOCALE_USER_DEFAULT when determining the date format
2199 * characters to use.
2200 * Possible values for the nFormat parameter are:
2201 *| Value Meaning
2202 *| ----- -------
2203 *| 0 General date format
2204 *| 1 Long date format
2205 *| 2 Short date format
2206 *| 3 Long time format
2207 *| 4 Short time format
2209 HRESULT WINAPI VarFormatDateTime(LPVARIANT pVarIn, INT nFormat, ULONG dwFlags, BSTR *pbstrOut)
2211 static WCHAR szEmpty[] = { '\0' };
2212 const BYTE* lpFmt = NULL;
2214 TRACE("%s,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), nFormat, dwFlags, pbstrOut);
2216 if (!pVarIn || !pbstrOut || nFormat < 0 || nFormat > 4)
2217 return E_INVALIDARG;
2219 switch (nFormat)
2221 case 0: lpFmt = fmtGeneralDate; break;
2222 case 1: lpFmt = fmtLongDate; break;
2223 case 2: lpFmt = fmtShortDate; break;
2224 case 3: lpFmt = fmtLongTime; break;
2225 case 4: lpFmt = fmtShortTime; break;
2227 return VarFormatFromTokens(pVarIn, szEmpty, (BYTE*)lpFmt, dwFlags,
2228 pbstrOut, LOCALE_USER_DEFAULT);
2231 #define GETLOCALENUMBER(type,field) GetLocaleInfoW(LOCALE_USER_DEFAULT, \
2232 type|LOCALE_RETURN_NUMBER, \
2233 (LPWSTR)&numfmt.field, \
2234 sizeof(numfmt.field)/sizeof(WCHAR))
2236 /**********************************************************************
2237 * VarFormatNumber [OLEAUT32.107]
2239 * Format a variant value as a number.
2241 * PARAMS
2242 * pVarIn [I] Variant to format
2243 * nDigits [I] Number of digits following the decimal point (-1 = user default)
2244 * nLeading [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2245 * nParens [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2246 * nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2247 * dwFlags [I] Currently unused, set to zero
2248 * pbstrOut [O] Destination for formatted string.
2250 * RETURNS
2251 * Success: S_OK. pbstrOut contains the formatted value.
2252 * Failure: E_INVALIDARG, if any parameter is invalid.
2253 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2254 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2256 * NOTES
2257 * This function uses LOCALE_USER_DEFAULT when determining the number format
2258 * characters to use.
2260 HRESULT WINAPI VarFormatNumber(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2261 INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2263 HRESULT hRet;
2264 VARIANT vStr;
2266 TRACE("(%s,%d,%d,%d,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), nDigits, nLeading,
2267 nParens, nGrouping, dwFlags, pbstrOut);
2269 if (!pVarIn || !pbstrOut || nDigits > 9)
2270 return E_INVALIDARG;
2272 *pbstrOut = NULL;
2274 V_VT(&vStr) = VT_EMPTY;
2275 hRet = VariantCopyInd(&vStr, pVarIn);
2277 if (SUCCEEDED(hRet))
2278 hRet = VariantChangeTypeEx(&vStr, &vStr, LCID_US, 0, VT_BSTR);
2280 if (SUCCEEDED(hRet))
2282 WCHAR buff[256], decimal[8], thousands[8];
2283 NUMBERFMTW numfmt;
2285 /* Although MSDN makes it clear that the native versions of these functions
2286 * are implemented using VarTokenizeFormatString()/VarFormatFromTokens(),
2287 * using NLS gives us the same result.
2289 if (nDigits < 0)
2290 GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2291 else
2292 numfmt.NumDigits = nDigits;
2294 if (nLeading == -2)
2295 GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2296 else if (nLeading == -1)
2297 numfmt.LeadingZero = 1;
2298 else
2299 numfmt.LeadingZero = 0;
2301 if (nGrouping == -2)
2303 WCHAR grouping[16];
2304 grouping[2] = '\0';
2305 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, grouping,
2306 sizeof(grouping)/sizeof(WCHAR));
2307 numfmt.Grouping = grouping[2] == '2' ? 32 : grouping[0] - '0';
2309 else if (nGrouping == -1)
2310 numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2311 else
2312 numfmt.Grouping = 0; /* 0 = No grouping */
2314 if (nParens == -2)
2315 GETLOCALENUMBER(LOCALE_INEGNUMBER, NegativeOrder);
2316 else if (nParens == -1)
2317 numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2318 else
2319 numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2321 numfmt.lpDecimalSep = decimal;
2322 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal,
2323 sizeof(decimal)/sizeof(WCHAR));
2324 numfmt.lpThousandSep = thousands;
2325 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_STHOUSAND, thousands,
2326 sizeof(thousands)/sizeof(WCHAR));
2328 if (GetNumberFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
2329 buff, sizeof(buff)/sizeof(WCHAR)))
2331 *pbstrOut = SysAllocString(buff);
2332 if (!*pbstrOut)
2333 hRet = E_OUTOFMEMORY;
2335 else
2336 hRet = DISP_E_TYPEMISMATCH;
2338 SysFreeString(V_BSTR(&vStr));
2340 return hRet;
2343 /**********************************************************************
2344 * VarFormatPercent [OLEAUT32.117]
2346 * Format a variant value as a percentage.
2348 * PARAMS
2349 * pVarIn [I] Variant to format
2350 * nDigits [I] Number of digits following the decimal point (-1 = user default)
2351 * nLeading [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2352 * nParens [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2353 * nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2354 * dwFlags [I] Currently unused, set to zero
2355 * pbstrOut [O] Destination for formatted string.
2357 * RETURNS
2358 * Success: S_OK. pbstrOut contains the formatted value.
2359 * Failure: E_INVALIDARG, if any parameter is invalid.
2360 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2361 * DISP_E_OVERFLOW, if overflow occurs during the conversion.
2362 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2364 * NOTES
2365 * This function uses LOCALE_USER_DEFAULT when determining the number format
2366 * characters to use.
2368 HRESULT WINAPI VarFormatPercent(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2369 INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2371 static const WCHAR szPercent[] = { '%','\0' };
2372 static const WCHAR szPercentBracket[] = { '%',')','\0' };
2373 WCHAR buff[256];
2374 HRESULT hRet;
2375 VARIANT vDbl;
2377 TRACE("(%s,%d,%d,%d,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), nDigits, nLeading,
2378 nParens, nGrouping, dwFlags, pbstrOut);
2380 if (!pVarIn || !pbstrOut || nDigits > 9)
2381 return E_INVALIDARG;
2383 *pbstrOut = NULL;
2385 V_VT(&vDbl) = VT_EMPTY;
2386 hRet = VariantCopyInd(&vDbl, pVarIn);
2388 if (SUCCEEDED(hRet))
2390 hRet = VariantChangeTypeEx(&vDbl, &vDbl, LOCALE_USER_DEFAULT, 0, VT_R8);
2392 if (SUCCEEDED(hRet))
2394 if (V_R8(&vDbl) > (R8_MAX / 100.0))
2395 return DISP_E_OVERFLOW;
2397 V_R8(&vDbl) *= 100.0;
2398 hRet = VarFormatNumber(&vDbl, nDigits, nLeading, nParens,
2399 nGrouping, dwFlags, pbstrOut);
2401 if (SUCCEEDED(hRet))
2403 DWORD dwLen = strlenW(*pbstrOut);
2404 BOOL bBracket = (*pbstrOut)[dwLen] == ')';
2406 dwLen -= bBracket;
2407 memcpy(buff, *pbstrOut, dwLen * sizeof(WCHAR));
2408 strcpyW(buff + dwLen, bBracket ? szPercentBracket : szPercent);
2409 SysFreeString(*pbstrOut);
2410 *pbstrOut = SysAllocString(buff);
2411 if (!*pbstrOut)
2412 hRet = E_OUTOFMEMORY;
2416 return hRet;
2419 /**********************************************************************
2420 * VarFormatCurrency [OLEAUT32.127]
2422 * Format a variant value as a currency.
2424 * PARAMS
2425 * pVarIn [I] Variant to format
2426 * nDigits [I] Number of digits following the decimal point (-1 = user default)
2427 * nLeading [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
2428 * nParens [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
2429 * nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
2430 * dwFlags [I] Currently unused, set to zero
2431 * pbstrOut [O] Destination for formatted string.
2433 * RETURNS
2434 * Success: S_OK. pbstrOut contains the formatted value.
2435 * Failure: E_INVALIDARG, if any parameter is invalid.
2436 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2437 * DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
2439 * NOTES
2440 * This function uses LOCALE_USER_DEFAULT when determining the currency format
2441 * characters to use.
2443 HRESULT WINAPI VarFormatCurrency(LPVARIANT pVarIn, INT nDigits, INT nLeading,
2444 INT nParens, INT nGrouping, ULONG dwFlags,
2445 BSTR *pbstrOut)
2447 HRESULT hRet;
2448 VARIANT vStr;
2450 TRACE("(%s,%d,%d,%d,%d,0x%08x,%p)\n", debugstr_variant(pVarIn), nDigits, nLeading,
2451 nParens, nGrouping, dwFlags, pbstrOut);
2453 if (!pVarIn || !pbstrOut || nDigits > 9)
2454 return E_INVALIDARG;
2456 *pbstrOut = NULL;
2458 V_VT(&vStr) = VT_EMPTY;
2459 hRet = VariantCopyInd(&vStr, pVarIn);
2461 if (SUCCEEDED(hRet))
2462 hRet = VariantChangeTypeEx(&vStr, &vStr, LOCALE_USER_DEFAULT, 0, VT_BSTR);
2464 if (SUCCEEDED(hRet))
2466 WCHAR buff[256], decimal[8], thousands[8], currency[8];
2467 CURRENCYFMTW numfmt;
2469 if (nDigits < 0)
2470 GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2471 else
2472 numfmt.NumDigits = nDigits;
2474 if (nLeading == -2)
2475 GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2476 else if (nLeading == -1)
2477 numfmt.LeadingZero = 1;
2478 else
2479 numfmt.LeadingZero = 0;
2481 if (nGrouping == -2)
2483 WCHAR grouping[16];
2484 grouping[2] = '\0';
2485 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, grouping,
2486 sizeof(grouping)/sizeof(WCHAR));
2487 numfmt.Grouping = grouping[2] == '2' ? 32 : grouping[0] - '0';
2489 else if (nGrouping == -1)
2490 numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2491 else
2492 numfmt.Grouping = 0; /* 0 = No grouping */
2494 if (nParens == -2)
2495 GETLOCALENUMBER(LOCALE_INEGCURR, NegativeOrder);
2496 else if (nParens == -1)
2497 numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2498 else
2499 numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2501 GETLOCALENUMBER(LOCALE_ICURRENCY, PositiveOrder);
2503 numfmt.lpDecimalSep = decimal;
2504 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal,
2505 sizeof(decimal)/sizeof(WCHAR));
2506 numfmt.lpThousandSep = thousands;
2507 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, thousands,
2508 sizeof(thousands)/sizeof(WCHAR));
2509 numfmt.lpCurrencySymbol = currency;
2510 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, currency,
2511 sizeof(currency)/sizeof(WCHAR));
2513 /* use NLS as per VarFormatNumber() */
2514 if (GetCurrencyFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
2515 buff, sizeof(buff)/sizeof(WCHAR)))
2517 *pbstrOut = SysAllocString(buff);
2518 if (!*pbstrOut)
2519 hRet = E_OUTOFMEMORY;
2521 else
2522 hRet = DISP_E_TYPEMISMATCH;
2524 SysFreeString(V_BSTR(&vStr));
2526 return hRet;
2529 /**********************************************************************
2530 * VarMonthName [OLEAUT32.129]
2532 * Print the specified month as localized name.
2534 * PARAMS
2535 * iMonth [I] month number 1..12
2536 * fAbbrev [I] 0 - full name, !0 - abbreviated name
2537 * dwFlags [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
2538 * pbstrOut [O] Destination for month name
2540 * RETURNS
2541 * Success: S_OK. pbstrOut contains the name.
2542 * Failure: E_INVALIDARG, if any parameter is invalid.
2543 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2545 HRESULT WINAPI VarMonthName(INT iMonth, INT fAbbrev, ULONG dwFlags, BSTR *pbstrOut)
2547 DWORD localeValue;
2548 INT size;
2550 if ((iMonth < 1) || (iMonth > 12))
2551 return E_INVALIDARG;
2553 if (dwFlags)
2554 FIXME("Does not support dwFlags 0x%x, ignoring.\n", dwFlags);
2556 if (fAbbrev)
2557 localeValue = LOCALE_SABBREVMONTHNAME1 + iMonth - 1;
2558 else
2559 localeValue = LOCALE_SMONTHNAME1 + iMonth - 1;
2561 size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, NULL, 0);
2562 if (!size) {
2563 ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2564 return HRESULT_FROM_WIN32(GetLastError());
2566 *pbstrOut = SysAllocStringLen(NULL,size - 1);
2567 if (!*pbstrOut)
2568 return E_OUTOFMEMORY;
2569 size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, *pbstrOut, size);
2570 if (!size) {
2571 ERR("GetLocaleInfo of 0x%x failed in 2nd stage?!\n", localeValue);
2572 SysFreeString(*pbstrOut);
2573 return HRESULT_FROM_WIN32(GetLastError());
2575 return S_OK;
2578 /**********************************************************************
2579 * VarWeekdayName [OLEAUT32.129]
2581 * Print the specified weekday as localized name.
2583 * PARAMS
2584 * iWeekday [I] day of week, 1..7, 1="the first day of the week"
2585 * fAbbrev [I] 0 - full name, !0 - abbreviated name
2586 * iFirstDay [I] first day of week,
2587 * 0=system default, 1=Sunday, 2=Monday, .. (contrary to MSDN)
2588 * dwFlags [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
2589 * pbstrOut [O] Destination for weekday name.
2591 * RETURNS
2592 * Success: S_OK, pbstrOut contains the name.
2593 * Failure: E_INVALIDARG, if any parameter is invalid.
2594 * E_OUTOFMEMORY, if enough memory cannot be allocated.
2596 HRESULT WINAPI VarWeekdayName(INT iWeekday, INT fAbbrev, INT iFirstDay,
2597 ULONG dwFlags, BSTR *pbstrOut)
2599 DWORD localeValue;
2600 INT size;
2602 /* Windows XP oleaut32.dll doesn't allow iWekday==0, contrary to MSDN */
2603 if (iWeekday < 1 || iWeekday > 7)
2604 return E_INVALIDARG;
2605 if (iFirstDay < 0 || iFirstDay > 7)
2606 return E_INVALIDARG;
2607 if (!pbstrOut)
2608 return E_INVALIDARG;
2610 if (dwFlags)
2611 FIXME("Does not support dwFlags 0x%x, ignoring.\n", dwFlags);
2613 /* If we have to use the default firstDay, find which one it is */
2614 if (iFirstDay == 0) {
2615 DWORD firstDay;
2616 localeValue = LOCALE_RETURN_NUMBER | LOCALE_IFIRSTDAYOFWEEK;
2617 size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue,
2618 (LPWSTR)&firstDay, sizeof(firstDay) / sizeof(WCHAR));
2619 if (!size) {
2620 ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2621 return HRESULT_FROM_WIN32(GetLastError());
2623 iFirstDay = firstDay + 2;
2626 /* Determine what we need to return */
2627 localeValue = fAbbrev ? LOCALE_SABBREVDAYNAME1 : LOCALE_SDAYNAME1;
2628 localeValue += (7 + iWeekday - 1 + iFirstDay - 2) % 7;
2630 /* Determine the size of the data, allocate memory and retrieve the data */
2631 size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue, NULL, 0);
2632 if (!size) {
2633 ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2634 return HRESULT_FROM_WIN32(GetLastError());
2636 *pbstrOut = SysAllocStringLen(NULL, size - 1);
2637 if (!*pbstrOut)
2638 return E_OUTOFMEMORY;
2639 size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue, *pbstrOut, size);
2640 if (!size) {
2641 ERR("GetLocaleInfo 0x%x failed in 2nd stage?!\n", localeValue);
2642 SysFreeString(*pbstrOut);
2643 return HRESULT_FROM_WIN32(GetLastError());
2645 return S_OK;