varformat.c 81.1 KB
Newer Older
1 2 3
/*
 * Variant formatting functions
 *
4
 * Copyright 2008 Damjan Jovanovic
5 6 7 8 9 10 11 12 13 14 15 16 17 18
 * Copyright 2003 Jon Griffiths
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * 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
20 21 22 23 24 25 26 27 28 29
 *
 * NOTES
 *  Since the formatting functions aren't properly documented, I used the
 *  Visual Basic documentation as a guide to implementing these functions. This
 *  means that some named or user-defined formats may work slightly differently.
 *  Please submit a test case if you find a difference.
 */

#include "config.h"

30 31
#include <string.h>
#include <stdlib.h>
32 33 34 35 36 37 38 39 40 41
#include <stdarg.h>
#include <stdio.h>

#define NONAMELESSUNION
#define NONAMELESSSTRUCT
#include "windef.h"
#include "winbase.h"
#include "wine/unicode.h"
#include "winerror.h"
#include "variant.h"
42
#include "wine/debug.h"
43

44
WINE_DEFAULT_DEBUG_CHANNEL(variant);
45 46 47 48 49 50 51 52 53 54 55 56 57

/* Make sure internal conversions to strings use the '.','+'/'-' and ','
 * format chars from the US locale. This enables us to parse the created
 * strings to determine the number of decimal places, exponent, etc.
 */
#define LCID_US MAKELCID(MAKELANGID(LANG_ENGLISH,SUBLANG_ENGLISH_US),SORT_DEFAULT)

static const WCHAR szPercent_d[] = { '%','d','\0' };
static const WCHAR szPercentZeroTwo_d[] = { '%','0','2','d','\0' };
static const WCHAR szPercentZeroStar_d[] = { '%','0','*','d','\0' };

#if 0
#define dump_tokens(rgb) do { \
58
  int i_; TRACE("Tokens->{\n"); \
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  for (i_ = 0; i_ < rgb[0]; i_++) \
    TRACE("%s0x%02x", i_?",":"",rgb[i_]); \
  TRACE(" }\n"); \
  } while(0)
#endif

/******************************************************************************
 * Variant-Formats {OLEAUT32}
 *
 * NOTES
 *  When formatting a variant a variety of format strings may be used to generate
 *  different kinds of formatted output. A format string consists of either a named
 *  format, or a user-defined format.
 *
 *  The following named formats are defined:
 *| Name           Description
 *| ----           -----------
 *| General Date   Display Date, and time for non-integer values
 *| Short Date     Short date format as defined by locale settings
 *| Medium Date    Medium date format as defined by locale settings
 *| Long Date      Long date format as defined by locale settings
 *| Short Time     Short Time format as defined by locale settings
 *| Medium Time    Medium time format as defined by locale settings
 *| Long Time      Long time format as defined by locale settings
 *| True/False     Localised text of "True" or "False"
 *| Yes/No         Localised text of "Yes" or "No"
 *| On/Off         Localised text of "On" or "Off"
86
 *| General Number No thousands separator. No decimal points for integers
87 88
 *| Currency       General currency format using localised characters
 *| Fixed          At least one whole and two fractional digits
89 90
 *| Standard       Same as 'Fixed', but including decimal separators
 *| Percent        Multiply by 100 and display a trailing '%' character
91 92 93 94 95 96
 *| Scientific     Display with exponent
 *
 *  User-defined formats consist of a combination of tokens and literal
 *  characters. Literal characters are copied unmodified to the formatted
 *  output at the position they occupy in the format string. Any character
 *  that is not recognised as a token is treated as a literal. A literal can
97
 *  also be specified by preceding it with a backslash character
98 99 100
 *  (e.g. "\L\i\t\e\r\a\l") or enclosing it in double quotes.
 *
 *  A user-defined format can have up to 4 sections, depending on the type of
101
 *  format. The following table lists sections and their meaning:
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
 *| Format Type  Sections Meaning
 *| -----------  -------- -------
 *| Number       1        Use the same format for all numbers
 *| Number       2        Use format 1 for positive and 2 for negative numbers
 *| Number       3        Use format 1 for positive, 2 for zero, and 3
 *|                       for negative numbers.
 *| Number       4        Use format 1 for positive, 2 for zero, 3 for
 *|                       negative, and 4 for null numbers.
 *| String       1        Use the same format for all strings
 *| String       2        Use format 2 for null and empty strings, otherwise
 *|                       use format 1.
 *| Date         1        Use the same format for all dates
 *
 *  The formatting tokens fall into several categories depending on the type
 *  of formatted output. For more information on each type, see
 *  VarFormat-Dates(), VarFormat-Strings() and VarFormat-Numbers().
 *
 *  SEE ALSO
 *  VarTokenizeFormatString(), VarFormatFromTokens(), VarFormat(),
 *  VarFormatDateTime(), VarFormatNumber(), VarFormatCurrency().
 */

/******************************************************************************
 * VarFormat-Strings {OLEAUT32}
 *
 * NOTES
 *  When formatting a variant as a string, it is first converted to a VT_BSTR.
 *  The user-format string defines which characters are copied into which
 *  positions in the output string. Literals may be inserted in the format
 *  string. When creating the formatted string, excess characters in the string
 *  (those not consumed by a token) are appended to the end of the output. If
 *  there are more tokens than characters in the string to format, spaces will
 *  be inserted at the start of the string if the '@' token was used.
 *
 *  By default strings are converted to lowercase, or uppercase if the '>' token
 *  is encountered. This applies to the whole string: it is not possible to
 *  generate a mixed-case output string.
 *
 *  In user-defined string formats, the following tokens are recognised:
 *| Token  Description
 *| -----  -----------
 *| '@'    Copy a char from the source, or a space if no chars are left.
 *| '&'    Copy a char from the source, or write nothing if no chars are left.
 *| '<'    Output the whole string as lower-case (the default).
 *| '>'    Output the whole string as upper-case.
 *| '!'    MSDN indicates that this character should cause right-to-left
 *|        copying, however tests show that it is tokenised but not processed.
 */

/*
 * Common format definitions
 */

155
 /* Format types */
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
#define FMT_TYPE_UNKNOWN 0x0
#define FMT_TYPE_GENERAL 0x1
#define FMT_TYPE_NUMBER  0x2
#define FMT_TYPE_DATE    0x3
#define FMT_TYPE_STRING  0x4

#define FMT_TO_STRING    0x0 /* If header->size == this, act like VB's Str() fn */

typedef struct tagFMT_SHORT_HEADER
{
  BYTE   size;      /* Size of tokenised block (including header), or FMT_TO_STRING */
  BYTE   type;      /* Allowable types (FMT_TYPE_*) */
  BYTE   offset[1]; /* Offset of the first (and only) format section */
} FMT_SHORT_HEADER;

typedef struct tagFMT_HEADER
{
  BYTE   size;      /* Total size of the whole tokenised block (including header) */
  BYTE   type;      /* Allowable types (FMT_TYPE_*) */
  BYTE   starts[4]; /* Offset of each of the 4 format sections, or 0 if none */
} FMT_HEADER;

#define FmtGetPositive(x)  (x->starts[0])
#define FmtGetNegative(x)  (x->starts[1] ? x->starts[1] : x->starts[0])
#define FmtGetZero(x)      (x->starts[2] ? x->starts[2] : x->starts[0])
#define FmtGetNull(x)      (x->starts[3] ? x->starts[3] : x->starts[0])

/*
 * String formats
 */

#define FMT_FLAG_LT  0x1 /* Has '<' (lower case) */
#define FMT_FLAG_GT  0x2 /* Has '>' (upper case) */
#define FMT_FLAG_RTL 0x4 /* Has '!' (Copy right to left) */

typedef struct tagFMT_STRING_HEADER
{
  BYTE   flags;      /* LT, GT, RTL */
  BYTE   unknown1;
  BYTE   unknown2;
  BYTE   copy_chars; /* Number of chars to be copied */
  BYTE   unknown3;
} FMT_STRING_HEADER;

/*
 * Number formats
 */

#define FMT_FLAG_PERCENT   0x1  /* Has '%' (Percentage) */
#define FMT_FLAG_EXPONENT  0x2  /* Has 'e' (Exponent/Scientific notation) */
206
#define FMT_FLAG_THOUSANDS 0x4  /* Has ',' (Standard use of the thousands separator) */
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
#define FMT_FLAG_BOOL      0x20 /* Boolean format */

typedef struct tagFMT_NUMBER_HEADER
{
  BYTE   flags;      /* PERCENT, EXPONENT, THOUSANDS, BOOL */
  BYTE   multiplier; /* Multiplier, 100 for percentages */
  BYTE   divisor;    /* Divisor, 1000 if '%%' was used */
  BYTE   whole;      /* Number of digits before the decimal point */
  BYTE   fractional; /* Number of digits after the decimal point */
} FMT_NUMBER_HEADER;

/*
 * Date Formats
 */
typedef struct tagFMT_DATE_HEADER
{
  BYTE   flags;
  BYTE   unknown1;
  BYTE   unknown2;
  BYTE   unknown3;
  BYTE   unknown4;
} FMT_DATE_HEADER;

/*
 * Format token values
 */
#define FMT_GEN_COPY        0x00 /* \n, "lit" => 0,pos,len: Copy len chars from input+pos */
#define FMT_GEN_INLINE      0x01 /*      => 1,len,[chars]: Copy len chars from token stream */
#define FMT_GEN_END         0x02 /* \0,; => 2: End of the tokenised format */
236 237
#define FMT_DATE_TIME_SEP   0x03 /* Time separator char */
#define FMT_DATE_DATE_SEP   0x04 /* Date separator char */
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
#define FMT_DATE_GENERAL    0x05 /* General format date */
#define FMT_DATE_QUARTER    0x06 /* Quarter of the year from 1-4 */
#define FMT_DATE_TIME_SYS   0x07 /* System long time format */
#define FMT_DATE_DAY        0x08 /* Day with no leading 0 */
#define FMT_DATE_DAY_0      0x09 /* Day with leading 0 */
#define FMT_DATE_DAY_SHORT  0x0A /* Short day name */
#define FMT_DATE_DAY_LONG   0x0B /* Long day name */
#define FMT_DATE_SHORT      0x0C /* Short date format */
#define FMT_DATE_LONG       0x0D /* Long date format */
#define FMT_DATE_MEDIUM     0x0E /* Medium date format */
#define FMT_DATE_DAY_WEEK   0x0F /* First day of the week */
#define FMT_DATE_WEEK_YEAR  0x10 /* First week of the year */
#define FMT_DATE_MON        0x11 /* Month with no leading 0 */
#define FMT_DATE_MON_0      0x12 /* Month with leading 0 */
#define FMT_DATE_MON_SHORT  0x13 /* Short month name */
#define FMT_DATE_MON_LONG   0x14 /* Long month name */
#define FMT_DATE_YEAR_DOY   0x15 /* Day of the year with no leading 0 */
#define FMT_DATE_YEAR_0     0x16 /* 2 digit year with leading 0 */
/* NOTE: token 0x17 is not defined, 'yyy' is not valid */
#define FMT_DATE_YEAR_LONG  0x18 /* 4 digit year */
#define FMT_DATE_MIN        0x1A /* Minutes with no leading 0 */
#define FMT_DATE_MIN_0      0x1B /* Minutes with leading 0 */
#define FMT_DATE_SEC        0x1C /* Seconds with no leading 0 */
#define FMT_DATE_SEC_0      0x1D /* Seconds with leading 0 */
#define FMT_DATE_HOUR       0x1E /* Hours with no leading 0 */
#define FMT_DATE_HOUR_0     0x1F /* Hours with leading 0 */
#define FMT_DATE_HOUR_12    0x20 /* Hours with no leading 0, 12 hour clock */
#define FMT_DATE_HOUR_12_0  0x21 /* Hours with leading 0, 12 hour clock */
#define FMT_DATE_TIME_UNK2  0x23
/* FIXME: probably missing some here */
#define FMT_DATE_AMPM_SYS1  0x2E /* AM/PM as defined by system settings */
#define FMT_DATE_AMPM_UPPER 0x2F /* Upper-case AM or PM */
#define FMT_DATE_A_UPPER    0x30 /* Upper-case A or P */
#define FMT_DATE_AMPM_SYS2  0x31 /* AM/PM as defined by system settings */
#define FMT_DATE_AMPM_LOWER 0x32 /* Lower-case AM or PM */
#define FMT_DATE_A_LOWER    0x33 /* Lower-case A or P */
#define FMT_NUM_COPY_ZERO   0x34 /* Copy 1 digit or 0 if no digit */
#define FMT_NUM_COPY_SKIP   0x35 /* Copy 1 digit or skip if no digit */
276
#define FMT_NUM_DECIMAL     0x36 /* Decimal separator */
277
#define FMT_NUM_EXP_POS_U   0x37 /* Scientific notation, uppercase, + sign */
278 279
#define FMT_NUM_EXP_NEG_U   0x38 /* Scientific notation, uppercase, - sign */
#define FMT_NUM_EXP_POS_L   0x39 /* Scientific notation, lowercase, + sign */
280 281 282 283 284 285 286 287
#define FMT_NUM_EXP_NEG_L   0x3A /* Scientific notation, lowercase, - sign */
#define FMT_NUM_CURRENCY    0x3B /* Currency symbol */
#define FMT_NUM_TRUE_FALSE  0x3D /* Convert to "True" or "False" */
#define FMT_NUM_YES_NO      0x3E /* Convert to "Yes" or "No" */
#define FMT_NUM_ON_OFF      0x3F /* Convert to "On" or "Off"  */
#define FMT_STR_COPY_SPACE  0x40 /* Copy len chars with space if no char */
#define FMT_STR_COPY_SKIP   0x41 /* Copy len chars or skip if no char */
/* Wine additions */
Jon Griffiths's avatar
Jon Griffiths committed
288
#define FMT_WINE_HOURS_12   0x81 /* Hours using 12 hour clock */
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464

