2 * Variant formatting functions
4 * Copyright 2003 Jon Griffiths
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.
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.
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
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.
38 #define NONAMELESSUNION
39 #define NONAMELESSSTRUCT
43 #include "wine/debug.h"
44 #include "wine/unicode.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(ole);
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.
54 #define LCID_US MAKELCID(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),SORT_DEFAULT)
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' };
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_]); \
70 /******************************************************************************
71 * Variant-Formats {OLEAUT32}
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.
78 * The following named formats are defined:
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
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.
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
118 *| Date 1 Use the same format for all dates
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().
125 * VarTokenizeFormatString(), VarFormatFromTokens(), VarFormat(),
126 * VarFormatDateTime(), VarFormatNumber(), VarFormatCurrency().
129 /******************************************************************************
130 * VarFormat-Strings {OLEAUT32}
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.
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.
145 * In user-defined string formats, the following tokens are recognised:
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.
157 * Common format definitions
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
167 #define FMT_TO_STRING 0x0 /* If header->size == this, act like VB's Str() fn */
169 typedef struct tagFMT_SHORT_HEADER
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 */
176 typedef struct tagFMT_HEADER
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 */
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])
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) */
196 typedef struct tagFMT_STRING_HEADER
198 BYTE flags; /* LT, GT, RTL */
201 BYTE copy_chars; /* Number of chars to be copied */
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 */
214 typedef struct tagFMT_NUMBER_HEADER
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 */
226 typedef struct tagFMT_DATE_HEADER
236 * Format token values
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 */
293 #define FMT_WINE_HOURS_12 0x81 /* Hours using 12 hour clockhourCopy len chars or skip if no char */
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] =
299 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
301 FMT_DATE_GENERAL,FMT_GEN_END
304 static const WCHAR szShortDate[] = { 'S','h','o','r','t',' ','D','a','t','e','\0' };
305 static const BYTE fmtShortDate[0x0a] =
307 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
309 FMT_DATE_SHORT,FMT_GEN_END
312 static const WCHAR szMediumDate[] = { 'M','e','d','i','u','m',' ','D','a','t','e','\0' };
313 static const BYTE fmtMediumDate[0x0a] =
315 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
317 FMT_DATE_MEDIUM,FMT_GEN_END
320 static const WCHAR szLongDate[] = { 'L','o','n','g',' ','D','a','t','e','\0' };
321 static const BYTE fmtLongDate[0x0a] =
323 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
325 FMT_DATE_LONG,FMT_GEN_END
328 static const WCHAR szShortTime[] = { 'S','h','o','r','t',' ','T','i','m','e','\0' };
329 static const BYTE fmtShortTime[0x0c] =
331 0x0c,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
333 FMT_DATE_TIME_UNK2,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,FMT_GEN_END
336 static const WCHAR szMediumTime[] = { 'M','e','d','i','u','m',' ','T','i','m','e','\0' };
337 static const BYTE fmtMediumTime[0x11] =
339 0x11,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
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
345 static const WCHAR szLongTime[] = { 'L','o','n','g',' ','T','i','m','e','\0' };
346 static const BYTE fmtLongTime[0x0d] =
348 0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
350 FMT_DATE_TIME_SYS,FMT_GEN_END
353 static const WCHAR szTrueFalse[] = { 'T','r','u','e','/','F','a','l','s','e','\0' };
354 static const BYTE fmtTrueFalse[0x0d] =
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
361 static const WCHAR szYesNo[] = { 'Y','e','s','/','N','o','\0' };
362 static const BYTE fmtYesNo[0x0d] =
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
369 static const WCHAR szOnOff[] = { 'O','n','/','O','f','f','\0' };
370 static const BYTE fmtOnOff[0x0d] =
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
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)] =
380 sizeof(FMT_HEADER),FMT_TYPE_GENERAL,sizeof(FMT_HEADER),0x0,0x0,0x0
383 static const WCHAR szCurrency[] = { 'C','u','r','r','e','n','c','y','\0' };
384 static const BYTE fmtCurrency[0x26] =
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,
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',
398 static const WCHAR szFixed[] = { 'F','i','x','e','d','\0' };
399 static const BYTE fmtFixed[0x11] =
401 0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
403 FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
406 static const WCHAR szStandard[] = { 'S','t','a','n','d','a','r','d','\0' };
407 static const BYTE fmtStandard[0x11] =
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
414 static const WCHAR szPercent[] = { 'P','e','r','c','e','n','t','\0' };
415 static const BYTE fmtPercent[0x15] =
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
423 static const WCHAR szScientific[] = { 'S','c','i','e','n','t','i','f','i','c','\0' };
424 static const BYTE fmtScientific[0x13] =
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
431 typedef struct tagNAMED_FORMAT
437 /* Format name to tokenised format. Must be kept sorted by name */
438 static const NAMED_FORMAT VARIANT_NamedFormats[] =
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 }
457 typedef const NAMED_FORMAT *LPCNAMED_FORMAT;
459 static int FormatCompareFn(const void *l, const void *r)
461 return strcmpiW(((LPCNAMED_FORMAT)l)->name, ((LPCNAMED_FORMAT)r)->name);
464 static inline const BYTE *VARIANT_GetNamedFormat(LPCWSTR lpszFormat)
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;
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)
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)
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 */
488 /**********************************************************************
489 * VarTokenizeFormatString [OLEAUT32.140]
491 * Convert a format string into tokenised form.
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
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.
508 * Valid values for the nFirstWeek parameter are:
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().
517 HRESULT WINAPI VarTokenizeFormatString(LPOLESTR lpszFormat, LPBYTE rgbTok,
518 int cbTok, int nFirstDay, int nFirstWeek,
519 LCID lcid, int *pcbActual)
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;
536 LPCWSTR pFormat = lpszFormat;
538 TRACE("(%s,%p,%d,%d,%d,0x%08lx,%p)\n", debugstr_w(lpszFormat), rgbTok, cbTok,
539 nFirstDay, nFirstWeek, lcid, pcbActual);
542 nFirstDay < 0 || nFirstDay > 7 || nFirstWeek < 0 || nFirstWeek > 3)
545 if (!lpszFormat || !*lpszFormat)
547 /* An empty string means 'general format' */
548 NEED_SPACE(sizeof(BYTE));
549 *rgbTok = FMT_TO_STRING;
551 *pcbActual = FMT_TO_STRING;
556 cbTok = 255; /* Ensure we error instead of wrapping */
559 namedFmt = VARIANT_GetNamedFormat(lpszFormat);
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 */
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));
574 header->starts[fmt_number] = sizeof(FMT_HEADER);
584 while (*pFormat == ';')
587 if (++fmt_number > 3)
588 return E_INVALIDARG; /* too many formats */
593 TRACE("New header\n");
594 NEED_SPACE(sizeof(BYTE) + sizeof(FMT_STRING_HEADER));
595 *pOut++ = FMT_GEN_END;
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);
607 else if (*pFormat == '\\')
609 /* Escaped character */
612 NEED_SPACE(3 * sizeof(BYTE));
614 *pOut++ = FMT_GEN_COPY;
615 *pOut++ = pFormat - lpszFormat;
617 fmt_state |= FMT_STATE_OPEN_COPY;
621 fmt_state &= ~FMT_STATE_OPEN_COPY;
624 else if (*pFormat == '"')
627 * Note: Native encodes "" as a copy of length zero. Thats just dumb, so
628 * here we avoid encoding anything in this case.
632 else if (pFormat[1] == '"')
638 LPCWSTR start = ++pFormat;
639 while (*pFormat && *pFormat != '"')
641 NEED_SPACE(3 * sizeof(BYTE));
642 *pOut++ = FMT_GEN_COPY;
643 *pOut++ = start - lpszFormat;
644 *pOut++ = pFormat - start;
647 TRACE("Quoted string pos %d, len %d\n", pOut[-2], pOut[-1]);
649 fmt_state &= ~FMT_STATE_OPEN_COPY;
655 else if (*pFormat == '0' && COULD_BE(FMT_TYPE_NUMBER))
657 /* Number formats: Digit from number or '0' if no digits
658 * Other formats: Literal
659 * Types the format if found
661 header->type = FMT_TYPE_NUMBER;
662 NEED_SPACE(2 * sizeof(BYTE));
663 *pOut++ = FMT_NUM_COPY_ZERO;
665 while (*pFormat == '0')
670 if (fmt_state & FMT_STATE_WROTE_DECIMAL)
671 num_header->fractional += *pOut;
673 num_header->whole += *pOut;
674 TRACE("%d 0's\n", *pOut);
676 fmt_state &= ~FMT_STATE_OPEN_COPY;
678 else if (*pFormat == '#' && COULD_BE(FMT_TYPE_NUMBER))
680 /* Number formats: Digit from number or blank if no digits
681 * Other formats: Literal
682 * Types the format if found
684 header->type = FMT_TYPE_NUMBER;
685 NEED_SPACE(2 * sizeof(BYTE));
686 *pOut++ = FMT_NUM_COPY_SKIP;
688 while (*pFormat == '#')
693 if (fmt_state & FMT_STATE_WROTE_DECIMAL)
694 num_header->fractional += *pOut;
696 num_header->whole += *pOut;
697 TRACE("%d #'s\n", *pOut);
699 fmt_state &= ~FMT_STATE_OPEN_COPY;
701 else if (*pFormat == '.' && COULD_BE(FMT_TYPE_NUMBER) &&
702 !(fmt_state & FMT_STATE_WROTE_DECIMAL))
704 /* Number formats: Decimal seperator when 1st seen, literal thereafter
705 * Other formats: Literal
706 * Types the format if found
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;
714 TRACE("decimal sep\n");
716 /* FIXME: E+ E- e+ e- => Exponent */
717 /* FIXME: %% => Divide by 1000 */
718 else if (*pFormat == ',' && header->type == FMT_TYPE_NUMBER)
720 /* Number formats: Use the thousands seperator
721 * Other formats: Literal
723 num_header->flags |= FMT_FLAG_THOUSANDS;
725 fmt_state &= ~FMT_STATE_OPEN_COPY;
726 TRACE("thousands sep\n");
732 else if (*pFormat == '/' && COULD_BE(FMT_TYPE_DATE))
734 /* Date formats: Date seperator
735 * Other formats: Literal
736 * Types the format if found
738 header->type = FMT_TYPE_DATE;
739 NEED_SPACE(sizeof(BYTE));
740 *pOut++ = FMT_DATE_DATE_SEP;
742 fmt_state &= ~FMT_STATE_OPEN_COPY;
745 else if (*pFormat == ':' && COULD_BE(FMT_TYPE_DATE))
747 /* Date formats: Time seperator
748 * Other formats: Literal
749 * Types the format if found
751 header->type = FMT_TYPE_DATE;
752 NEED_SPACE(sizeof(BYTE));
753 *pOut++ = FMT_DATE_TIME_SEP;
755 fmt_state &= ~FMT_STATE_OPEN_COPY;
758 else if ((*pFormat == 'a' || *pFormat == 'A') &&
759 !strncmpiW(pFormat, szAMPM, sizeof(szAMPM)/sizeof(WCHAR)))
761 /* Date formats: System AM/PM designation
762 * Other formats: Literal
763 * Types the format if found
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;
771 *pOut++ = FMT_DATE_AMPM_SYS1;
773 *pLastHours = *pLastHours + 2;
776 else if (*pFormat == 'a' && pFormat[1] == '/' &&
777 (pFormat[2] == 'p' || pFormat[2] == 'P'))
779 /* Date formats: lowercase a or p designation
780 * Other formats: Literal
781 * Types the format if found
783 header->type = FMT_TYPE_DATE;
784 NEED_SPACE(sizeof(BYTE));
786 *pOut++ = FMT_DATE_A_LOWER;
788 *pLastHours = *pLastHours + 2;
791 else if (*pFormat == 'A' && pFormat[1] == '/' &&
792 (pFormat[2] == 'p' || pFormat[2] == 'P'))
794 /* Date formats: Uppercase a or p designation
795 * Other formats: Literal
796 * Types the format if found
798 header->type = FMT_TYPE_DATE;
799 NEED_SPACE(sizeof(BYTE));
801 *pOut++ = FMT_DATE_A_UPPER;
803 *pLastHours = *pLastHours + 2;
806 else if (*pFormat == 'a' &&
807 !strncmpW(pFormat, szamSlashpm, sizeof(szamSlashpm)/sizeof(WCHAR)))
809 /* Date formats: lowercase AM or PM designation
810 * Other formats: Literal
811 * Types the format if found
813 header->type = FMT_TYPE_DATE;
814 NEED_SPACE(sizeof(BYTE));
815 pFormat += sizeof(szamSlashpm)/sizeof(WCHAR);
816 *pOut++ = FMT_DATE_AMPM_LOWER;
818 *pLastHours = *pLastHours + 2;
821 else if (*pFormat == 'A' &&
822 !strncmpW(pFormat, szAMSlashPM, sizeof(szAMSlashPM)/sizeof(WCHAR)))
824 /* Date formats: Uppercase AM or PM designation
825 * Other formats: Literal
826 * Types the format if found
828 header->type = FMT_TYPE_DATE;
829 NEED_SPACE(sizeof(BYTE));
830 pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
831 *pOut++ = FMT_DATE_AMPM_UPPER;
834 else if (*pFormat == 'c' || *pFormat == 'C')
836 /* Date formats: General date format
837 * Other formats: Literal
838 * Types the format if found
840 header->type = FMT_TYPE_DATE;
841 NEED_SPACE(sizeof(BYTE));
842 pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
843 *pOut++ = FMT_DATE_GENERAL;
846 else if ((*pFormat == 'd' || *pFormat == 'D') && COULD_BE(FMT_TYPE_DATE))
848 /* Date formats: Day specifier
849 * Other formats: Literal
850 * Types the format if found
853 header->type = FMT_TYPE_DATE;
854 while ((*pFormat == 'd' || *pFormat == 'D') && count < 6)
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.
865 fmt_state &= ~FMT_STATE_SEEN_HOURS;
866 TRACE("%d d's\n", count + 1);
868 else if ((*pFormat == 'h' || *pFormat == 'H') && COULD_BE(FMT_TYPE_DATE))
870 /* Date formats: Hour specifier
871 * Other formats: Literal
872 * Types the format if found
874 header->type = FMT_TYPE_DATE;
875 NEED_SPACE(sizeof(BYTE));
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.
881 if (*pFormat == 'h' || *pFormat == 'H')
884 *pOut++ = FMT_DATE_HOUR_0;
889 *pOut++ = FMT_DATE_HOUR;
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.
896 fmt_state |= FMT_STATE_SEEN_HOURS;
898 else if ((*pFormat == 'm' || *pFormat == 'M') && COULD_BE(FMT_TYPE_DATE))
900 /* Date formats: Month specifier (or Minute specifier, after hour specifier)
901 * Other formats: Literal
902 * Types the format if found
905 header->type = FMT_TYPE_DATE;
906 while ((*pFormat == 'm' || *pFormat == 'M') && count < 4)
911 NEED_SPACE(sizeof(BYTE));
912 if (count <= 1 && fmt_state & FMT_STATE_SEEN_HOURS &&
913 !(fmt_state & FMT_STATE_WROTE_MINUTES))
915 /* We have seen an hours specifier and not yet written a minutes
916 * specifier. Write this as minutes and thereafter as months.
918 *pOut++ = count == 1 ? FMT_DATE_MIN_0 : FMT_DATE_MIN;
919 fmt_state |= FMT_STATE_WROTE_MINUTES; /* Hereafter write months */
922 *pOut++ = FMT_DATE_MON + count; /* Months */
923 fmt_state &= ~FMT_STATE_OPEN_COPY;
924 TRACE("%d m's\n", count + 1);
926 else if ((*pFormat == 'n' || *pFormat == 'N') && COULD_BE(FMT_TYPE_DATE))
928 /* Date formats: Minute specifier
929 * Other formats: Literal
930 * Types the format if found
932 header->type = FMT_TYPE_DATE;
933 NEED_SPACE(sizeof(BYTE));
935 if (*pFormat == 'n' || *pFormat == 'N')
938 *pOut++ = FMT_DATE_MIN_0;
943 *pOut++ = FMT_DATE_MIN;
946 fmt_state &= ~FMT_STATE_OPEN_COPY;
948 else if ((*pFormat == 'q' || *pFormat == 'q') && COULD_BE(FMT_TYPE_DATE))
950 /* Date formats: Quarter specifier
951 * Other formats: Literal
952 * Types the format if found
954 header->type = FMT_TYPE_DATE;
955 NEED_SPACE(sizeof(BYTE));
956 *pOut++ = FMT_DATE_QUARTER;
958 fmt_state &= ~FMT_STATE_OPEN_COPY;
961 else if ((*pFormat == 's' || *pFormat == 'S') && COULD_BE(FMT_TYPE_DATE))
963 /* Date formats: Second specifier
964 * Other formats: Literal
965 * Types the format if found
967 header->type = FMT_TYPE_DATE;
968 NEED_SPACE(sizeof(BYTE));
970 if (*pFormat == 's' || *pFormat == 'S')
973 *pOut++ = FMT_DATE_SEC_0;
978 *pOut++ = FMT_DATE_SEC;
981 fmt_state &= ~FMT_STATE_OPEN_COPY;
983 else if ((*pFormat == 't' || *pFormat == 'T') &&
984 !strncmpiW(pFormat, szTTTTT, sizeof(szTTTTT)/sizeof(WCHAR)))
986 /* Date formats: System time specifier
987 * Other formats: Literal
988 * Types the format if found
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;
996 else if ((*pFormat == 'w' || *pFormat == 'W') && COULD_BE(FMT_TYPE_DATE))
998 /* Date formats: Week of the year/Day of the week
999 * Other formats: Literal
1000 * Types the format if found
1002 header->type = FMT_TYPE_DATE;
1004 if (*pFormat == 'w' || *pFormat == 'W')
1006 NEED_SPACE(3 * sizeof(BYTE));
1008 *pOut++ = FMT_DATE_WEEK_YEAR;
1009 *pOut++ = nFirstDay;
1010 *pOut++ = nFirstWeek;
1015 NEED_SPACE(2 * sizeof(BYTE));
1016 *pOut++ = FMT_DATE_DAY_WEEK;
1017 *pOut++ = nFirstDay;
1021 fmt_state &= ~FMT_STATE_OPEN_COPY;
1023 else if ((*pFormat == 'y' || *pFormat == 'Y') && COULD_BE(FMT_TYPE_DATE))
1025 /* Date formats: Day of year/Year specifier
1026 * Other formats: Literal
1027 * Types the format if found
1030 header->type = FMT_TYPE_DATE;
1031 while ((*pFormat == 'y' || *pFormat == 'Y') && count < 4)
1038 count--; /* 'yyy' has no meaning, despite what MSDN says */
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);
1050 else if (*pFormat == '@' && COULD_BE(FMT_TYPE_STRING))
1052 /* String formats: Character from string or space if no char
1053 * Other formats: Literal
1054 * Types the format if found
1056 header->type = FMT_TYPE_STRING;
1057 NEED_SPACE(2 * sizeof(BYTE));
1058 *pOut++ = FMT_STR_COPY_SPACE;
1060 while (*pFormat == '@')
1063 str_header->copy_chars++;
1066 TRACE("%d @'s\n", *pOut);
1068 fmt_state &= ~FMT_STATE_OPEN_COPY;
1070 else if (*pFormat == '&' && COULD_BE(FMT_TYPE_STRING))
1072 /* String formats: Character from string or skip if no char
1073 * Other formats: Literal
1074 * Types the format if found
1076 header->type = FMT_TYPE_STRING;
1077 NEED_SPACE(2 * sizeof(BYTE));
1078 *pOut++ = FMT_STR_COPY_SKIP;
1080 while (*pFormat == '&')
1083 str_header->copy_chars++;
1086 TRACE("%d &'s\n", *pOut);
1088 fmt_state &= ~FMT_STATE_OPEN_COPY;
1090 else if ((*pFormat == '<' || *pFormat == '>') && COULD_BE(FMT_TYPE_STRING))
1092 /* String formats: Use upper/lower case
1093 * Other formats: Literal
1094 * Types the format if found
1096 header->type = FMT_TYPE_STRING;
1097 if (*pFormat == '<')
1098 str_header->flags |= FMT_FLAG_LT;
1100 str_header->flags |= FMT_FLAG_GT;
1101 TRACE("to %s case\n", *pFormat == '<' ? "lower" : "upper");
1103 fmt_state &= ~FMT_STATE_OPEN_COPY;
1105 else if (*pFormat == '!' && COULD_BE(FMT_TYPE_STRING))
1107 /* String formats: Copy right to left
1108 * Other formats: Literal
1109 * Types the format if found
1111 header->type = FMT_TYPE_STRING;
1112 str_header->flags |= FMT_FLAG_RTL;
1114 fmt_state &= ~FMT_STATE_OPEN_COPY;
1115 TRACE("copy right-to-left\n");
1121 /* FIXME: [ seems to be ignored */
1124 if (*pFormat == '%' && header->type == FMT_TYPE_NUMBER)
1126 /* Number formats: Percentage indicator, also a literal
1127 * Other formats: Literal
1128 * Doesn't type the format
1130 num_header->flags |= FMT_FLAG_PERCENT;
1133 if (fmt_state & FMT_STATE_OPEN_COPY)
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]);
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;
1146 fmt_state |= FMT_STATE_OPEN_COPY;
1152 *pOut++ = FMT_GEN_END;
1154 header->size = pOut - rgbTok;
1156 *pcbActual = header->size;
1161 /* Number formatting state flags */
1162 #define NUM_WROTE_DEC 0x01 /* Written the decimal seperator */
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)
1171 int wholeNumberDigits, fractionalDigits, divisor10 = 0, multiplier10 = 0;
1172 WCHAR buff[256], *pBuff = buff;
1173 VARIANT vString, vBool;
1175 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1176 FMT_NUMBER_HEADER *numHeader;
1177 const BYTE* pToken = NULL;
1178 HRESULT hRes = S_OK;
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,
1184 V_VT(&vString) = VT_EMPTY;
1185 V_VT(&vBool) = VT_BOOL;
1187 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1189 wholeNumberDigits = fractionalDigits = 0;
1190 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNull(header));
1191 V_BOOL(&vBool) = VARIANT_FALSE;
1195 /* Get a number string from pVarIn, and parse it */
1196 hRes = VariantChangeTypeEx(&vString, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1200 np.cDig = sizeof(rgbDig);
1201 np.dwInFlags = NUMPRS_STD;
1202 hRes = VarParseNumFromStr(V_BSTR(&vString), LCID_US, 0, &np, rgbDig);
1208 if (-np.nPwr10 >= np.cDig)
1210 /* A real number < +/- 1.0 e.g. 0.1024 or 0.01024 */
1211 wholeNumberDigits = 0;
1212 fractionalDigits = np.cDig;
1213 divisor10 = -np.nPwr10;
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;
1223 else if (np.nPwr10 == 0)
1225 /* An exactly represented whole number e.g. 1024 */
1226 wholeNumberDigits = np.cDig;
1227 fractionalDigits = 0;
1229 else /* np.nPwr10 > 0 */
1231 /* A whole number followed by nPwr10 0's e.g. 102400 */
1232 wholeNumberDigits = np.cDig;
1233 fractionalDigits = 0;
1234 multiplier10 = np.nPwr10;
1237 /* Figure out which format to use */
1238 if (np.dwOutFlags & NUMPRS_NEG)
1240 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNegative(header));
1241 V_BOOL(&vBool) = VARIANT_TRUE;
1243 else if (wholeNumberDigits == 1 && !fractionalDigits && !multiplier10 &&
1244 !divisor10 && rgbDig[0] == 0)
1246 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetZero(header));
1247 V_BOOL(&vBool) = VARIANT_FALSE;
1251 numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetPositive(header));
1252 V_BOOL(&vBool) = VARIANT_TRUE;
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);
1259 if (numHeader->flags & FMT_FLAG_PERCENT &&
1260 !(wholeNumberDigits == 1 && !fractionalDigits && !multiplier10 &&
1261 !divisor10 && rgbDig[0] == 0))
1263 /* *100 for %'s. Try to 'steal' fractional digits if we can */
1264 TRACE("Fraction - multiply by 100\n");
1265 if (!fractionalDigits)
1270 wholeNumberDigits++;
1271 if (!fractionalDigits)
1276 wholeNumberDigits++;
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);
1285 pToken = (const BYTE*)numHeader + sizeof(FMT_NUMBER_HEADER);
1287 while (SUCCEEDED(hRes) && *pToken != FMT_GEN_END)
1289 WCHAR defaultChar = '?';
1290 DWORD boolFlag, localeValue = 0;
1292 if (pToken - rgbTok > header->size)
1294 ERR("Ran off the end of the format!\n");
1295 hRes = E_INVALIDARG;
1296 goto VARIANT_FormatNumber_Exit;
1302 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1303 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1308 case FMT_GEN_INLINE:
1310 TRACE("copy %s\n", debugstr_a(pToken));
1312 *pBuff++ = *pToken++;
1315 case FMT_NUM_YES_NO:
1316 boolFlag = VAR_BOOLYESNO;
1317 goto VARIANT_FormatNumber_Bool;
1320 case FMT_NUM_ON_OFF:
1321 boolFlag = VAR_BOOLONOFF;
1322 goto VARIANT_FormatNumber_Bool;
1325 case FMT_NUM_TRUE_FALSE:
1326 boolFlag = VAR_LOCALBOOL;
1328 VARIANT_FormatNumber_Bool:
1330 BSTR boolStr = NULL;
1332 if (pToken[1] != FMT_GEN_END)
1334 ERR("Boolean token not at end of format!\n");
1335 hRes = E_INVALIDARG;
1336 goto VARIANT_FormatNumber_Exit;
1338 hRes = VarBstrFromBool(V_BOOL(&vBool), lcid, boolFlag, &boolStr);
1339 if (SUCCEEDED(hRes))
1341 strcpyW(pBuff, boolStr);
1342 SysFreeString(boolStr);
1349 case FMT_NUM_DECIMAL:
1350 TRACE("write decimal seperator\n");
1351 localeValue = LOCALE_SDECIMAL;
1353 dwState |= NUM_WROTE_DEC;
1356 case FMT_NUM_CURRENCY:
1357 TRACE("write currency symbol\n");
1358 localeValue = LOCALE_SCURRENCY;
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)
1373 sprintfW(pBuff, szPercentZeroStar_d, pToken[1], divisor10);
1377 if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_POS_U)
1379 sprintfW(pBuff, szPercentZeroStar_d, pToken[1], multiplier10);
1386 case FMT_NUM_COPY_SKIP:
1387 if (dwState & NUM_WROTE_DEC)
1391 TRACE("write %d fractional digits or skip\n", pToken[1]);
1393 for (count = 0; count < fractionalDigits; count++)
1394 pBuff[count] = rgbDig[wholeNumberDigits + count];
1395 pBuff += fractionalDigits;
1401 TRACE("write %d digits or skip\n", pToken[1]);
1403 if (wholeNumberDigits > 1 || rgbDig[0] > 0)
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 */
1416 case FMT_NUM_COPY_ZERO:
1417 if (dwState & NUM_WROTE_DEC)
1421 TRACE("write %d fractional digits or 0's\n", pToken[1]);
1423 for (count = 0; count < fractionalDigits; count++)
1424 pBuff[count] = rgbDig[wholeNumberDigits + count];
1425 pBuff += fractionalDigits;
1426 if (pToken[1] > fractionalDigits)
1428 count = pToken[1] - fractionalDigits;
1430 *pBuff++ = '0'; /* Write trailing zeros for missing digits */
1437 TRACE("write %d digits or 0's\n", pToken[1]);
1439 if (pToken[1] > (wholeNumberDigits + multiplier10))
1441 count = pToken[1] - (wholeNumberDigits + multiplier10);
1442 TRACE("write %d leading zeros\n", count);
1444 *pBuff++ = '0'; /* Write leading zeros for missing digits */
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 */
1457 ERR("Unknown token 0x%02x!\n", *pToken);
1458 hRes = E_INVALIDARG;
1459 goto VARIANT_FormatNumber_Exit;
1464 if (GetLocaleInfoW(lcid, localeValue, pBuff,
1465 sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1467 TRACE("added %s\n", debugstr_w(pBuff));
1473 TRACE("added %d '%c'\n", defaultChar, defaultChar);
1474 *pBuff++ = defaultChar;
1480 VARIANT_FormatNumber_Exit:
1481 VariantClear(&vString);
1483 TRACE("buff is %s\n", debugstr_w(buff));
1484 if (SUCCEEDED(hRes))
1486 *pbstrOut = SysAllocString(buff);
1488 hRes = E_OUTOFMEMORY;
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)
1498 WCHAR buff[256], *pBuff = buff;
1501 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1502 FMT_DATE_HEADER *dateHeader;
1503 const BYTE* pToken = NULL;
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,
1510 V_VT(&vDate) = VT_EMPTY;
1512 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1514 dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetNegative(header));
1519 USHORT usFlags = dwFlags & VARIANT_CALENDAR_HIJRI ? VAR_CALENDAR_HIJRI : 0;
1521 hRes = VariantChangeTypeEx(&vDate, pVarIn, LCID_US, usFlags, VT_DATE);
1524 dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetPositive(header));
1527 hRes = VarUdateFromDate(V_DATE(&vDate), 0 /* FIXME: flags? */, &udate);
1530 pToken = (const BYTE*)dateHeader + sizeof(FMT_DATE_HEADER);
1532 while (*pToken != FMT_GEN_END)
1534 DWORD dwVal = 0, localeValue = 0, dwFmt = 0;
1535 LPCWSTR szPrintFmt = NULL;
1536 WCHAR defaultChar = '?';
1538 if (pToken - rgbTok > header->size)
1540 ERR("Ran off the end of the format!\n");
1541 hRes = E_INVALIDARG;
1542 goto VARIANT_FormatDate_Exit;
1548 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1549 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
1554 case FMT_DATE_TIME_SEP:
1555 TRACE("time seperator\n");
1556 localeValue = LOCALE_STIME;
1560 case FMT_DATE_DATE_SEP:
1561 TRACE("date seperator\n");
1562 localeValue = LOCALE_SDATE;
1566 case FMT_DATE_GENERAL:
1569 WCHAR *pDate = date;
1570 hRes = VarBstrFromDate(V_DATE(&vDate), lcid, 0, pbstrOut);
1572 goto VARIANT_FormatDate_Exit;
1574 *pBuff++ = *pDate++;
1575 SysFreeString(date);
1579 case FMT_DATE_QUARTER:
1580 if (udate.st.wMonth <= 3)
1582 else if (udate.st.wMonth <= 6)
1584 else if (udate.st.wMonth <= 9)
1590 case FMT_DATE_TIME_SYS:
1592 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1594 WCHAR *pDate = date;
1595 hRes = VarBstrFromDate(V_DATE(&vDate), lcid, VAR_TIMEVALUEONLY, pbstrOut);
1597 goto VARIANT_FormatDate_Exit;
1599 *pBuff++ = *pDate++;
1600 SysFreeString(date);
1605 szPrintFmt = szPercent_d;
1606 dwVal = udate.st.wDay;
1609 case FMT_DATE_DAY_0:
1610 szPrintFmt = szPercentZeroTwo_d;
1611 dwVal = udate.st.wDay;
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;
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;
1628 case FMT_DATE_SHORT:
1629 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1630 dwFmt = LOCALE_SSHORTDATE;
1634 /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
1635 dwFmt = LOCALE_SLONGDATE;
1638 case FMT_DATE_MEDIUM:
1639 FIXME("Medium date treated as long date\n");
1640 dwFmt = LOCALE_SLONGDATE;
1643 case FMT_DATE_DAY_WEEK:
1644 szPrintFmt = szPercent_d;
1646 dwVal = udate.st.wDayOfWeek + 2 - pToken[1];
1649 GetLocaleInfoW(lcid,LOCALE_RETURN_NUMBER|LOCALE_IFIRSTDAYOFWEEK,
1650 (LPWSTR)&dwVal, sizeof(dwVal)/sizeof(WCHAR));
1651 dwVal = udate.st.wDayOfWeek + 1 - dwVal;
1656 case FMT_DATE_WEEK_YEAR:
1657 szPrintFmt = szPercent_d;
1658 dwVal = udate.wDayOfYear / 7 + 1;
1660 FIXME("Ignoring nFirstDay of %d, nFirstWeek of %d\n", pToken[0], pToken[1]);
1664 szPrintFmt = szPercent_d;
1665 dwVal = udate.st.wMonth;
1668 case FMT_DATE_MON_0:
1669 szPrintFmt = szPercentZeroTwo_d;
1670 dwVal = udate.st.wMonth;
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;
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;
1687 case FMT_DATE_YEAR_DOY:
1688 szPrintFmt = szPercent_d;
1689 dwVal = udate.wDayOfYear;
1692 case FMT_DATE_YEAR_0:
1693 szPrintFmt = szPercentZeroTwo_d;
1694 dwVal = udate.st.wYear % 100;
1697 case FMT_DATE_YEAR_LONG:
1698 szPrintFmt = szPercent_d;
1699 dwVal = udate.st.wYear;
1703 szPrintFmt = szPercent_d;
1704 dwVal = udate.st.wMinute;
1707 case FMT_DATE_MIN_0:
1708 szPrintFmt = szPercentZeroTwo_d;
1709 dwVal = udate.st.wMinute;
1713 szPrintFmt = szPercent_d;
1714 dwVal = udate.st.wSecond;
1717 case FMT_DATE_SEC_0:
1718 szPrintFmt = szPercentZeroTwo_d;
1719 dwVal = udate.st.wSecond;
1723 szPrintFmt = szPercent_d;
1724 dwVal = udate.st.wHour;
1727 case FMT_DATE_HOUR_0:
1728 szPrintFmt = szPercentZeroTwo_d;
1729 dwVal = udate.st.wHour;
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;
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;
1742 case FMT_DATE_AMPM_SYS1:
1743 case FMT_DATE_AMPM_SYS2:
1744 localeValue = udate.st.wHour < 12 ? LOCALE_S1159 : LOCALE_S2359;
1748 case FMT_DATE_AMPM_UPPER:
1749 *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1753 case FMT_DATE_A_UPPER:
1754 *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
1757 case FMT_DATE_AMPM_LOWER:
1758 *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1762 case FMT_DATE_A_LOWER:
1763 *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
1767 ERR("Unknown token 0x%02x!\n", *pToken);
1768 hRes = E_INVALIDARG;
1769 goto VARIANT_FormatDate_Exit;
1775 if (GetLocaleInfoW(lcid, localeValue, pBuff,
1776 sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
1778 TRACE("added %s\n", debugstr_w(pBuff));
1784 TRACE("added %d %c\n", defaultChar, defaultChar);
1785 *pBuff++ = defaultChar;
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)))
1796 hRes = E_INVALIDARG;
1797 goto VARIANT_FormatDate_Exit;
1802 else if (szPrintFmt)
1804 sprintfW(pBuff, szPrintFmt, dwVal);
1811 VARIANT_FormatDate_Exit:
1813 TRACE("buff is %s\n", debugstr_w(buff));
1814 if (SUCCEEDED(hRes))
1816 *pbstrOut = SysAllocString(buff);
1818 hRes = E_OUTOFMEMORY;
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)
1828 static const WCHAR szEmpty[] = { '\0' };
1829 WCHAR buff[256], *pBuff = buff;
1831 FMT_HEADER *header = (FMT_HEADER*)rgbTok;
1832 FMT_STRING_HEADER *strHeader;
1833 const BYTE* pToken = NULL;
1836 BOOL bUpper = FALSE;
1837 HRESULT hRes = S_OK;
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,
1843 V_VT(&vStr) = VT_EMPTY;
1845 if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
1847 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1848 V_BSTR(&vStr) = (WCHAR*)szEmpty;
1852 hRes = VariantChangeTypeEx(&vStr, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
1856 if (V_BSTR(pVarIn)[0] == '\0')
1857 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1859 strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetPositive(header));
1861 pSrc = V_BSTR(&vStr);
1862 if ((strHeader->flags & (FMT_FLAG_LT|FMT_FLAG_GT)) == FMT_FLAG_GT)
1864 blanks_first = strHeader->copy_chars - strlenW(pSrc);
1865 pToken = (const BYTE*)strHeader + sizeof(FMT_DATE_HEADER);
1867 while (*pToken != FMT_GEN_END)
1871 if (pToken - rgbTok > header->size)
1873 ERR("Ran off the end of the format!\n");
1874 hRes = E_INVALIDARG;
1875 goto VARIANT_FormatString_Exit;
1881 TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
1882 memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
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)
1892 TRACE("insert %d initial spaces\n", blanks_first);
1893 while (dwCount > 0 && blanks_first > 0)
1900 TRACE("copy %d chars%s\n", dwCount,
1901 *pToken == FMT_STR_COPY_SPACE ? " with space" :"");
1902 while (dwCount > 0 && *pSrc)
1905 *pBuff++ = toupperW(*pSrc);
1907 *pBuff++ = tolowerW(*pSrc);
1911 if (*pToken == FMT_STR_COPY_SPACE && dwCount > 0)
1913 TRACE("insert %d spaces\n", dwCount);
1914 while (dwCount-- > 0)
1921 ERR("Unknown token 0x%02x!\n", *pToken);
1922 hRes = E_INVALIDARG;
1923 goto VARIANT_FormatString_Exit;
1929 VARIANT_FormatString_Exit:
1930 /* Copy out any remaining chars */
1934 *pBuff++ = toupperW(*pSrc);
1936 *pBuff++ = tolowerW(*pSrc);
1939 VariantClear(&vStr);
1941 TRACE("buff is %s\n", debugstr_w(buff));
1942 if (SUCCEEDED(hRes))
1944 *pbstrOut = SysAllocString(buff);
1946 hRes = E_OUTOFMEMORY;
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))
1956 /**********************************************************************
1957 * VarFormatFromTokens [OLEAUT32.139]
1959 HRESULT WINAPI VarFormatFromTokens(LPVARIANT pVarIn, LPOLESTR lpszFormat,
1960 LPBYTE rgbTok, ULONG dwFlags,
1961 BSTR *pbstrOut, LCID lcid)
1963 FMT_SHORT_HEADER *header = (FMT_SHORT_HEADER *)rgbTok;
1967 TRACE("(%p,%s,%p,%lx,%p,0x%08lx)\n", pVarIn, debugstr_w(lpszFormat),
1968 rgbTok, dwFlags, pbstrOut, lcid);
1971 return E_INVALIDARG;
1975 if (!pVarIn || !rgbTok)
1976 return E_INVALIDARG;
1978 if (*rgbTok == FMT_TO_STRING || header->type == FMT_TYPE_GENERAL)
1980 /* According to MSDN, general format acts somewhat like the 'Str'
1981 * function in Visual Basic.
1983 VarFormatFromTokens_AsStr:
1984 V_VT(&vTmp) = VT_EMPTY;
1985 hres = VariantChangeTypeEx(&vTmp, pVarIn, lcid, dwFlags, VT_BSTR);
1986 *pbstrOut = V_BSTR(&vTmp);
1990 if (header->type == FMT_TYPE_NUMBER ||
1991 (header->type == FMT_TYPE_UNKNOWN && ((1 << V_TYPE(pVarIn)) & NUMBER_VTBITS)))
1993 hres = VARIANT_FormatNumber(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
1995 else if (header->type == FMT_TYPE_DATE ||
1996 (header->type == FMT_TYPE_UNKNOWN && V_TYPE(pVarIn) == VT_DATE))
1998 hres = VARIANT_FormatDate(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2000 else if (header->type == FMT_TYPE_STRING || V_TYPE(pVarIn) == VT_BSTR)
2002 hres = VARIANT_FormatString(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
2006 ERR("unrecognised format type 0x%02x\n", header->type);
2007 return E_INVALIDARG;
2009 /* If the coercion failed, still try to create output, unless the
2010 * VAR_FORMAT_NOSUBSTITUTE flag is set.
2012 if ((hres == DISP_E_OVERFLOW || hres == DISP_E_TYPEMISMATCH) &&
2013 !(dwFlags & VAR_FORMAT_NOSUBSTITUTE))
2014 goto VarFormatFromTokens_AsStr;
2020 /**********************************************************************
2021 * VarFormat [OLEAUT32.87]
2023 * Format a variant from a format string.
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.
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.
2040 * - See Variant-Formats for details concerning creating format strings.
2041 * - This function uses LOCALE_USER_DEFAULT when calling VarTokenizeFormatString()
2042 * and VarFormatFromTokens().
2044 HRESULT WINAPI VarFormat(LPVARIANT pVarIn, LPOLESTR lpszFormat,
2045 int nFirstDay, int nFirstWeek, ULONG dwFlags,
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,
2056 return E_INVALIDARG;
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));
2068 /**********************************************************************
2069 * VarFormatDateTime [OLEAUT32.97]
2071 * Format a variant value as a date and/or time.
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.
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.
2086 * This function uses LOCALE_USER_DEFAULT when determining the date format
2087 * characters to use.
2088 * Possible values for the nFormat parameter are:
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
2097 HRESULT WINAPI VarFormatDateTime(LPVARIANT pVarIn, INT nFormat, ULONG dwFlags, BSTR *pbstrOut)
2099 static const WCHAR szEmpty[] = { '\0' };
2100 const BYTE* lpFmt = NULL;
2102 TRACE("(%p->(%s%s),%d,0x%08lx,%p)\n", pVarIn, debugstr_VT(pVarIn),
2103 debugstr_VF(pVarIn), nFormat, dwFlags, pbstrOut);
2105 if (!pVarIn || !pbstrOut || nFormat < 0 || nFormat > 4)
2106 return E_INVALIDARG;
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;
2116 return VarFormatFromTokens(pVarIn, (LPWSTR)szEmpty, (BYTE*)lpFmt, dwFlags,
2117 pbstrOut, LOCALE_USER_DEFAULT);
2120 #define GETLOCALENUMBER(type,field) GetLocaleInfoW(LOCALE_USER_DEFAULT, \
2121 type|LOCALE_RETURN_NUMBER, \
2122 (LPWSTR)&numfmt.field, \
2123 sizeof(numfmt.field)/sizeof(WCHAR))
2125 /**********************************************************************
2126 * VarFormatNumber [OLEAUT32.107]
2128 * Format a variant value as a number.
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.
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.
2146 * This function uses LOCALE_USER_DEFAULT when determining the number format
2147 * characters to use.
2149 HRESULT WINAPI VarFormatNumber(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2150 INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
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);
2158 if (!pVarIn || !pbstrOut || nDigits > 9)
2159 return E_INVALIDARG;
2163 V_VT(&vStr) = VT_EMPTY;
2164 hRet = VariantCopyInd(&vStr, pVarIn);
2166 if (SUCCEEDED(hRet))
2167 hRet = VariantChangeTypeEx(&vStr, &vStr, LOCALE_USER_DEFAULT, 0, VT_BSTR);
2169 if (SUCCEEDED(hRet))
2171 WCHAR buff[256], decimal[8], thousands[8];
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.
2179 GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2181 numfmt.NumDigits = nDigits;
2184 GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2185 else if (nLeading == -1)
2186 numfmt.LeadingZero = 1;
2188 numfmt.LeadingZero = 0;
2190 if (nGrouping == -2)
2194 GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, grouping,
2195 sizeof(grouping)/sizeof(WCHAR));
2196 numfmt.Grouping = grouping[2] == '2' ? 32 : grouping[0] - '0';
2198 else if (nGrouping == -1)
2199 numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2201 numfmt.Grouping = 0; /* 0 = No grouping */
2204 GETLOCALENUMBER(LOCALE_INEGNUMBER, NegativeOrder);
2205 else if (nParens == -1)
2206 numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2208 numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
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));
2217 if (GetNumberFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
2218 buff, sizeof(buff)/sizeof(WCHAR)))
2220 *pbstrOut = SysAllocString(buff);
2222 hRet = E_OUTOFMEMORY;
2225 hRet = DISP_E_TYPEMISMATCH;
2227 SysFreeString(V_BSTR(&vStr));
2232 /**********************************************************************
2233 * VarFormatPercent [OLEAUT32.117]
2235 * Format a variant value as a percentage.
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.
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.
2254 * This function uses LOCALE_USER_DEFAULT when determining the number format
2255 * characters to use.
2257 HRESULT WINAPI VarFormatPercent(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
2258 INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
2260 static const WCHAR szPercent[] = { '%','\0' };
2261 static const WCHAR szPercentBracket[] = { '%',')','\0' };
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,
2270 if (!pVarIn || !pbstrOut || nDigits > 9)
2271 return E_INVALIDARG;
2275 V_VT(&vDbl) = VT_EMPTY;
2276 hRet = VariantCopyInd(&vDbl, pVarIn);
2278 if (SUCCEEDED(hRet))
2280 hRet = VariantChangeTypeEx(&vDbl, &vDbl, LOCALE_USER_DEFAULT, 0, VT_R8);
2282 if (SUCCEEDED(hRet))
2284 if (V_R8(&vDbl) > (R8_MAX / 100.0))
2285 return DISP_E_OVERFLOW;
2287 V_R8(&vDbl) *= 100.0;
2288 hRet = VarFormatNumber(&vDbl, nDigits, nLeading, nParens,
2289 nGrouping, dwFlags, pbstrOut);
2291 if (SUCCEEDED(hRet))
2293 DWORD dwLen = strlenW(*pbstrOut);
2294 BOOL bBracket = (*pbstrOut)[dwLen] == ')' ? TRUE : FALSE;
2297 memcpy(buff, *pbstrOut, dwLen * sizeof(WCHAR));
2298 strcpyW(buff + dwLen, bBracket ? szPercentBracket : szPercent);
2299 SysFreeString(*pbstrOut);
2300 *pbstrOut = SysAllocString(buff);
2302 hRet = E_OUTOFMEMORY;
2309 /**********************************************************************
2310 * VarFormatCurrency [OLEAUT32.127]
2312 * Format a variant value as a currency.
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.
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.
2330 * This function uses LOCALE_USER_DEFAULT when determining the currency format
2331 * characters to use.
2333 HRESULT WINAPI VarFormatCurrency(LPVARIANT pVarIn, INT nDigits, INT nLeading,
2334 INT nParens, INT nGrouping, ULONG dwFlags,
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);
2343 if (!pVarIn || !pbstrOut || nDigits > 9)
2344 return E_INVALIDARG;
2348 V_VT(&vStr) = VT_EMPTY;
2349 hRet = VariantCopyInd(&vStr, pVarIn);
2351 if (SUCCEEDED(hRet))
2352 hRet = VariantChangeTypeEx(&vStr, &vStr, LOCALE_USER_DEFAULT, 0, VT_BSTR);
2354 if (SUCCEEDED(hRet))
2356 WCHAR buff[256], decimal[8], thousands[8], currency[8];
2357 CURRENCYFMTW numfmt;
2360 GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
2362 numfmt.NumDigits = nDigits;
2365 GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
2366 else if (nLeading == -1)
2367 numfmt.LeadingZero = 1;
2369 numfmt.LeadingZero = 0;
2371 if (nGrouping == -2)
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';
2379 else if (nGrouping == -1)
2380 numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
2382 numfmt.Grouping = 0; /* 0 = No grouping */
2385 GETLOCALENUMBER(LOCALE_INEGCURR, NegativeOrder);
2386 else if (nParens == -1)
2387 numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
2389 numfmt.NegativeOrder = 1; /* 1 = "-xxx" */
2391 GETLOCALENUMBER(LOCALE_ICURRENCY, PositiveOrder);
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));
2403 /* use NLS as per VarFormatNumber() */
2404 if (GetCurrencyFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
2405 buff, sizeof(buff)/sizeof(WCHAR)))
2407 *pbstrOut = SysAllocString(buff);
2409 hRet = E_OUTOFMEMORY;
2412 hRet = DISP_E_TYPEMISMATCH;
2414 SysFreeString(V_BSTR(&vStr));