/* Named Formats and their tokenised values */
static const WCHAR szGeneralDate[] = { 'G','e','n','e','r','a','l',' ','D','a','t','e','\0' };
static const BYTE fmtGeneralDate[0x0a] =
{
  0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
  0x0,0x0,0x0,0x0,0x0,
  FMT_DATE_GENERAL,FMT_GEN_END
};

static const WCHAR szShortDate[] = { 'S','h','o','r','t',' ','D','a','t','e','\0' };
static const BYTE fmtShortDate[0x0a] =
{
  0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
  0x0,0x0,0x0,0x0,0x0,
  FMT_DATE_SHORT,FMT_GEN_END
};

static const WCHAR szMediumDate[] = { 'M','e','d','i','u','m',' ','D','a','t','e','\0' };
static const BYTE fmtMediumDate[0x0a] =
{
  0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
  0x0,0x0,0x0,0x0,0x0,
  FMT_DATE_MEDIUM,FMT_GEN_END
};

static const WCHAR szLongDate[] = { 'L','o','n','g',' ','D','a','t','e','\0' };
static const BYTE fmtLongDate[0x0a] =
{
  0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
  0x0,0x0,0x0,0x0,0x0,
  FMT_DATE_LONG,FMT_GEN_END
};

static const WCHAR szShortTime[] = { 'S','h','o','r','t',' ','T','i','m','e','\0' };
static const BYTE fmtShortTime[0x0c] =
{
  0x0c,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
  0x0,0x0,0x0,0x0,0x0,
  FMT_DATE_TIME_UNK2,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,FMT_GEN_END
};

static const WCHAR szMediumTime[] = { 'M','e','d','i','u','m',' ','T','i','m','e','\0' };
static const BYTE fmtMediumTime[0x11] =
{
  0x11,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
  0x0,0x0,0x0,0x0,0x0,
  FMT_DATE_HOUR_12_0,FMT_DATE_TIME_SEP,FMT_DATE_MIN_0,
  FMT_GEN_INLINE,0x01,' ','\0',FMT_DATE_AMPM_SYS1,FMT_GEN_END
};

static const WCHAR szLongTime[] = { 'L','o','n','g',' ','T','i','m','e','\0' };
static const BYTE fmtLongTime[0x0d] =
{
  0x0a,FMT_TYPE_DATE,sizeof(FMT_SHORT_HEADER),
  0x0,0x0,0x0,0x0,0x0,
  FMT_DATE_TIME_SYS,FMT_GEN_END
};

static const WCHAR szTrueFalse[] = { 'T','r','u','e','/','F','a','l','s','e','\0' };
static const BYTE fmtTrueFalse[0x0d] =
{
  0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
  FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
  FMT_NUM_TRUE_FALSE,FMT_GEN_END
};

static const WCHAR szYesNo[] = { 'Y','e','s','/','N','o','\0' };
static const BYTE fmtYesNo[0x0d] =
{
  0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
  FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
  FMT_NUM_YES_NO,FMT_GEN_END
};

static const WCHAR szOnOff[] = { 'O','n','/','O','f','f','\0' };
static const BYTE fmtOnOff[0x0d] =
{
  0x0d,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
  FMT_FLAG_BOOL,0x0,0x0,0x0,0x0,
  FMT_NUM_ON_OFF,FMT_GEN_END
};

static const WCHAR szGeneralNumber[] = { 'G','e','n','e','r','a','l',' ','N','u','m','b','e','r','\0' };
static const BYTE fmtGeneralNumber[sizeof(FMT_HEADER)] =
{
  sizeof(FMT_HEADER),FMT_TYPE_GENERAL,sizeof(FMT_HEADER),0x0,0x0,0x0
};

static const WCHAR szCurrency[] = { 'C','u','r','r','e','n','c','y','\0' };
static const BYTE fmtCurrency[0x26] =
{
  0x26,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x12,0x0,0x0,
  /* Positive numbers */
  FMT_FLAG_THOUSANDS,0xcc,0x0,0x1,0x2,
  FMT_NUM_CURRENCY,FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,
  FMT_GEN_END,
  /* Negative numbers */
  FMT_FLAG_THOUSANDS,0xcc,0x0,0x1,0x2,
  FMT_GEN_INLINE,0x1,'(','\0',FMT_NUM_CURRENCY,FMT_NUM_COPY_ZERO,0x1,
  FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_INLINE,0x1,')','\0',
  FMT_GEN_END
};

static const WCHAR szFixed[] = { 'F','i','x','e','d','\0' };
static const BYTE fmtFixed[0x11] =
{
  0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
  0x0,0x0,0x0,0x1,0x2,
  FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
};

static const WCHAR szStandard[] = { 'S','t','a','n','d','a','r','d','\0' };
static const BYTE fmtStandard[0x11] =
{
  0x11,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
  FMT_FLAG_THOUSANDS,0x0,0x0,0x1,0x2,
  FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_GEN_END
};

static const WCHAR szPercent[] = { 'P','e','r','c','e','n','t','\0' };
static const BYTE fmtPercent[0x15] =
{
  0x15,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
  FMT_FLAG_PERCENT,0x1,0x0,0x1,0x2,
  FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,
  FMT_GEN_INLINE,0x1,'%','\0',FMT_GEN_END
};

static const WCHAR szScientific[] = { 'S','c','i','e','n','t','i','f','i','c','\0' };
static const BYTE fmtScientific[0x13] =
{
  0x13,FMT_TYPE_NUMBER,sizeof(FMT_HEADER),0x0,0x0,0x0,
  FMT_FLAG_EXPONENT,0x0,0x0,0x1,0x2,
  FMT_NUM_COPY_ZERO,0x1,FMT_NUM_DECIMAL,FMT_NUM_COPY_ZERO,0x2,FMT_NUM_EXP_POS_U,0x2,FMT_GEN_END
};

typedef struct tagNAMED_FORMAT
{
  LPCWSTR name;
  const BYTE* format;
} NAMED_FORMAT;

/* Format name to tokenised format. Must be kept sorted by name */
static const NAMED_FORMAT VARIANT_NamedFormats[] =
{
  { szCurrency, fmtCurrency },
  { szFixed, fmtFixed },
  { szGeneralDate, fmtGeneralDate },
  { szGeneralNumber, fmtGeneralNumber },
  { szLongDate, fmtLongDate },
  { szLongTime, fmtLongTime },
  { szMediumDate, fmtMediumDate },
  { szMediumTime, fmtMediumTime },
  { szOnOff, fmtOnOff },
  { szPercent, fmtPercent },
  { szScientific, fmtScientific },
  { szShortDate, fmtShortDate },
  { szShortTime, fmtShortTime },
  { szStandard, fmtStandard },
  { szTrueFalse, fmtTrueFalse },
  { szYesNo, fmtYesNo }
};
typedef const NAMED_FORMAT *LPCNAMED_FORMAT;

static int FormatCompareFn(const void *l, const void *r)
{
  return strcmpiW(((LPCNAMED_FORMAT)l)->name, ((LPCNAMED_FORMAT)r)->name);
}

static inline const BYTE *VARIANT_GetNamedFormat(LPCWSTR lpszFormat)
{
  NAMED_FORMAT key;
  LPCNAMED_FORMAT fmt;

  key.name = lpszFormat;
465
  fmt = bsearch(&key, VARIANT_NamedFormats,
466 467 468 469 470 471 472 473 474 475 476 477 478
                                 sizeof(VARIANT_NamedFormats)/sizeof(NAMED_FORMAT),
                                 sizeof(NAMED_FORMAT), FormatCompareFn);
  return fmt ? fmt->format : NULL;
}

/* Return an error if the token for the value will not fit in the destination */
#define NEED_SPACE(x) if (cbTok < (int)(x)) return TYPE_E_BUFFERTOOSMALL; cbTok -= (x)

/* Non-zero if the format is unknown or a given type */
#define COULD_BE(typ) ((!fmt_number && header->type==FMT_TYPE_UNKNOWN)||header->type==typ)

/* State during tokenising */
#define FMT_STATE_OPEN_COPY     0x1 /* Last token written was a copy */
479
#define FMT_STATE_WROTE_DECIMAL 0x2 /* Already wrote a decimal separator */
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
#define FMT_STATE_SEEN_HOURS    0x4 /* See the hh specifier */
#define FMT_STATE_WROTE_MINUTES 0x8 /* Wrote minutes */

/**********************************************************************
 *              VarTokenizeFormatString [OLEAUT32.140]
 *
 * Convert a format string into tokenised form.
 *
 * PARAMS
 *  lpszFormat [I] Format string to tokenise
 *  rgbTok     [O] Destination for tokenised format
 *  cbTok      [I] Size of rgbTok in bytes
 *  nFirstDay  [I] First day of the week (1-7, or 0 for current system default)
 *  nFirstWeek [I] How to treat the first week (see notes)
 *  lcid       [I] Locale Id of the format string
 *  pcbActual  [O] If non-NULL, filled with the first token generated
 *
 * RETURNS
 *  Success: S_OK. rgbTok contains the tokenised format.
 *  Failure: E_INVALIDARG, if any argument is invalid.
 *           TYPE_E_BUFFERTOOSMALL, if rgbTok is not large enough.
 *
 * NOTES
 * Valid values for the nFirstWeek parameter are:
 *| Value  Meaning
 *| -----  -------
 *|   0    Use the current system default
 *|   1    The first week is that containing Jan 1
 *|   2    Four or more days of the first week are in the current year
 *|   3    The first week is 7 days long
 * See Variant-Formats(), VarFormatFromTokens().
 */
HRESULT WINAPI VarTokenizeFormatString(LPOLESTR lpszFormat, LPBYTE rgbTok,
                                       int cbTok, int nFirstDay, int nFirstWeek,
                                       LCID lcid, int *pcbActual)
{
  /* Note: none of these strings should be NUL terminated */
  static const WCHAR szTTTTT[] = { 't','t','t','t','t' };
  static const WCHAR szAMPM[] = { 'A','M','P','M' };
  static const WCHAR szampm[] = { 'a','m','p','m' };
  static const WCHAR szAMSlashPM[] = { 'A','M','/','P','M' };
  static const WCHAR szamSlashpm[] = { 'a','m','/','p','m' };
  const BYTE *namedFmt;
  FMT_HEADER *header = (FMT_HEADER*)rgbTok;
  FMT_STRING_HEADER *str_header = (FMT_STRING_HEADER*)(rgbTok + sizeof(FMT_HEADER));
  FMT_NUMBER_HEADER *num_header = (FMT_NUMBER_HEADER*)str_header;
  BYTE* pOut = rgbTok + sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER);
  BYTE* pLastHours = NULL;
  BYTE fmt_number = 0;
  DWORD fmt_state = 0;
  LPCWSTR pFormat = lpszFormat;

532
  TRACE("(%s,%p,%d,%d,%d,0x%08x,%p)\n", debugstr_w(lpszFormat), rgbTok, cbTok,
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
        nFirstDay, nFirstWeek, lcid, pcbActual);

  if (!rgbTok ||
      nFirstDay < 0 || nFirstDay > 7 || nFirstWeek < 0 || nFirstWeek > 3)
    return E_INVALIDARG;

  if (!lpszFormat || !*lpszFormat)
  {
    /* An empty string means 'general format' */
    NEED_SPACE(sizeof(BYTE));
    *rgbTok = FMT_TO_STRING;
    if (pcbActual)
      *pcbActual = FMT_TO_STRING;
    return S_OK;
  }

  if (cbTok > 255)
    cbTok = 255; /* Ensure we error instead of wrapping */

  /* Named formats */
  namedFmt = VARIANT_GetNamedFormat(lpszFormat);
  if (namedFmt)
  {
    NEED_SPACE(namedFmt[0]);
    memcpy(rgbTok, namedFmt, namedFmt[0]);
    TRACE("Using pre-tokenised named format %s\n", debugstr_w(lpszFormat));
    /* FIXME: pcbActual */
    return S_OK;
  }

  /* Insert header */
  NEED_SPACE(sizeof(FMT_HEADER) + sizeof(FMT_STRING_HEADER));
  memset(header, 0, sizeof(FMT_HEADER));
  memset(str_header, 0, sizeof(FMT_STRING_HEADER));

  header->starts[fmt_number] = sizeof(FMT_HEADER);

  while (*pFormat)
  {
    /* --------------
     * General tokens
     * --------------
     */
    if (*pFormat == ';')
    {
      while (*pFormat == ';')
      {
        TRACE(";\n");
        if (++fmt_number > 3)
          return E_INVALIDARG; /* too many formats */
        pFormat++;
      }
      if (*pFormat)
      {
        TRACE("New header\n");
        NEED_SPACE(sizeof(BYTE) + sizeof(FMT_STRING_HEADER));
        *pOut++ = FMT_GEN_END;

        header->starts[fmt_number] = pOut - rgbTok;
        str_header = (FMT_STRING_HEADER*)pOut;
        num_header = (FMT_NUMBER_HEADER*)pOut;
        memset(str_header, 0, sizeof(FMT_STRING_HEADER));
        pOut += sizeof(FMT_STRING_HEADER);
        fmt_state = 0;
        pLastHours = NULL;
      }
    }
    else if (*pFormat == '\\')
    {
      /* Escaped character */
      if (pFormat[1])
      {
        NEED_SPACE(3 * sizeof(BYTE));
        pFormat++;
        *pOut++ = FMT_GEN_COPY;
        *pOut++ = pFormat - lpszFormat;
        *pOut++ = 0x1;
        fmt_state |= FMT_STATE_OPEN_COPY;
        TRACE("'\\'\n");
      }
      else
        fmt_state &= ~FMT_STATE_OPEN_COPY;
      pFormat++;
    }
    else if (*pFormat == '"')
    {
      /* Escaped string
620
       * Note: Native encodes "" as a copy of length zero. That's just dumb, so
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
       * here we avoid encoding anything in this case.
       */
      if (!pFormat[1])
        pFormat++;
      else if (pFormat[1] == '"')
      {
        pFormat += 2;
      }
      else
      {
        LPCWSTR start = ++pFormat;
        while (*pFormat && *pFormat != '"')
          pFormat++;
        NEED_SPACE(3 * sizeof(BYTE));
        *pOut++ = FMT_GEN_COPY;
        *pOut++ = start - lpszFormat;
        *pOut++ = pFormat - start;
        if (*pFormat == '"')
          pFormat++;
        TRACE("Quoted string pos %d, len %d\n", pOut[-2], pOut[-1]);
      }
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    /* -------------
     * Number tokens
     * -------------
     */
    else if (*pFormat == '0' && COULD_BE(FMT_TYPE_NUMBER))
    {
      /* Number formats: Digit from number or '0' if no digits
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_NUMBER;
      NEED_SPACE(2 * sizeof(BYTE));
      *pOut++ = FMT_NUM_COPY_ZERO;
      *pOut = 0x0;
      while (*pFormat == '0')
      {
        *pOut = *pOut + 1;
        pFormat++;
      }
      if (fmt_state & FMT_STATE_WROTE_DECIMAL)
        num_header->fractional += *pOut;
      else
        num_header->whole += *pOut;
      TRACE("%d 0's\n", *pOut);
      pOut++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    else if (*pFormat == '#' && COULD_BE(FMT_TYPE_NUMBER))
    {
      /* Number formats: Digit from number or blank if no digits
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_NUMBER;
      NEED_SPACE(2 * sizeof(BYTE));
      *pOut++ = FMT_NUM_COPY_SKIP;
      *pOut = 0x0;
      while (*pFormat == '#')
      {
        *pOut = *pOut + 1;
        pFormat++;
      }
      if (fmt_state & FMT_STATE_WROTE_DECIMAL)
        num_header->fractional += *pOut;
      else
        num_header->whole += *pOut;
      TRACE("%d #'s\n", *pOut);
      pOut++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    else if (*pFormat == '.' && COULD_BE(FMT_TYPE_NUMBER) &&
              !(fmt_state & FMT_STATE_WROTE_DECIMAL))
    {
697
      /* Number formats: Decimal separator when 1st seen, literal thereafter
698 699 700 701 702 703 704 705 706 707 708
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_NUMBER;
      NEED_SPACE(sizeof(BYTE));
      *pOut++ = FMT_NUM_DECIMAL;
      fmt_state |= FMT_STATE_WROTE_DECIMAL;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      pFormat++;
      TRACE("decimal sep\n");
    }
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    else if ((*pFormat == 'e' || *pFormat == 'E') && (pFormat[1] == '-' ||
              pFormat[1] == '+') && header->type == FMT_TYPE_NUMBER)
    {
      /* Number formats: Exponent specifier
       * Other formats: Literal
       */
      num_header->flags |= FMT_FLAG_EXPONENT;
      NEED_SPACE(2 * sizeof(BYTE));
      if (*pFormat == 'e') {
        if (pFormat[1] == '+')
          *pOut = FMT_NUM_EXP_POS_L;
        else
          *pOut = FMT_NUM_EXP_NEG_L;
      } else {
        if (pFormat[1] == '+')
          *pOut = FMT_NUM_EXP_POS_U;
        else
          *pOut = FMT_NUM_EXP_NEG_U;
      }
      pFormat += 2;
      *++pOut = 0x0;
      while (*pFormat == '0')
      {
        *pOut = *pOut + 1;
        pFormat++;
      }
      pOut++;
      TRACE("exponent\n");
    }
738 739 740
    /* FIXME: %% => Divide by 1000 */
    else if (*pFormat == ',' && header->type == FMT_TYPE_NUMBER)
    {
741
      /* Number formats: Use the thousands separator
742 743 744 745 746 747 748 749 750 751 752 753 754
       * Other formats: Literal
       */
      num_header->flags |= FMT_FLAG_THOUSANDS;
      pFormat++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      TRACE("thousands sep\n");
    }
    /* -----------
     * Date tokens
     * -----------
     */
    else if (*pFormat == '/' && COULD_BE(FMT_TYPE_DATE))
    {
755
      /* Date formats: Date separator
756 757 758 759 760 761 762 763 764 765 766 767
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      *pOut++ = FMT_DATE_DATE_SEP;
      pFormat++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      TRACE("date sep\n");
    }
    else if (*pFormat == ':' && COULD_BE(FMT_TYPE_DATE))
    {
768
      /* Date formats: Time separator
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      *pOut++ = FMT_DATE_TIME_SEP;
      pFormat++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      TRACE("time sep\n");
    }
    else if ((*pFormat == 'a' || *pFormat == 'A') &&
              !strncmpiW(pFormat, szAMPM, sizeof(szAMPM)/sizeof(WCHAR)))
    {
      /* Date formats: System AM/PM designation
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat += sizeof(szAMPM)/sizeof(WCHAR);
      if (!strncmpW(pFormat, szampm, sizeof(szampm)/sizeof(WCHAR)))
        *pOut++ = FMT_DATE_AMPM_SYS2;
      else
        *pOut++ = FMT_DATE_AMPM_SYS1;
      if (pLastHours)
        *pLastHours = *pLastHours + 2;
      TRACE("ampm\n");
    }
    else if (*pFormat == 'a' && pFormat[1] == '/' &&
              (pFormat[2] == 'p' || pFormat[2] == 'P'))
    {
      /* Date formats: lowercase a or p designation
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat += 3;
      *pOut++ = FMT_DATE_A_LOWER;
      if (pLastHours)
        *pLastHours = *pLastHours + 2;
      TRACE("a/p\n");
    }
    else if (*pFormat == 'A' && pFormat[1] == '/' &&
              (pFormat[2] == 'p' || pFormat[2] == 'P'))
    {
      /* Date formats: Uppercase a or p designation
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat += 3;
      *pOut++ = FMT_DATE_A_UPPER;
      if (pLastHours)
        *pLastHours = *pLastHours + 2;
      TRACE("A/P\n");
    }
    else if (*pFormat == 'a' &&
              !strncmpW(pFormat, szamSlashpm, sizeof(szamSlashpm)/sizeof(WCHAR)))
    {
      /* Date formats: lowercase AM or PM designation
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat += sizeof(szamSlashpm)/sizeof(WCHAR);
      *pOut++ = FMT_DATE_AMPM_LOWER;
      if (pLastHours)
        *pLastHours = *pLastHours + 2;
      TRACE("AM/PM\n");
    }
    else if (*pFormat == 'A' &&
              !strncmpW(pFormat, szAMSlashPM, sizeof(szAMSlashPM)/sizeof(WCHAR)))
    {
      /* Date formats: Uppercase AM or PM designation
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
      *pOut++ = FMT_DATE_AMPM_UPPER;
      TRACE("AM/PM\n");
    }
    else if (*pFormat == 'c' || *pFormat == 'C')
    {
      /* Date formats: General date format
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat += sizeof(szAMSlashPM)/sizeof(WCHAR);
      *pOut++ = FMT_DATE_GENERAL;
      TRACE("gen date\n");
    }
    else if ((*pFormat == 'd' || *pFormat == 'D') && COULD_BE(FMT_TYPE_DATE))
    {
      /* Date formats: Day specifier
       * Other formats: Literal
       * Types the format if found
       */
      int count = -1;
      header->type = FMT_TYPE_DATE;
      while ((*pFormat == 'd' || *pFormat == 'D') && count < 6)
      {
        pFormat++;
        count++;
      }
      NEED_SPACE(sizeof(BYTE));
      *pOut++ = FMT_DATE_DAY + count;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      /* When we find the days token, reset the seen hours state so that
       * 'mm' is again written as month when encountered.
       */
      fmt_state &= ~FMT_STATE_SEEN_HOURS;
      TRACE("%d d's\n", count + 1);
    }
    else if ((*pFormat == 'h' || *pFormat == 'H') && COULD_BE(FMT_TYPE_DATE))
    {
      /* Date formats: Hour specifier
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat++;
      /* Record the position of the hours specifier - if we encounter
       * an am/pm specifier we will change the hours from 24 to 12.
       */
      pLastHours = pOut;
      if (*pFormat == 'h' || *pFormat == 'H')
      {
        pFormat++;
        *pOut++ = FMT_DATE_HOUR_0;
        TRACE("hh\n");
      }
      else
      {
        *pOut++ = FMT_DATE_HOUR;
        TRACE("h\n");
      }
      fmt_state &= ~FMT_STATE_OPEN_COPY;
914
      /* Note that now we have seen an hours token, the next occurrence of
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
       * 'mm' indicates minutes, not months.
       */
      fmt_state |= FMT_STATE_SEEN_HOURS;
    }
    else if ((*pFormat == 'm' || *pFormat == 'M') && COULD_BE(FMT_TYPE_DATE))
    {
      /* Date formats: Month specifier (or Minute specifier, after hour specifier)
       * Other formats: Literal
       * Types the format if found
       */
      int count = -1;
      header->type = FMT_TYPE_DATE;
      while ((*pFormat == 'm' || *pFormat == 'M') && count < 4)
      {
        pFormat++;
        count++;
      }
      NEED_SPACE(sizeof(BYTE));
      if (count <= 1 && fmt_state & FMT_STATE_SEEN_HOURS &&
          !(fmt_state & FMT_STATE_WROTE_MINUTES))
      {
        /* We have seen an hours specifier and not yet written a minutes
         * specifier. Write this as minutes and thereafter as months.
         */
        *pOut++ = count == 1 ? FMT_DATE_MIN_0 : FMT_DATE_MIN;
        fmt_state |= FMT_STATE_WROTE_MINUTES; /* Hereafter write months */
      }
      else
        *pOut++ = FMT_DATE_MON + count; /* Months */
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      TRACE("%d m's\n", count + 1);
    }
    else if ((*pFormat == 'n' || *pFormat == 'N') && COULD_BE(FMT_TYPE_DATE))
    {
      /* Date formats: Minute specifier
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat++;
      if (*pFormat == 'n' || *pFormat == 'N')
      {
        pFormat++;
        *pOut++ = FMT_DATE_MIN_0;
        TRACE("nn\n");
      }
      else
      {
        *pOut++ = FMT_DATE_MIN;
        TRACE("n\n");
      }
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
969
    else if ((*pFormat == 'q' || *pFormat == 'Q') && COULD_BE(FMT_TYPE_DATE))
970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
    {
      /* Date formats: Quarter specifier
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      *pOut++ = FMT_DATE_QUARTER;
      pFormat++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      TRACE("quarter\n");
    }
    else if ((*pFormat == 's' || *pFormat == 'S') && COULD_BE(FMT_TYPE_DATE))
    {
      /* Date formats: Second specifier
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      NEED_SPACE(sizeof(BYTE));
      pFormat++;
      if (*pFormat == 's' || *pFormat == 'S')
      {
        pFormat++;
        *pOut++ = FMT_DATE_SEC_0;
        TRACE("ss\n");
      }
      else
      {
        *pOut++ = FMT_DATE_SEC;
        TRACE("s\n");
      }
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    else if ((*pFormat == 't' || *pFormat == 'T') &&
              !strncmpiW(pFormat, szTTTTT, sizeof(szTTTTT)/sizeof(WCHAR)))
    {
      /* Date formats: System time specifier
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      pFormat += sizeof(szTTTTT)/sizeof(WCHAR);
      NEED_SPACE(sizeof(BYTE));
      *pOut++ = FMT_DATE_TIME_SYS;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    else if ((*pFormat == 'w' || *pFormat == 'W') && COULD_BE(FMT_TYPE_DATE))
    {
      /* Date formats: Week of the year/Day of the week
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_DATE;
      pFormat++;
      if (*pFormat == 'w' || *pFormat == 'W')
      {
        NEED_SPACE(3 * sizeof(BYTE));
        pFormat++;
        *pOut++ = FMT_DATE_WEEK_YEAR;
        *pOut++ = nFirstDay;
        *pOut++ = nFirstWeek;
        TRACE("ww\n");
      }
      else
      {
        NEED_SPACE(2 * sizeof(BYTE));
        *pOut++ = FMT_DATE_DAY_WEEK;
        *pOut++ = nFirstDay;
        TRACE("w\n");
      }

      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    else if ((*pFormat == 'y' || *pFormat == 'Y') && COULD_BE(FMT_TYPE_DATE))
    {
      /* Date formats: Day of year/Year specifier
       * Other formats: Literal
       * Types the format if found
       */
      int count = -1;
      header->type = FMT_TYPE_DATE;
      while ((*pFormat == 'y' || *pFormat == 'Y') && count < 4)
      {
        pFormat++;
        count++;
      }
      if (count == 2)
      {
        count--; /* 'yyy' has no meaning, despite what MSDN says */
        pFormat--;
      }
      NEED_SPACE(sizeof(BYTE));
      *pOut++ = FMT_DATE_YEAR_DOY + count;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      TRACE("%d y's\n", count + 1);
    }
    /* -------------
     * String tokens
     * -------------
     */
    else if (*pFormat == '@' && COULD_BE(FMT_TYPE_STRING))
    {
      /* String formats: Character from string or space if no char
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_STRING;
      NEED_SPACE(2 * sizeof(BYTE));
      *pOut++ = FMT_STR_COPY_SPACE;
      *pOut = 0x0;
      while (*pFormat == '@')
      {
        *pOut = *pOut + 1;
        str_header->copy_chars++;
        pFormat++;
      }
      TRACE("%d @'s\n", *pOut);
      pOut++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    else if (*pFormat == '&' && COULD_BE(FMT_TYPE_STRING))
    {
      /* String formats: Character from string or skip if no char
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_STRING;
      NEED_SPACE(2 * sizeof(BYTE));
      *pOut++ = FMT_STR_COPY_SKIP;
      *pOut = 0x0;
      while (*pFormat == '&')
      {
        *pOut = *pOut + 1;
        str_header->copy_chars++;
        pFormat++;
      }
      TRACE("%d &'s\n", *pOut);
      pOut++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    else if ((*pFormat == '<' || *pFormat == '>') && COULD_BE(FMT_TYPE_STRING))
    {
      /* String formats: Use upper/lower case
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_STRING;
      if (*pFormat == '<')
        str_header->flags |= FMT_FLAG_LT;
      else
        str_header->flags |= FMT_FLAG_GT;
      TRACE("to %s case\n", *pFormat == '<' ? "lower" : "upper");
      pFormat++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
    }
    else if (*pFormat == '!' && COULD_BE(FMT_TYPE_STRING))
    {
      /* String formats: Copy right to left
       * Other formats: Literal
       * Types the format if found
       */
      header->type = FMT_TYPE_STRING;
      str_header->flags |= FMT_FLAG_RTL;
      pFormat++;
      fmt_state &= ~FMT_STATE_OPEN_COPY;
      TRACE("copy right-to-left\n");
    }
    /* --------
     * Literals
     * --------
     */
    /* FIXME: [ seems to be ignored */
    else
    {
      if (*pFormat == '%' && header->type == FMT_TYPE_NUMBER)
      {
        /* Number formats: Percentage indicator, also a literal
         * Other formats: Literal
         * Doesn't type the format
         */
        num_header->flags |= FMT_FLAG_PERCENT;
      }

      if (fmt_state & FMT_STATE_OPEN_COPY)
      {
        pOut[-1] = pOut[-1] + 1; /* Increase the length of the open copy */
        TRACE("extend copy (char '%c'), length now %d\n", *pFormat, pOut[-1]);
      }
      else
      {
        /* Create a new open copy */
        TRACE("New copy (char '%c')\n", *pFormat);
        NEED_SPACE(3 * sizeof(BYTE));
        *pOut++ = FMT_GEN_COPY;
        *pOut++ = pFormat - lpszFormat;
        *pOut++ = 0x1;
        fmt_state |= FMT_STATE_OPEN_COPY;
      }
      pFormat++;
    }
  }

  *pOut++ = FMT_GEN_END;

  header->size = pOut - rgbTok;
  if (pcbActual)
    *pcbActual = header->size;

  return S_OK;
}

/* Number formatting state flags */
1183
#define NUM_WROTE_DEC  0x01 /* Written the decimal separator */
1184
#define NUM_WRITE_ON   0x02 /* Started to write the number */
1185
#define NUM_WROTE_SIGN 0x04 /* Written the negative sign */
1186 1187 1188 1189 1190 1191

/* Format a variant using a number format */
static HRESULT VARIANT_FormatNumber(LPVARIANT pVarIn, LPOLESTR lpszFormat,
                                    LPBYTE rgbTok, ULONG dwFlags,
                                    BSTR *pbstrOut, LCID lcid)
{
1192
  BYTE rgbDig[256], *prgbDig;
1193
  NUMPARSE np;
1194
  int have_int, need_int = 0, have_frac, need_frac, exponent = 0, pad = 0;
1195
  WCHAR buff[256], *pBuff = buff;
1196
  WCHAR thousandSeparator[32];
1197 1198 1199 1200 1201 1202 1203
  VARIANT vString, vBool;
  DWORD dwState = 0;
  FMT_HEADER *header = (FMT_HEADER*)rgbTok;
  FMT_NUMBER_HEADER *numHeader;
  const BYTE* pToken = NULL;
  HRESULT hRes = S_OK;

1204
  TRACE("(%p->(%s%s),%s,%p,0x%08x,%p,0x%08x)\n", pVarIn, debugstr_VT(pVarIn),
1205 1206 1207 1208 1209 1210 1211 1212
        debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
        lcid);

  V_VT(&vString) = VT_EMPTY;
  V_VT(&vBool) = VT_BOOL;

  if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
  {
1213
    have_int = have_frac = 0;
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNull(header));
    V_BOOL(&vBool) = VARIANT_FALSE;
  }
  else
  {
    /* Get a number string from pVarIn, and parse it */
    hRes = VariantChangeTypeEx(&vString, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
    if (FAILED(hRes))
      return hRes;

    np.cDig = sizeof(rgbDig);
    np.dwInFlags = NUMPRS_STD;
    hRes = VarParseNumFromStr(V_BSTR(&vString), LCID_US, 0, &np, rgbDig);
    if (FAILED(hRes))
      return hRes;

1230 1231 1232
    have_int = np.cDig;
    have_frac = 0;
    exponent = np.nPwr10;
1233 1234 1235 1236 1237 1238 1239

    /* Figure out which format to use */
    if (np.dwOutFlags & NUMPRS_NEG)
    {
      numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetNegative(header));
      V_BOOL(&vBool) = VARIANT_TRUE;
    }
1240
    else if (have_int == 1 && !exponent && rgbDig[0] == 0)
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
    {
      numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetZero(header));
      V_BOOL(&vBool) = VARIANT_FALSE;
    }
    else
    {
      numHeader = (FMT_NUMBER_HEADER*)(rgbTok + FmtGetPositive(header));
      V_BOOL(&vBool) = VARIANT_TRUE;
    }

    TRACE("num header: flags = 0x%x, mult=%d, div=%d, whole=%d, fract=%d\n",
          numHeader->flags, numHeader->multiplier, numHeader->divisor,
          numHeader->whole, numHeader->fractional);

1255 1256 1257
    need_int = numHeader->whole;
    need_frac = numHeader->fractional;

1258
    if (numHeader->flags & FMT_FLAG_PERCENT &&
1259 1260 1261 1262
        !(have_int == 1 && !exponent && rgbDig[0] == 0))
      exponent += 2;

    if (numHeader->flags & FMT_FLAG_EXPONENT)
1263
    {
1264 1265 1266 1267 1268
      /* Exponent format: length of the integral number part is fixed and
         specified by the format. */
      pad = need_int - have_int;
      if (pad >= 0)
        exponent -= pad;
1269 1270
      else
      {
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
        have_int = need_int;
        have_frac -= pad;
        exponent -= pad;
        pad = 0;
      }
    }
    else
    {
      /* Convert the exponent */
      pad = max(exponent, -have_int);
      exponent -= pad;
      if (pad < 0)
      {
        have_int += pad;
        have_frac = -pad;
        pad = 0;
      }
    }

    /* Rounding the number */
    if (have_frac > need_frac)
    {
      prgbDig = &rgbDig[have_int + need_frac];
      have_frac = need_frac;
      if (*prgbDig >= 5)
      {
        while (prgbDig-- > rgbDig && *prgbDig == 9)
          *prgbDig = 0;
        if (prgbDig < rgbDig)
1300
        {
1301 1302 1303 1304 1305 1306 1307 1308 1309
          /* We reached the first digit and that was also a 9 */
          rgbDig[0] = 1;
          if (numHeader->flags & FMT_FLAG_EXPONENT)
            exponent++;
          else
          {
            rgbDig[have_int + need_frac] = 0;
            have_int++;
          }
1310
        }
1311 1312
        else
          (*prgbDig)++;
1313 1314
      }
    }
1315 1316
    TRACE("have_int=%d,need_int=%d,have_frac=%d,need_frac=%d,pad=%d,exp=%d\n",
          have_int, need_int, have_frac, need_frac, pad, exponent);
1317
  }
1318

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
  if (numHeader->flags & FMT_FLAG_THOUSANDS)
  {
    if (!GetLocaleInfoW(lcid, LOCALE_STHOUSAND, thousandSeparator,
                        sizeof(thousandSeparator)/sizeof(WCHAR)))
    {
      thousandSeparator[0] = ',';
      thousandSeparator[1] = 0;
    }
  }

1329
  pToken = (const BYTE*)numHeader + sizeof(FMT_NUMBER_HEADER);
1330
  prgbDig = rgbDig;
1331 1332 1333 1334 1335

  while (SUCCEEDED(hRes) && *pToken != FMT_GEN_END)
  {
    WCHAR defaultChar = '?';
    DWORD boolFlag, localeValue = 0;
1336
    BOOL shouldAdvance = TRUE;
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355

    if (pToken - rgbTok > header->size)
    {
      ERR("Ran off the end of the format!\n");
      hRes = E_INVALIDARG;
      goto VARIANT_FormatNumber_Exit;
    }

    switch (*pToken)
    {
    case FMT_GEN_COPY:
      TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
      memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
      pBuff += pToken[2];
      pToken += 2;
      break;

    case FMT_GEN_INLINE:
      pToken += 2;
Mike McCormack's avatar
Mike McCormack committed
1356
      TRACE("copy %s\n", debugstr_a((LPCSTR)pToken));
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393
      while (*pToken)
        *pBuff++ = *pToken++;
      break;

    case FMT_NUM_YES_NO:
      boolFlag = VAR_BOOLYESNO;
      goto VARIANT_FormatNumber_Bool;

    case FMT_NUM_ON_OFF:
      boolFlag = VAR_BOOLONOFF;
      goto VARIANT_FormatNumber_Bool;

    case FMT_NUM_TRUE_FALSE:
      boolFlag = VAR_LOCALBOOL;

VARIANT_FormatNumber_Bool:
      {
        BSTR boolStr = NULL;

        if (pToken[1] != FMT_GEN_END)
        {
          ERR("Boolean token not at end of format!\n");
          hRes = E_INVALIDARG;
          goto VARIANT_FormatNumber_Exit;
        }
        hRes = VarBstrFromBool(V_BOOL(&vBool), lcid, boolFlag, &boolStr);
        if (SUCCEEDED(hRes))
        {
          strcpyW(pBuff, boolStr);
          SysFreeString(boolStr);
          while (*pBuff)
            pBuff++;
        }
      }
      break;

    case FMT_NUM_DECIMAL:
1394
      if ((np.dwOutFlags & NUMPRS_NEG) && !(dwState & NUM_WROTE_SIGN) && !header->starts[1])
1395 1396 1397 1398 1399 1400 1401 1402 1403
      {
        /* last chance for a negative sign in the .# case */
        TRACE("write negative sign\n");
        localeValue = LOCALE_SNEGATIVESIGN;
        defaultChar = '-';
        dwState |= NUM_WROTE_SIGN;
        shouldAdvance = FALSE;
        break;
      }
1404
      TRACE("write decimal separator\n");
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
      localeValue = LOCALE_SDECIMAL;
      defaultChar = '.';
      dwState |= NUM_WROTE_DEC;
      break;

    case FMT_NUM_CURRENCY:
      TRACE("write currency symbol\n");
      localeValue = LOCALE_SCURRENCY;
      defaultChar = '$';
      break;

    case FMT_NUM_EXP_POS_U:
    case FMT_NUM_EXP_POS_L:
    case FMT_NUM_EXP_NEG_U:
    case FMT_NUM_EXP_NEG_L:
      if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_NEG_L)
        *pBuff++ = 'e';
      else
        *pBuff++ = 'E';
1424
      if (exponent < 0)
1425 1426
      {
        *pBuff++ = '-';
1427
        sprintfW(pBuff, szPercentZeroStar_d, pToken[1], -exponent);
1428 1429 1430 1431 1432
      }
      else
      {
        if (*pToken == FMT_NUM_EXP_POS_L || *pToken == FMT_NUM_EXP_POS_U)
          *pBuff++ = '+';
1433
        sprintfW(pBuff, szPercentZeroStar_d, pToken[1], exponent);
1434 1435 1436 1437 1438 1439
      }
      while (*pBuff)
        pBuff++;
      pToken++;
      break;

1440 1441 1442
    case FMT_NUM_COPY_ZERO:
      dwState |= NUM_WRITE_ON;
      /* Fall through */
1443

1444 1445 1446 1447
    case FMT_NUM_COPY_SKIP:
      TRACE("write %d %sdigits or %s\n", pToken[1],
            dwState & NUM_WROTE_DEC ? "fractional " : "",
            *pToken == FMT_NUM_COPY_ZERO ? "0" : "skip");
1448

1449
      if (dwState & NUM_WROTE_DEC)
1450
      {
1451
        int count, i;
1452

1453
        if (!(numHeader->flags & FMT_FLAG_EXPONENT) && exponent < 0)
1454
        {
1455 1456 1457 1458 1459 1460
          /* Pad with 0 before writing the fractional digits */
          pad = max(exponent, -pToken[1]);
          exponent -= pad;
          count = min(have_frac, pToken[1] + pad);
          for (i = 0; i > pad; i--)
            *pBuff++ = '0';
1461
        }
1462 1463
        else
          count = min(have_frac, pToken[1]);
1464

1465 1466 1467 1468 1469
        pad += pToken[1] - count;
        have_frac -= count;
        while (count--)
          *pBuff++ = '0' + *prgbDig++;
        if (*pToken == FMT_NUM_COPY_ZERO)
1470
        {
1471 1472
          for (; pad > 0; pad--)
            *pBuff++ = '0'; /* Write zeros for missing trailing digits */
1473 1474 1475 1476
        }
      }
      else
      {
1477
        int count, count_max, position;
1478

1479
        if ((np.dwOutFlags & NUMPRS_NEG) && !(dwState & NUM_WROTE_SIGN) && !header->starts[1])
1480 1481 1482 1483 1484 1485 1486 1487 1488
        {
          TRACE("write negative sign\n");
          localeValue = LOCALE_SNEGATIVESIGN;
          defaultChar = '-';
          dwState |= NUM_WROTE_SIGN;
          shouldAdvance = FALSE;
          break;
        }

1489 1490 1491
        position = have_int + pad;
        if (dwState & NUM_WRITE_ON)
          position = max(position, need_int);
1492 1493 1494 1495 1496
        need_int -= pToken[1];
        count_max = have_int + pad - need_int;
        if (count_max < 0)
            count_max = 0;
        if (dwState & NUM_WRITE_ON)
1497
        {
1498
          count = pToken[1] - count_max;
1499
          TRACE("write %d leading zeros\n", count);
1500
          while (count-- > 0)
1501
          {
1502
            *pBuff++ = '0';
1503 1504 1505 1506 1507 1508 1509 1510 1511
            if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
                position > 1 && (--position % 3) == 0)
            {
              int k;
              TRACE("write thousand separator\n");
              for (k = 0; thousandSeparator[k]; k++)
                *pBuff++ = thousandSeparator[k];
            }
          }
1512
        }
1513 1514
        if (*pToken == FMT_NUM_COPY_ZERO || have_int > 1 ||
            (have_int > 0 && *prgbDig > 0))
1515 1516 1517 1518 1519 1520
        {
          count = min(count_max, have_int);
          count_max -= count;
          have_int -= count;
          TRACE("write %d whole number digits\n", count);
          while (count--)
1521 1522
          {
            dwState |= NUM_WRITE_ON;
1523
            *pBuff++ = '0' + *prgbDig++;
1524 1525 1526 1527 1528 1529 1530 1531 1532
            if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
                position > 1 && (--position % 3) == 0)
            {
              int k;
              TRACE("write thousand separator\n");
              for (k = 0; thousandSeparator[k]; k++)
                *pBuff++ = thousandSeparator[k];
            }
          }
1533
        }
1534 1535 1536 1537
        count = min(count_max, pad);
        pad -= count;
        TRACE("write %d whole trailing 0's\n", count);
        while (count--)
1538
        {
1539
          *pBuff++ = '0';
1540 1541 1542 1543 1544 1545 1546 1547 1548
          if ((numHeader->flags & FMT_FLAG_THOUSANDS) &&
              position > 1 && (--position % 3) == 0)
          {
            int k;
            TRACE("write thousand separator\n");
            for (k = 0; thousandSeparator[k]; k++)
              *pBuff++ = thousandSeparator[k];
          }
        }
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
      }
      pToken++;
      break;

    default:
      ERR("Unknown token 0x%02x!\n", *pToken);
      hRes = E_INVALIDARG;
      goto VARIANT_FormatNumber_Exit;
    }
    if (localeValue)
    {
      if (GetLocaleInfoW(lcid, localeValue, pBuff, 
                         sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
      {
        TRACE("added %s\n", debugstr_w(pBuff));
        while (*pBuff)
          pBuff++;
      }
      else
      {
        TRACE("added %d '%c'\n", defaultChar, defaultChar);
        *pBuff++ = defaultChar;
      }
    }
1573 1574
    if (shouldAdvance)
      pToken++;
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
  }

VARIANT_FormatNumber_Exit:
  VariantClear(&vString);
  *pBuff = '\0';
  TRACE("buff is %s\n", debugstr_w(buff));
  if (SUCCEEDED(hRes))
  {
    *pbstrOut = SysAllocString(buff);
    if (!*pbstrOut)
      hRes = E_OUTOFMEMORY;
  }
  return hRes;
}

/* Format a variant using a date format */
static HRESULT VARIANT_FormatDate(LPVARIANT pVarIn, LPOLESTR lpszFormat,
                                  LPBYTE rgbTok, ULONG dwFlags,
                                  BSTR *pbstrOut, LCID lcid)
{
  WCHAR buff[256], *pBuff = buff;
  VARIANT vDate;
  UDATE udate;
  FMT_HEADER *header = (FMT_HEADER*)rgbTok;
  FMT_DATE_HEADER *dateHeader;
  const BYTE* pToken = NULL;
  HRESULT hRes;

1603
  TRACE("(%p->(%s%s),%s,%p,0x%08x,%p,0x%08x)\n", pVarIn, debugstr_VT(pVarIn),
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
        debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
        lcid);

  V_VT(&vDate) = VT_EMPTY;

  if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
  {
    dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetNegative(header));
    V_DATE(&vDate) = 0;
  }
  else
  {
    USHORT usFlags = dwFlags & VARIANT_CALENDAR_HIJRI ? VAR_CALENDAR_HIJRI : 0;

    hRes = VariantChangeTypeEx(&vDate, pVarIn, LCID_US, usFlags, VT_DATE);
    if (FAILED(hRes))
      return hRes;
    dateHeader = (FMT_DATE_HEADER*)(rgbTok + FmtGetPositive(header));
  }

  hRes = VarUdateFromDate(V_DATE(&vDate), 0 /* FIXME: flags? */, &udate);
  if (FAILED(hRes))
    return hRes;
  pToken = (const BYTE*)dateHeader + sizeof(FMT_DATE_HEADER);

  while (*pToken != FMT_GEN_END)
  {
    DWORD dwVal = 0, localeValue = 0, dwFmt = 0;
    LPCWSTR szPrintFmt = NULL;
    WCHAR defaultChar = '?';

    if (pToken - rgbTok > header->size)
    {
      ERR("Ran off the end of the format!\n");
      hRes = E_INVALIDARG;
      goto VARIANT_FormatDate_Exit;
    }

    switch (*pToken)
    {
    case FMT_GEN_COPY:
      TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
      memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
      pBuff += pToken[2];
      pToken += 2;
      break;

    case FMT_DATE_TIME_SEP:
1652
      TRACE("time separator\n");
1653 1654 1655 1656 1657
      localeValue = LOCALE_STIME;
      defaultChar = ':';
      break;

    case FMT_DATE_DATE_SEP:
1658
      TRACE("date separator\n");
1659 1660 1661 1662 1663 1664 1665
      localeValue = LOCALE_SDATE;
      defaultChar = '/';
      break;

    case FMT_DATE_GENERAL:
      {
        BSTR date = NULL;
1666 1667
        WCHAR *pDate;
        hRes = VarBstrFromDate(V_DATE(&vDate), lcid, 0, &date);
1668 1669
        if (FAILED(hRes))
          goto VARIANT_FormatDate_Exit;
1670
	pDate = date;
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
        while (*pDate)
          *pBuff++ = *pDate++;
        SysFreeString(date);
      }
      break;

    case FMT_DATE_QUARTER:
      if (udate.st.wMonth <= 3)
        *pBuff++ = '1';
      else if (udate.st.wMonth <= 6)
        *pBuff++ = '2';
      else if (udate.st.wMonth <= 9)
        *pBuff++ = '3';
      else
        *pBuff++ = '4';
      break;

    case FMT_DATE_TIME_SYS:
      {
        /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
        BSTR date = NULL;
1692 1693
        WCHAR *pDate;
        hRes = VarBstrFromDate(V_DATE(&vDate), lcid, VAR_TIMEVALUEONLY, &date);
1694 1695
        if (FAILED(hRes))
          goto VARIANT_FormatDate_Exit;
1696
	pDate = date;
1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
        while (*pDate)
          *pBuff++ = *pDate++;
        SysFreeString(date);
      }
      break;

    case FMT_DATE_DAY:
      szPrintFmt = szPercent_d;
      dwVal = udate.st.wDay;
      break;

    case FMT_DATE_DAY_0:
      szPrintFmt = szPercentZeroTwo_d;
      dwVal = udate.st.wDay;
      break;

    case FMT_DATE_DAY_SHORT:
      /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
      TRACE("short day\n");
      localeValue = LOCALE_SABBREVDAYNAME1 + udate.st.wMonth - 1;
      defaultChar = '?';
      break;

    case FMT_DATE_DAY_LONG:
      /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
      TRACE("long day\n");
      localeValue = LOCALE_SDAYNAME1 + udate.st.wMonth - 1;
      defaultChar = '?';
      break;

    case FMT_DATE_SHORT:
      /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
      dwFmt = LOCALE_SSHORTDATE;
      break;

    case FMT_DATE_LONG:
      /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
      dwFmt = LOCALE_SLONGDATE;
      break;

    case FMT_DATE_MEDIUM:
      FIXME("Medium date treated as long date\n");
      dwFmt = LOCALE_SLONGDATE;
      break;

    case FMT_DATE_DAY_WEEK:
      szPrintFmt = szPercent_d;
      if (pToken[1])
        dwVal = udate.st.wDayOfWeek + 2 - pToken[1];
      else
      {
        GetLocaleInfoW(lcid,LOCALE_RETURN_NUMBER|LOCALE_IFIRSTDAYOFWEEK,
                       (LPWSTR)&dwVal, sizeof(dwVal)/sizeof(WCHAR));
        dwVal = udate.st.wDayOfWeek + 1 - dwVal;
      }
      pToken++;
      break;

    case FMT_DATE_WEEK_YEAR:
      szPrintFmt = szPercent_d;
      dwVal = udate.wDayOfYear / 7 + 1;
      pToken += 2;
      FIXME("Ignoring nFirstDay of %d, nFirstWeek of %d\n", pToken[0], pToken[1]);
      break;

    case FMT_DATE_MON:
      szPrintFmt = szPercent_d;
      dwVal = udate.st.wMonth;
      break;

    case FMT_DATE_MON_0:
      szPrintFmt = szPercentZeroTwo_d;
      dwVal = udate.st.wMonth;
      break;

    case FMT_DATE_MON_SHORT:
      /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
      TRACE("short month\n");
      localeValue = LOCALE_SABBREVMONTHNAME1 + udate.st.wMonth - 1;
      defaultChar = '?';
      break;

    case FMT_DATE_MON_LONG:
      /* FIXME: VARIANT_CALENDAR HIJRI should cause Hijri output */
      TRACE("long month\n");
      localeValue = LOCALE_SMONTHNAME1 + udate.st.wMonth - 1;
      defaultChar = '?';
      break;

    case FMT_DATE_YEAR_DOY:
      szPrintFmt = szPercent_d;
      dwVal = udate.wDayOfYear;
      break;

    case FMT_DATE_YEAR_0:
      szPrintFmt = szPercentZeroTwo_d;
      dwVal = udate.st.wYear % 100;
      break;

    case FMT_DATE_YEAR_LONG:
      szPrintFmt = szPercent_d;
      dwVal = udate.st.wYear;
      break;

    case FMT_DATE_MIN:
      szPrintFmt = szPercent_d;
      dwVal = udate.st.wMinute;
      break;

    case FMT_DATE_MIN_0:
      szPrintFmt = szPercentZeroTwo_d;
      dwVal = udate.st.wMinute;
      break;

    case FMT_DATE_SEC:
      szPrintFmt = szPercent_d;
      dwVal = udate.st.wSecond;
      break;

    case FMT_DATE_SEC_0:
      szPrintFmt = szPercentZeroTwo_d;
      dwVal = udate.st.wSecond;
      break;

    case FMT_DATE_HOUR:
      szPrintFmt = szPercent_d;
      dwVal = udate.st.wHour;
      break;

    case FMT_DATE_HOUR_0:
      szPrintFmt = szPercentZeroTwo_d;
      dwVal = udate.st.wHour;
      break;

    case FMT_DATE_HOUR_12:
      szPrintFmt = szPercent_d;
      dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
      break;

    case FMT_DATE_HOUR_12_0:
      szPrintFmt = szPercentZeroTwo_d;
      dwVal = udate.st.wHour ? udate.st.wHour > 12 ? udate.st.wHour - 12 : udate.st.wHour : 12;
      break;

    case FMT_DATE_AMPM_SYS1:
    case FMT_DATE_AMPM_SYS2:
      localeValue = udate.st.wHour < 12 ? LOCALE_S1159 : LOCALE_S2359;
      defaultChar = '?';
      break;

    case FMT_DATE_AMPM_UPPER:
      *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
      *pBuff++ = 'M';
      break;

    case FMT_DATE_A_UPPER:
      *pBuff++ = udate.st.wHour < 12 ? 'A' : 'P';
      break;

    case FMT_DATE_AMPM_LOWER:
      *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
      *pBuff++ = 'm';
      break;

    case FMT_DATE_A_LOWER:
      *pBuff++ = udate.st.wHour < 12 ? 'a' : 'p';
      break;

    default:
      ERR("Unknown token 0x%02x!\n", *pToken);
      hRes = E_INVALIDARG;
      goto VARIANT_FormatDate_Exit;
    }
    if (localeValue)
    {
      *pBuff = '\0';
      if (GetLocaleInfoW(lcid, localeValue, pBuff,
          sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
      {
        TRACE("added %s\n", debugstr_w(pBuff));
        while (*pBuff)
          pBuff++;
      }
      else
      {
        TRACE("added %d %c\n", defaultChar, defaultChar);
        *pBuff++ = defaultChar;
      }
    }
    else if (dwFmt)
    {
      WCHAR fmt_buff[80];

      if (!GetLocaleInfoW(lcid, dwFmt, fmt_buff, sizeof(fmt_buff)/sizeof(WCHAR)) ||
          !GetDateFormatW(lcid, 0, &udate.st, fmt_buff, pBuff,
                          sizeof(buff)/sizeof(WCHAR)-(pBuff-buff)))
      {
        hRes = E_INVALIDARG;
        goto VARIANT_FormatDate_Exit;
      }
      while (*pBuff)
        pBuff++;
    }
    else if (szPrintFmt)
    {
      sprintfW(pBuff, szPrintFmt, dwVal);
      while (*pBuff)
        pBuff++;
    }
    pToken++;
  }

VARIANT_FormatDate_Exit:
  *pBuff = '\0';
  TRACE("buff is %s\n", debugstr_w(buff));
  if (SUCCEEDED(hRes))
  {
    *pbstrOut = SysAllocString(buff);
    if (!*pbstrOut)
      hRes = E_OUTOFMEMORY;
  }
  return hRes;
}

/* Format a variant using a string format */
static HRESULT VARIANT_FormatString(LPVARIANT pVarIn, LPOLESTR lpszFormat,
                                    LPBYTE rgbTok, ULONG dwFlags,
                                    BSTR *pbstrOut, LCID lcid)
{
1926
  static WCHAR szEmpty[] = { '\0' };
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
  WCHAR buff[256], *pBuff = buff;
  WCHAR *pSrc;
  FMT_HEADER *header = (FMT_HEADER*)rgbTok;
  FMT_STRING_HEADER *strHeader;
  const BYTE* pToken = NULL;
  VARIANT vStr;
  int blanks_first;
  BOOL bUpper = FALSE;
  HRESULT hRes = S_OK;

1937
  TRACE("(%p->(%s%s),%s,%p,0x%08x,%p,0x%08x)\n", pVarIn, debugstr_VT(pVarIn),
1938 1939 1940 1941 1942 1943 1944 1945
        debugstr_VF(pVarIn), debugstr_w(lpszFormat), rgbTok, dwFlags, pbstrOut,
        lcid);

  V_VT(&vStr) = VT_EMPTY;

  if (V_TYPE(pVarIn) == VT_EMPTY || V_TYPE(pVarIn) == VT_NULL)
  {
    strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
1946
    V_BSTR(&vStr) = szEmpty;
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
  }
  else
  {
    hRes = VariantChangeTypeEx(&vStr, pVarIn, LCID_US, VARIANT_NOUSEROVERRIDE, VT_BSTR);
    if (FAILED(hRes))
      return hRes;

    if (V_BSTR(pVarIn)[0] == '\0')
      strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetNegative(header));
    else
      strHeader = (FMT_STRING_HEADER*)(rgbTok + FmtGetPositive(header));
  }
  pSrc = V_BSTR(&vStr);
  if ((strHeader->flags & (FMT_FLAG_LT|FMT_FLAG_GT)) == FMT_FLAG_GT)
    bUpper = TRUE;
  blanks_first = strHeader->copy_chars - strlenW(pSrc);
  pToken = (const BYTE*)strHeader + sizeof(FMT_DATE_HEADER);

  while (*pToken != FMT_GEN_END)
  {
    int dwCount = 0;

    if (pToken - rgbTok > header->size)
    {
      ERR("Ran off the end of the format!\n");
      hRes = E_INVALIDARG;
      goto VARIANT_FormatString_Exit;
    }

    switch (*pToken)
    {
    case FMT_GEN_COPY:
      TRACE("copy %s\n", debugstr_wn(lpszFormat + pToken[1], pToken[2]));
      memcpy(pBuff, lpszFormat + pToken[1], pToken[2] * sizeof(WCHAR));
      pBuff += pToken[2];
      pToken += 2;
      break;

    case FMT_STR_COPY_SPACE:
    case FMT_STR_COPY_SKIP:
      dwCount = pToken[1];
      if (*pToken == FMT_STR_COPY_SPACE && blanks_first > 0)
      {
        TRACE("insert %d initial spaces\n", blanks_first);
        while (dwCount > 0 && blanks_first > 0)
        {
          *pBuff++ = ' ';
          dwCount--;
          blanks_first--;
        }
      }
      TRACE("copy %d chars%s\n", dwCount,
            *pToken == FMT_STR_COPY_SPACE ? " with space" :"");
      while (dwCount > 0 && *pSrc)
      {
        if (bUpper)
          *pBuff++ = toupperW(*pSrc);
        else
          *pBuff++ = tolowerW(*pSrc);
        dwCount--;
        pSrc++;
      }
      if (*pToken == FMT_STR_COPY_SPACE && dwCount > 0)
      {
        TRACE("insert %d spaces\n", dwCount);
        while (dwCount-- > 0)
          *pBuff++ = ' ';
      }
      pToken++;
      break;

    default:
      ERR("Unknown token 0x%02x!\n", *pToken);
      hRes = E_INVALIDARG;
      goto VARIANT_FormatString_Exit;
    }
    pToken++;
  }

VARIANT_FormatString_Exit:
  /* Copy out any remaining chars */
  while (*pSrc)
  {
    if (bUpper)
      *pBuff++ = toupperW(*pSrc);
    else
      *pBuff++ = tolowerW(*pSrc);
    pSrc++;
  }
  VariantClear(&vStr);
  *pBuff = '\0';
  TRACE("buff is %s\n", debugstr_w(buff));
  if (SUCCEEDED(hRes))
  {
    *pbstrOut = SysAllocString(buff);
    if (!*pbstrOut)
      hRes = E_OUTOFMEMORY;
  }
  return hRes;
}

#define NUMBER_VTBITS (VTBIT_I1|VTBIT_UI1|VTBIT_I2|VTBIT_UI2| \
                       VTBIT_I4|VTBIT_UI4|VTBIT_I8|VTBIT_UI8| \
                       VTBIT_R4|VTBIT_R8|VTBIT_CY|VTBIT_DECIMAL| \
2051
                       VTBIT_BOOL|VTBIT_INT|VTBIT_UINT)
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063

/**********************************************************************
 *              VarFormatFromTokens [OLEAUT32.139]
 */
HRESULT WINAPI VarFormatFromTokens(LPVARIANT pVarIn, LPOLESTR lpszFormat,
                                   LPBYTE rgbTok, ULONG dwFlags,
                                   BSTR *pbstrOut, LCID lcid)
{
  FMT_SHORT_HEADER *header = (FMT_SHORT_HEADER *)rgbTok;
  VARIANT vTmp;
  HRESULT hres;

2064
  TRACE("(%p,%s,%p,%x,%p,0x%08x)\n", pVarIn, debugstr_w(lpszFormat),
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
          rgbTok, dwFlags, pbstrOut, lcid);

  if (!pbstrOut)
    return E_INVALIDARG;

  *pbstrOut = NULL;

  if (!pVarIn || !rgbTok)
    return E_INVALIDARG;

2075 2076 2077
  if (V_VT(pVarIn) == VT_NULL)
    return S_OK;

2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150
  if (*rgbTok == FMT_TO_STRING || header->type == FMT_TYPE_GENERAL)
  {
    /* According to MSDN, general format acts somewhat like the 'Str'
     * function in Visual Basic.
     */
VarFormatFromTokens_AsStr:
    V_VT(&vTmp) = VT_EMPTY;
    hres = VariantChangeTypeEx(&vTmp, pVarIn, lcid, dwFlags, VT_BSTR);
    *pbstrOut = V_BSTR(&vTmp);
  }
  else
  {
    if (header->type == FMT_TYPE_NUMBER ||
        (header->type == FMT_TYPE_UNKNOWN && ((1 << V_TYPE(pVarIn)) & NUMBER_VTBITS)))
    {
      hres = VARIANT_FormatNumber(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
    }
    else if (header->type == FMT_TYPE_DATE ||
             (header->type == FMT_TYPE_UNKNOWN && V_TYPE(pVarIn) == VT_DATE))
    {
      hres = VARIANT_FormatDate(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
    }
    else if (header->type == FMT_TYPE_STRING || V_TYPE(pVarIn) == VT_BSTR)
    {
      hres = VARIANT_FormatString(pVarIn, lpszFormat, rgbTok, dwFlags, pbstrOut, lcid);
    }
    else
    {
      ERR("unrecognised format type 0x%02x\n", header->type);
      return E_INVALIDARG;
    }
    /* If the coercion failed, still try to create output, unless the
     * VAR_FORMAT_NOSUBSTITUTE flag is set.
     */
    if ((hres == DISP_E_OVERFLOW || hres == DISP_E_TYPEMISMATCH) &&
        !(dwFlags & VAR_FORMAT_NOSUBSTITUTE))
      goto VarFormatFromTokens_AsStr;
  }

  return hres;
}

/**********************************************************************
 *              VarFormat [OLEAUT32.87]
 *
 * Format a variant from a format string.
 *
 * PARAMS
 *  pVarIn     [I] Variant to format
 *  lpszFormat [I] Format string (see notes)
 *  nFirstDay  [I] First day of the week, (See VarTokenizeFormatString() for details)
 *  nFirstWeek [I] First week of the year (See VarTokenizeFormatString() for details)
 *  dwFlags    [I] Flags for the format (VAR_ flags from "oleauto.h")
 *  pbstrOut   [O] Destination for formatted string.
 *
 * RETURNS
 *  Success: S_OK. pbstrOut contains the formatted value.
 *  Failure: E_INVALIDARG, if any parameter is invalid.
 *           E_OUTOFMEMORY, if enough memory cannot be allocated.
 *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
 *
 * NOTES
 *  - See Variant-Formats for details concerning creating format strings.
 *  - This function uses LOCALE_USER_DEFAULT when calling VarTokenizeFormatString()
 *    and VarFormatFromTokens().
 */
HRESULT WINAPI VarFormat(LPVARIANT pVarIn, LPOLESTR lpszFormat,
                         int nFirstDay, int nFirstWeek, ULONG dwFlags,
                         BSTR *pbstrOut)
{
  BYTE buff[256];
  HRESULT hres;

2151
  TRACE("(%p->(%s%s),%s,%d,%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163
        debugstr_VF(pVarIn), debugstr_w(lpszFormat), nFirstDay, nFirstWeek,
        dwFlags, pbstrOut);

  if (!pbstrOut)
    return E_INVALIDARG;
  *pbstrOut = NULL;

  hres = VarTokenizeFormatString(lpszFormat, buff, sizeof(buff), nFirstDay,
                                 nFirstWeek, LOCALE_USER_DEFAULT, NULL);
  if (SUCCEEDED(hres))
    hres = VarFormatFromTokens(pVarIn, lpszFormat, buff, dwFlags,
                               pbstrOut, LOCALE_USER_DEFAULT);
2164
  TRACE("returning 0x%08x, %s\n", hres, debugstr_w(*pbstrOut));
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
  return hres;
}

/**********************************************************************
 *              VarFormatDateTime [OLEAUT32.97]
 *
 * Format a variant value as a date and/or time.
 *
 * PARAMS
 *  pVarIn    [I] Variant to format
 *  nFormat   [I] Format type (see notes)
 *  dwFlags   [I] Flags for the format (VAR_ flags from "oleauto.h")
 *  pbstrOut  [O] Destination for formatted string.
 *
 * RETURNS
 *  Success: S_OK. pbstrOut contains the formatted value.
 *  Failure: E_INVALIDARG, if any parameter is invalid.
 *           E_OUTOFMEMORY, if enough memory cannot be allocated.
 *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
 *
 * NOTES
 *  This function uses LOCALE_USER_DEFAULT when determining the date format
 *  characters to use.
 *  Possible values for the nFormat parameter are:
 *| Value  Meaning
 *| -----  -------
 *|   0    General date format
 *|   1    Long date format
 *|   2    Short date format
 *|   3    Long time format
 *|   4    Short time format
 */
HRESULT WINAPI VarFormatDateTime(LPVARIANT pVarIn, INT nFormat, ULONG dwFlags, BSTR *pbstrOut)
{
2199
  static WCHAR szEmpty[] = { '\0' };
2200 2201
  const BYTE* lpFmt = NULL;

2202
  TRACE("(%p->(%s%s),%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
        debugstr_VF(pVarIn), nFormat, dwFlags, pbstrOut);

  if (!pVarIn || !pbstrOut || nFormat < 0 || nFormat > 4)
    return E_INVALIDARG;

  switch (nFormat)
  {
  case 0: lpFmt = fmtGeneralDate; break;
  case 1: lpFmt = fmtLongDate; break;
  case 2: lpFmt = fmtShortDate; break;
  case 3: lpFmt = fmtLongTime; break;
  case 4: lpFmt = fmtShortTime; break;
  }
2216
  return VarFormatFromTokens(pVarIn, szEmpty, (BYTE*)lpFmt, dwFlags,
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254
                              pbstrOut, LOCALE_USER_DEFAULT);
}

#define GETLOCALENUMBER(type,field) GetLocaleInfoW(LOCALE_USER_DEFAULT, \
                                                   type|LOCALE_RETURN_NUMBER, \
                                                   (LPWSTR)&numfmt.field, \
                                                   sizeof(numfmt.field)/sizeof(WCHAR))

/**********************************************************************
 *              VarFormatNumber [OLEAUT32.107]
 *
 * Format a variant value as a number.
 *
 * PARAMS
 *  pVarIn    [I] Variant to format
 *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
 *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
 *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
 *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
 *  dwFlags   [I] Currently unused, set to zero
 *  pbstrOut  [O] Destination for formatted string.
 *
 * RETURNS
 *  Success: S_OK. pbstrOut contains the formatted value.
 *  Failure: E_INVALIDARG, if any parameter is invalid.
 *           E_OUTOFMEMORY, if enough memory cannot be allocated.
 *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
 *
 * NOTES
 *  This function uses LOCALE_USER_DEFAULT when determining the number format
 *  characters to use.
 */
HRESULT WINAPI VarFormatNumber(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
                               INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
{
  HRESULT hRet;
  VARIANT vStr;

2255
  TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
        debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping, dwFlags, pbstrOut);

  if (!pVarIn || !pbstrOut || nDigits > 9)
    return E_INVALIDARG;

  *pbstrOut = NULL;

  V_VT(&vStr) = VT_EMPTY;
  hRet = VariantCopyInd(&vStr, pVarIn);

  if (SUCCEEDED(hRet))
2267
    hRet = VariantChangeTypeEx(&vStr, &vStr, LCID_US, 0, VT_BSTR);
2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365

  if (SUCCEEDED(hRet))
  {
    WCHAR buff[256], decimal[8], thousands[8];
    NUMBERFMTW numfmt;

    /* Although MSDN makes it clear that the native versions of these functions
     * are implemented using VarTokenizeFormatString()/VarFormatFromTokens(),
     * using NLS gives us the same result.
     */
    if (nDigits < 0)
      GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
    else
      numfmt.NumDigits = nDigits;

    if (nLeading == -2)
      GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
    else if (nLeading == -1)
      numfmt.LeadingZero = 1;
    else
      numfmt.LeadingZero = 0;

    if (nGrouping == -2)
    {
      WCHAR grouping[16];
      grouping[2] = '\0';
      GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, grouping,
                     sizeof(grouping)/sizeof(WCHAR));
      numfmt.Grouping = grouping[2] == '2' ? 32 : grouping[0] - '0';
    }
    else if (nGrouping == -1)
      numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
    else
      numfmt.Grouping = 0; /* 0 = No grouping */

    if (nParens == -2)
      GETLOCALENUMBER(LOCALE_INEGNUMBER, NegativeOrder);
    else if (nParens == -1)
      numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
    else
      numfmt.NegativeOrder = 1; /* 1 = "-xxx" */

    numfmt.lpDecimalSep = decimal;
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal,
                   sizeof(decimal)/sizeof(WCHAR));
    numfmt.lpThousandSep = thousands;
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, thousands,
                   sizeof(thousands)/sizeof(WCHAR));

    if (GetNumberFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
                         buff, sizeof(buff)/sizeof(WCHAR)))
    {
      *pbstrOut = SysAllocString(buff);
      if (!*pbstrOut)
        hRet = E_OUTOFMEMORY;
    }
    else
      hRet = DISP_E_TYPEMISMATCH;

    SysFreeString(V_BSTR(&vStr));
  }
  return hRet;
}

/**********************************************************************
 *              VarFormatPercent [OLEAUT32.117]
 *
 * Format a variant value as a percentage.
 *
 * PARAMS
 *  pVarIn    [I] Variant to format
 *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
 *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
 *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
 *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
 *  dwFlags   [I] Currently unused, set to zero
 *  pbstrOut  [O] Destination for formatted string.
 *
 * RETURNS
 *  Success: S_OK. pbstrOut contains the formatted value.
 *  Failure: E_INVALIDARG, if any parameter is invalid.
 *           E_OUTOFMEMORY, if enough memory cannot be allocated.
 *           DISP_E_OVERFLOW, if overflow occurs during the conversion.
 *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
 *
 * NOTES
 *  This function uses LOCALE_USER_DEFAULT when determining the number format
 *  characters to use.
 */
HRESULT WINAPI VarFormatPercent(LPVARIANT pVarIn, INT nDigits, INT nLeading, INT nParens,
                                INT nGrouping, ULONG dwFlags, BSTR *pbstrOut)
{
  static const WCHAR szPercent[] = { '%','\0' };
  static const WCHAR szPercentBracket[] = { '%',')','\0' };
  WCHAR buff[256];
  HRESULT hRet;
  VARIANT vDbl;

2366
  TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439
        debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping,
        dwFlags, pbstrOut);

  if (!pVarIn || !pbstrOut || nDigits > 9)
    return E_INVALIDARG;

  *pbstrOut = NULL;

  V_VT(&vDbl) = VT_EMPTY;
  hRet = VariantCopyInd(&vDbl, pVarIn);

  if (SUCCEEDED(hRet))
  {
    hRet = VariantChangeTypeEx(&vDbl, &vDbl, LOCALE_USER_DEFAULT, 0, VT_R8);

    if (SUCCEEDED(hRet))
    {
      if (V_R8(&vDbl) > (R8_MAX / 100.0))
        return DISP_E_OVERFLOW;

      V_R8(&vDbl) *= 100.0;
      hRet = VarFormatNumber(&vDbl, nDigits, nLeading, nParens,
                             nGrouping, dwFlags, pbstrOut);

      if (SUCCEEDED(hRet))
      {
        DWORD dwLen = strlenW(*pbstrOut);
        BOOL bBracket = (*pbstrOut)[dwLen] == ')' ? TRUE : FALSE;

        dwLen -= bBracket;
        memcpy(buff, *pbstrOut, dwLen * sizeof(WCHAR));
        strcpyW(buff + dwLen, bBracket ? szPercentBracket : szPercent);
        SysFreeString(*pbstrOut);
        *pbstrOut = SysAllocString(buff);
        if (!*pbstrOut)
          hRet = E_OUTOFMEMORY;
      }
    }
  }
  return hRet;
}

/**********************************************************************
 *              VarFormatCurrency [OLEAUT32.127]
 *
 * Format a variant value as a currency.
 *
 * PARAMS
 *  pVarIn    [I] Variant to format
 *  nDigits   [I] Number of digits following the decimal point (-1 = user default)
 *  nLeading  [I] Use a leading zero (-2 = user default, -1 = yes, 0 = no)
 *  nParens   [I] Use brackets for values < 0 (-2 = user default, -1 = yes, 0 = no)
 *  nGrouping [I] Use grouping characters (-2 = user default, -1 = yes, 0 = no)
 *  dwFlags   [I] Currently unused, set to zero
 *  pbstrOut  [O] Destination for formatted string.
 *
 * RETURNS
 *  Success: S_OK. pbstrOut contains the formatted value.
 *  Failure: E_INVALIDARG, if any parameter is invalid.
 *           E_OUTOFMEMORY, if enough memory cannot be allocated.
 *           DISP_E_TYPEMISMATCH, if the variant cannot be formatted.
 *
 * NOTES
 *  This function uses LOCALE_USER_DEFAULT when determining the currency format
 *  characters to use.
 */
HRESULT WINAPI VarFormatCurrency(LPVARIANT pVarIn, INT nDigits, INT nLeading,
                                 INT nParens, INT nGrouping, ULONG dwFlags,
                                 BSTR *pbstrOut)
{
  HRESULT hRet;
  VARIANT vStr;

2440
  TRACE("(%p->(%s%s),%d,%d,%d,%d,0x%08x,%p)\n", pVarIn, debugstr_VT(pVarIn),
2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
        debugstr_VF(pVarIn), nDigits, nLeading, nParens, nGrouping, dwFlags, pbstrOut);

  if (!pVarIn || !pbstrOut || nDigits > 9)
    return E_INVALIDARG;

  *pbstrOut = NULL;

  V_VT(&vStr) = VT_EMPTY;
  hRet = VariantCopyInd(&vStr, pVarIn);

  if (SUCCEEDED(hRet))
    hRet = VariantChangeTypeEx(&vStr, &vStr, LOCALE_USER_DEFAULT, 0, VT_BSTR);

  if (SUCCEEDED(hRet))
  {
    WCHAR buff[256], decimal[8], thousands[8], currency[8];
    CURRENCYFMTW numfmt;

    if (nDigits < 0)
      GETLOCALENUMBER(LOCALE_IDIGITS, NumDigits);
    else
      numfmt.NumDigits = nDigits;

    if (nLeading == -2)
      GETLOCALENUMBER(LOCALE_ILZERO, LeadingZero);
    else if (nLeading == -1)
      numfmt.LeadingZero = 1;
    else
      numfmt.LeadingZero = 0;

    if (nGrouping == -2)
    {
      WCHAR nGrouping[16];
      nGrouping[2] = '\0';
      GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, nGrouping,
                     sizeof(nGrouping)/sizeof(WCHAR));
      numfmt.Grouping = nGrouping[2] == '2' ? 32 : nGrouping[0] - '0';
    }
    else if (nGrouping == -1)
      numfmt.Grouping = 3; /* 3 = "n,nnn.nn" */
    else
      numfmt.Grouping = 0; /* 0 = No grouping */

    if (nParens == -2)
      GETLOCALENUMBER(LOCALE_INEGCURR, NegativeOrder);
    else if (nParens == -1)
      numfmt.NegativeOrder = 0; /* 0 = "(xxx)" */
    else
      numfmt.NegativeOrder = 1; /* 1 = "-xxx" */

    GETLOCALENUMBER(LOCALE_ICURRENCY, PositiveOrder);

    numfmt.lpDecimalSep = decimal;
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, decimal,
                   sizeof(decimal)/sizeof(WCHAR));
    numfmt.lpThousandSep = thousands;
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, thousands,
                   sizeof(thousands)/sizeof(WCHAR));
    numfmt.lpCurrencySymbol = currency;
    GetLocaleInfoW(LOCALE_USER_DEFAULT, LOCALE_SDECIMAL, currency,
                   sizeof(currency)/sizeof(WCHAR));

    /* use NLS as per VarFormatNumber() */
    if (GetCurrencyFormatW(LOCALE_USER_DEFAULT, 0, V_BSTR(&vStr), &numfmt,
                           buff, sizeof(buff)/sizeof(WCHAR)))
    {
      *pbstrOut = SysAllocString(buff);
      if (!*pbstrOut)
        hRet = E_OUTOFMEMORY;
    }
    else
      hRet = DISP_E_TYPEMISMATCH;

    SysFreeString(V_BSTR(&vStr));
  }
  return hRet;
}
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543

/**********************************************************************
 *              VarMonthName [OLEAUT32.129]
 *
 * Print the specified month as localized name.
 *
 * PARAMS
 *  iMonth    [I] month number 1..12
 *  fAbbrev   [I] 0 - full name, !0 - abbreviated name
 *  dwFlags   [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
 *  pbstrOut  [O] Destination for month name
 *
 * RETURNS
 *  Success: S_OK. pbstrOut contains the name.
 *  Failure: E_INVALIDARG, if any parameter is invalid.
 *           E_OUTOFMEMORY, if enough memory cannot be allocated.
 */
HRESULT WINAPI VarMonthName(INT iMonth, INT fAbbrev, ULONG dwFlags, BSTR *pbstrOut)
{
  DWORD localeValue;
  INT size;

  if ((iMonth < 1)  || (iMonth > 12))
    return E_INVALIDARG;

  if (dwFlags)
2544
    FIXME("Does not support dwFlags 0x%x, ignoring.\n", dwFlags);
2545 2546 2547 2548 2549 2550 2551 2552

  if (fAbbrev)
	localeValue = LOCALE_SABBREVMONTHNAME1 + iMonth - 1;
  else
	localeValue = LOCALE_SMONTHNAME1 + iMonth - 1;

  size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, NULL, 0);
  if (!size) {
2553
    ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
2554
    return HRESULT_FROM_WIN32(GetLastError());
2555
  }
2556 2557
  *pbstrOut = SysAllocStringLen(NULL,size - 1);
  if (!*pbstrOut)
2558
    return E_OUTOFMEMORY;
2559
  size = GetLocaleInfoW(LOCALE_USER_DEFAULT,localeValue, *pbstrOut, size);
2560
  if (!size) {
2561
    ERR("GetLocaleInfo of 0x%x failed in 2nd stage?!\n", localeValue);
2562
    SysFreeString(*pbstrOut);
2563
    return HRESULT_FROM_WIN32(GetLastError());
2564 2565 2566
  }
  return S_OK;
}
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636

/**********************************************************************
 *              VarWeekdayName [OLEAUT32.129]
 *
 * Print the specified weekday as localized name.
 *
 * PARAMS
 *  iWeekday  [I] day of week, 1..7, 1="the first day of the week"
 *  fAbbrev   [I] 0 - full name, !0 - abbreviated name
 *  iFirstDay [I] first day of week,
 *                0=system default, 1=Sunday, 2=Monday, .. (contrary to MSDN)
 *  dwFlags   [I] flag stuff. only VAR_CALENDAR_HIJRI possible.
 *  pbstrOut  [O] Destination for weekday name.
 *
 * RETURNS
 *  Success: S_OK, pbstrOut contains the name.
 *  Failure: E_INVALIDARG, if any parameter is invalid.
 *           E_OUTOFMEMORY, if enough memory cannot be allocated.
 */
HRESULT WINAPI VarWeekdayName(INT iWeekday, INT fAbbrev, INT iFirstDay,
                              ULONG dwFlags, BSTR *pbstrOut)
{
  DWORD localeValue;
  INT size;

  /* Windows XP oleaut32.dll doesn't allow iWekday==0, contrary to MSDN */
  if (iWeekday < 1 || iWeekday > 7)
    return E_INVALIDARG;
  if (iFirstDay < 0 || iFirstDay > 7)
    return E_INVALIDARG;
  if (!pbstrOut)
    return E_INVALIDARG;

  if (dwFlags)
    FIXME("Does not support dwFlags 0x%x, ignoring.\n", dwFlags);

  /* If we have to use the default firstDay, find which one it is */
  if (iFirstDay == 0) {
    DWORD firstDay;
    localeValue = LOCALE_RETURN_NUMBER | LOCALE_IFIRSTDAYOFWEEK;
    size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue,
                          (LPWSTR)&firstDay, sizeof(firstDay) / sizeof(WCHAR));
    if (!size) {
      ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
      return HRESULT_FROM_WIN32(GetLastError());
    }
    iFirstDay = firstDay + 2;
  }

  /* Determine what we need to return */
  localeValue = fAbbrev ? LOCALE_SABBREVDAYNAME1 : LOCALE_SDAYNAME1;
  localeValue += (7 + iWeekday - 1 + iFirstDay - 2) % 7;

  /* Determine the size of the data, allocate memory and retrieve the data */
  size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue, NULL, 0);
  if (!size) {
    ERR("GetLocaleInfo 0x%x failed.\n", localeValue);
    return HRESULT_FROM_WIN32(GetLastError());
  }
  *pbstrOut = SysAllocStringLen(NULL, size - 1);
  if (!*pbstrOut)
    return E_OUTOFMEMORY;
  size = GetLocaleInfoW(LOCALE_USER_DEFAULT, localeValue, *pbstrOut, size);
  if (!size) {
    ERR("GetLocaleInfo 0x%x failed in 2nd stage?!\n", localeValue);
    SysFreeString(*pbstrOut);
    return HRESULT_FROM_WIN32(GetLastError());
  }
  return S_OK;
}