]> git.saurik.com Git - wxWidgets.git/blob - src/common/wxprintf.cpp
Patch from Bo, adapt generic code to new API, add GetItemRect and HitTest
[wxWidgets.git] / src / common / wxprintf.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/wxprintf.cpp
3 // Purpose: wxWidgets wxPrintf() implementation
4 // Author: Ove Kaven
5 // Modified by: Ron Lee, Francesco Montorsi
6 // Created: 09/04/99
7 // RCS-ID: $Id$
8 // Copyright: (c) wxWidgets copyright
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ===========================================================================
13 // headers, declarations, constants
14 // ===========================================================================
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20 #pragma hdrstop
21 #endif
22
23 #include "wx/crt.h"
24
25 #include <string.h>
26
27 #ifndef WX_PRECOMP
28 #include "wx/string.h"
29 #include "wx/hash.h"
30 #include "wx/utils.h" // for wxMin and wxMax
31 #include "wx/log.h"
32 #endif
33
34 #if defined(__MWERKS__) && __MSL__ >= 0x6000
35 namespace std {}
36 using namespace std ;
37 #endif
38
39
40 // ============================================================================
41 // printf() implementation
42 // ============================================================================
43
44 // special test mode: define all functions below even if we don't really need
45 // them to be able to test them
46 #ifdef wxTEST_PRINTF
47 #undef wxCRT_VsnprintfW
48 #undef wxCRT_VsnprintfA
49 #endif
50
51 // ----------------------------------------------------------------------------
52 // implement [v]snprintf() if the system doesn't provide a safe one
53 // or if the system's one does not support positional parameters
54 // (very useful for i18n purposes)
55 // ----------------------------------------------------------------------------
56
57 // ----------------------------------------------------------------------------
58 // common code for both ANSI and Unicode versions
59 // ----------------------------------------------------------------------------
60
61 #if !defined(wxCRT_VsnprintfW) || !defined(wxCRT_VsnprintfA)
62
63 // some limits of our implementation
64 #define wxMAX_SVNPRINTF_ARGUMENTS 64
65 #define wxMAX_SVNPRINTF_FLAGBUFFER_LEN 32
66 #define wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN 512
67
68 // prefer snprintf over sprintf
69 #if defined(__VISUALC__) || \
70 (defined(__BORLANDC__) && __BORLANDC__ >= 0x540)
71 #define system_sprintf(buff, max, flags, data) \
72 ::_snprintf(buff, max, flags, data)
73 #elif defined(HAVE_SNPRINTF)
74 #define system_sprintf(buff, max, flags, data) \
75 ::snprintf(buff, max, flags, data)
76 #else // NB: at least sprintf() should always be available
77 // since 'max' is not used in this case, wxVsnprintf() should always
78 // ensure that 'buff' is big enough for all common needs
79 // (see wxMAX_SVNPRINTF_FLAGBUFFER_LEN and wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN)
80 #define system_sprintf(buff, max, flags, data) \
81 ::sprintf(buff, flags, data)
82
83 #define SYSTEM_SPRINTF_IS_UNSAFE
84 #endif
85
86 namespace
87 {
88
89 // the conversion specifiers accepted by wxCRT_VsnprintfW
90 enum wxPrintfArgType {
91 wxPAT_INVALID = -1,
92
93 wxPAT_INT, // %d, %i, %o, %u, %x, %X
94 wxPAT_LONGINT, // %ld, etc
95 #ifdef wxLongLong_t
96 wxPAT_LONGLONGINT, // %Ld, etc
97 #endif
98 wxPAT_SIZET, // %Zd, etc
99
100 wxPAT_DOUBLE, // %e, %E, %f, %g, %G
101 wxPAT_LONGDOUBLE, // %le, etc
102
103 wxPAT_POINTER, // %p
104
105 wxPAT_CHAR, // %hc (in ANSI mode: %c, too)
106 wxPAT_WCHAR, // %lc (in Unicode mode: %c, too)
107
108 wxPAT_PCHAR, // %s (related to a char *)
109 wxPAT_PWCHAR, // %s (related to a wchar_t *)
110
111 wxPAT_NINT, // %n
112 wxPAT_NSHORTINT, // %hn
113 wxPAT_NLONGINT // %ln
114 };
115
116 // an argument passed to wxCRT_VsnprintfW
117 typedef union {
118 int pad_int; // %d, %i, %o, %u, %x, %X
119 long int pad_longint; // %ld, etc
120 #ifdef wxLongLong_t
121 wxLongLong_t pad_longlongint; // %Ld, etc
122 #endif
123 size_t pad_sizet; // %Zd, etc
124
125 double pad_double; // %e, %E, %f, %g, %G
126 long double pad_longdouble; // %le, etc
127
128 void *pad_pointer; // %p
129
130 char pad_char; // %hc (in ANSI mode: %c, too)
131 wchar_t pad_wchar; // %lc (in Unicode mode: %c, too)
132
133 void *pad_str; // %s
134
135 int *pad_nint; // %n
136 short int *pad_nshortint; // %hn
137 long int *pad_nlongint; // %ln
138 } wxPrintfArg;
139
140 // helper for converting string into either char* or wchar_t* dependening
141 // on the type of wxPrintfConvSpec<T> instantiation:
142 template<typename CharType> struct wxPrintfStringHelper {};
143
144 template<> struct wxPrintfStringHelper<char>
145 {
146 typedef const wxWX2MBbuf ConvertedType;
147 static ConvertedType Convert(const wxString& s) { return s.mb_str(); }
148 };
149
150 template<> struct wxPrintfStringHelper<wchar_t>
151 {
152 typedef const wxWX2WCbuf ConvertedType;
153 static ConvertedType Convert(const wxString& s) { return s.wc_str(); }
154 };
155
156
157 // Contains parsed data relative to a conversion specifier given to
158 // wxCRT_VsnprintfW and parsed from the format string
159 // NOTE: in C++ there is almost no difference between struct & classes thus
160 // there is no performance gain by using a struct here...
161 template<typename CharType>
162 class wxPrintfConvSpec
163 {
164 public:
165
166 // the position of the argument relative to this conversion specifier
167 size_t m_pos;
168
169 // the type of this conversion specifier
170 wxPrintfArgType m_type;
171
172 // the minimum and maximum width
173 // when one of this var is set to -1 it means: use the following argument
174 // in the stack as minimum/maximum width for this conversion specifier
175 int m_nMinWidth, m_nMaxWidth;
176
177 // does the argument need to the be aligned to left ?
178 bool m_bAlignLeft;
179
180 // pointer to the '%' of this conversion specifier in the format string
181 // NOTE: this points somewhere in the string given to the Parse() function -
182 // it's task of the caller ensure that memory is still valid !
183 const CharType *m_pArgPos;
184
185 // pointer to the last character of this conversion specifier in the
186 // format string
187 // NOTE: this points somewhere in the string given to the Parse() function -
188 // it's task of the caller ensure that memory is still valid !
189 const CharType *m_pArgEnd;
190
191 // a little buffer where formatting flags like #+\.hlqLZ are stored by Parse()
192 // for use in Process()
193 // NB: even if this buffer is used only for numeric conversion specifiers and
194 // thus could be safely declared as a char[] buffer, we want it to be wchar_t
195 // so that in Unicode builds we can avoid to convert its contents to Unicode
196 // chars when copying it in user's buffer.
197 char m_szFlags[wxMAX_SVNPRINTF_FLAGBUFFER_LEN];
198
199
200 public:
201
202 // we don't declare this as a constructor otherwise it would be called
203 // automatically and we don't want this: to be optimized, wxCRT_VsnprintfW
204 // calls this function only on really-used instances of this class.
205 void Init();
206
207 // Parses the first conversion specifier in the given string, which must
208 // begin with a '%'. Returns false if the first '%' does not introduce a
209 // (valid) conversion specifier and thus should be ignored.
210 bool Parse(const CharType *format);
211
212 // Process this conversion specifier and puts the result in the given
213 // buffer. Returns the number of characters written in 'buf' or -1 if
214 // there's not enough space.
215 int Process(CharType *buf, size_t lenMax, wxPrintfArg *p, size_t written);
216
217 // Loads the argument of this conversion specifier from given va_list.
218 bool LoadArg(wxPrintfArg *p, va_list &argptr);
219
220 private:
221 // An helper function of LoadArg() which is used to handle the '*' flag
222 void ReplaceAsteriskWith(int w);
223 };
224
225 template<typename CharType>
226 void wxPrintfConvSpec<CharType>::Init()
227 {
228 m_nMinWidth = 0;
229 m_nMaxWidth = 0xFFFF;
230 m_pos = 0;
231 m_bAlignLeft = false;
232 m_pArgPos = m_pArgEnd = NULL;
233 m_type = wxPAT_INVALID;
234
235 // this character will never be removed from m_szFlags array and
236 // is important when calling sprintf() in wxPrintfConvSpec::Process() !
237 m_szFlags[0] = '%';
238 }
239
240 template<typename CharType>
241 bool wxPrintfConvSpec<CharType>::Parse(const CharType *format)
242 {
243 bool done = false;
244
245 // temporary parse data
246 size_t flagofs = 1;
247 bool in_prec, // true if we found the dot in some previous iteration
248 prec_dot; // true if the dot has been already added to m_szFlags
249 int ilen = 0;
250
251 m_bAlignLeft = in_prec = prec_dot = false;
252 m_pArgPos = m_pArgEnd = format;
253 do
254 {
255 #define CHECK_PREC \
256 if (in_prec && !prec_dot) \
257 { \
258 m_szFlags[flagofs++] = '.'; \
259 prec_dot = true; \
260 }
261
262 // what follows '%'?
263 const CharType ch = *(++m_pArgEnd);
264 switch ( ch )
265 {
266 case wxT('\0'):
267 return false; // not really an argument
268
269 case wxT('%'):
270 return false; // not really an argument
271
272 case wxT('#'):
273 case wxT('0'):
274 case wxT(' '):
275 case wxT('+'):
276 case wxT('\''):
277 CHECK_PREC
278 m_szFlags[flagofs++] = char(ch);
279 break;
280
281 case wxT('-'):
282 CHECK_PREC
283 m_bAlignLeft = true;
284 m_szFlags[flagofs++] = char(ch);
285 break;
286
287 case wxT('.'):
288 CHECK_PREC
289 in_prec = true;
290 prec_dot = false;
291 m_nMaxWidth = 0;
292 // dot will be auto-added to m_szFlags if non-negative
293 // number follows
294 break;
295
296 case wxT('h'):
297 ilen = -1;
298 CHECK_PREC
299 m_szFlags[flagofs++] = char(ch);
300 break;
301
302 case wxT('l'):
303 // NB: it's safe to use flagofs-1 as flagofs always start from 1
304 if (m_szFlags[flagofs-1] == 'l') // 'll' modifier is the same as 'L' or 'q'
305 ilen = 2;
306 else
307 ilen = 1;
308 CHECK_PREC
309 m_szFlags[flagofs++] = char(ch);
310 break;
311
312 case wxT('q'):
313 case wxT('L'):
314 ilen = 2;
315 CHECK_PREC
316 m_szFlags[flagofs++] = char(ch);
317 break;
318 #ifdef __WXMSW__
319 // under Windows we support the special '%I64' notation as longlong
320 // integer conversion specifier for MSVC compatibility
321 // (it behaves exactly as '%lli' or '%Li' or '%qi')
322 case wxT('I'):
323 if (*(m_pArgEnd+1) != wxT('6') ||
324 *(m_pArgEnd+2) != wxT('4'))
325 return false; // bad format
326
327 m_pArgEnd++;
328 m_pArgEnd++;
329
330 ilen = 2;
331 CHECK_PREC
332 m_szFlags[flagofs++] = char(ch);
333 m_szFlags[flagofs++] = '6';
334 m_szFlags[flagofs++] = '4';
335 break;
336 #endif // __WXMSW__
337
338 case wxT('Z'):
339 ilen = 3;
340 CHECK_PREC
341 m_szFlags[flagofs++] = char(ch);
342 break;
343
344 case wxT('*'):
345 if (in_prec)
346 {
347 CHECK_PREC
348
349 // tell Process() to use the next argument
350 // in the stack as maxwidth...
351 m_nMaxWidth = -1;
352 }
353 else
354 {
355 // tell Process() to use the next argument
356 // in the stack as minwidth...
357 m_nMinWidth = -1;
358 }
359
360 // save the * in our formatting buffer...
361 // will be replaced later by Process()
362 m_szFlags[flagofs++] = char(ch);
363 break;
364
365 case wxT('1'): case wxT('2'): case wxT('3'):
366 case wxT('4'): case wxT('5'): case wxT('6'):
367 case wxT('7'): case wxT('8'): case wxT('9'):
368 {
369 int len = 0;
370 CHECK_PREC
371 while ( (*m_pArgEnd >= CharType('0')) &&
372 (*m_pArgEnd <= CharType('9')) )
373 {
374 m_szFlags[flagofs++] = char(*m_pArgEnd);
375 len = len*10 + (*m_pArgEnd - wxT('0'));
376 m_pArgEnd++;
377 }
378
379 if (in_prec)
380 m_nMaxWidth = len;
381 else
382 m_nMinWidth = len;
383
384 m_pArgEnd--; // the main loop pre-increments n again
385 }
386 break;
387
388 case wxT('$'): // a positional parameter (e.g. %2$s) ?
389 {
390 if (m_nMinWidth <= 0)
391 break; // ignore this formatting flag as no
392 // numbers are preceding it
393
394 // remove from m_szFlags all digits previously added
395 do {
396 flagofs--;
397 } while (m_szFlags[flagofs] >= '1' &&
398 m_szFlags[flagofs] <= '9');
399
400 // re-adjust the offset making it point to the
401 // next free char of m_szFlags
402 flagofs++;
403
404 m_pos = m_nMinWidth;
405 m_nMinWidth = 0;
406 }
407 break;
408
409 case wxT('d'):
410 case wxT('i'):
411 case wxT('o'):
412 case wxT('u'):
413 case wxT('x'):
414 case wxT('X'):
415 CHECK_PREC
416 m_szFlags[flagofs++] = char(ch);
417 m_szFlags[flagofs] = '\0';
418 if (ilen == 0)
419 m_type = wxPAT_INT;
420 else if (ilen == -1)
421 // NB: 'short int' value passed through '...'
422 // is promoted to 'int', so we have to get
423 // an int from stack even if we need a short
424 m_type = wxPAT_INT;
425 else if (ilen == 1)
426 m_type = wxPAT_LONGINT;
427 else if (ilen == 2)
428 #ifdef wxLongLong_t
429 m_type = wxPAT_LONGLONGINT;
430 #else // !wxLongLong_t
431 m_type = wxPAT_LONGINT;
432 #endif // wxLongLong_t/!wxLongLong_t
433 else if (ilen == 3)
434 m_type = wxPAT_SIZET;
435 done = true;
436 break;
437
438 case wxT('e'):
439 case wxT('E'):
440 case wxT('f'):
441 case wxT('g'):
442 case wxT('G'):
443 CHECK_PREC
444 m_szFlags[flagofs++] = char(ch);
445 m_szFlags[flagofs] = '\0';
446 if (ilen == 2)
447 m_type = wxPAT_LONGDOUBLE;
448 else
449 m_type = wxPAT_DOUBLE;
450 done = true;
451 break;
452
453 case wxT('p'):
454 m_type = wxPAT_POINTER;
455 m_szFlags[flagofs++] = char(ch);
456 m_szFlags[flagofs] = '\0';
457 done = true;
458 break;
459
460 case wxT('c'):
461 if (ilen == -1)
462 {
463 // in Unicode mode %hc == ANSI character
464 // and in ANSI mode, %hc == %c == ANSI...
465 m_type = wxPAT_CHAR;
466 }
467 else if (ilen == 1)
468 {
469 // in ANSI mode %lc == Unicode character
470 // and in Unicode mode, %lc == %c == Unicode...
471 m_type = wxPAT_WCHAR;
472 }
473 else
474 {
475 #if wxUSE_UNICODE
476 // in Unicode mode, %c == Unicode character
477 m_type = wxPAT_WCHAR;
478 #else
479 // in ANSI mode, %c == ANSI character
480 m_type = wxPAT_CHAR;
481 #endif
482 }
483 done = true;
484 break;
485
486 case wxT('s'):
487 if (ilen == -1)
488 {
489 // Unicode mode wx extension: we'll let %hs mean non-Unicode
490 // strings (when in ANSI mode, %s == %hs == ANSI string)
491 m_type = wxPAT_PCHAR;
492 }
493 else if (ilen == 1)
494 {
495 // in Unicode mode, %ls == %s == Unicode string
496 // in ANSI mode, %ls == Unicode string
497 m_type = wxPAT_PWCHAR;
498 }
499 else
500 {
501 #if wxUSE_UNICODE
502 m_type = wxPAT_PWCHAR;
503 #else
504 m_type = wxPAT_PCHAR;
505 #endif
506 }
507 done = true;
508 break;
509
510 case wxT('n'):
511 if (ilen == 0)
512 m_type = wxPAT_NINT;
513 else if (ilen == -1)
514 m_type = wxPAT_NSHORTINT;
515 else if (ilen >= 1)
516 m_type = wxPAT_NLONGINT;
517 done = true;
518 break;
519
520 default:
521 // bad format, don't consider this an argument;
522 // leave it unchanged
523 return false;
524 }
525
526 if (flagofs == wxMAX_SVNPRINTF_FLAGBUFFER_LEN)
527 {
528 wxLogDebug(wxT("Too many flags specified for a single conversion specifier!"));
529 return false;
530 }
531 }
532 while (!done);
533
534 return true; // parsing was successful
535 }
536
537 template<typename CharType>
538 void wxPrintfConvSpec<CharType>::ReplaceAsteriskWith(int width)
539 {
540 char temp[wxMAX_SVNPRINTF_FLAGBUFFER_LEN];
541
542 // find the first * in our flag buffer
543 char *pwidth = strchr(m_szFlags, '*');
544 wxCHECK_RET(pwidth, _T("field width must be specified"));
545
546 // save what follows the * (the +1 is to skip the asterisk itself!)
547 strcpy(temp, pwidth+1);
548 if (width < 0)
549 {
550 pwidth[0] = wxT('-');
551 pwidth++;
552 }
553
554 // replace * with the actual integer given as width
555 #ifndef SYSTEM_SPRINTF_IS_UNSAFE
556 int maxlen = (m_szFlags + wxMAX_SVNPRINTF_FLAGBUFFER_LEN - pwidth) /
557 sizeof(*m_szFlags);
558 #endif
559 int offset = system_sprintf(pwidth, maxlen, "%d", abs(width));
560
561 // restore after the expanded * what was following it
562 strcpy(pwidth+offset, temp);
563 }
564
565 template<typename CharType>
566 bool wxPrintfConvSpec<CharType>::LoadArg(wxPrintfArg *p, va_list &argptr)
567 {
568 // did the '*' width/precision specifier was used ?
569 if (m_nMaxWidth == -1)
570 {
571 // take the maxwidth specifier from the stack
572 m_nMaxWidth = va_arg(argptr, int);
573 if (m_nMaxWidth < 0)
574 m_nMaxWidth = 0;
575 else
576 ReplaceAsteriskWith(m_nMaxWidth);
577 }
578
579 if (m_nMinWidth == -1)
580 {
581 // take the minwidth specifier from the stack
582 m_nMinWidth = va_arg(argptr, int);
583
584 ReplaceAsteriskWith(m_nMinWidth);
585 if (m_nMinWidth < 0)
586 {
587 m_bAlignLeft = !m_bAlignLeft;
588 m_nMinWidth = -m_nMinWidth;
589 }
590 }
591
592 switch (m_type) {
593 case wxPAT_INT:
594 p->pad_int = va_arg(argptr, int);
595 break;
596 case wxPAT_LONGINT:
597 p->pad_longint = va_arg(argptr, long int);
598 break;
599 #ifdef wxLongLong_t
600 case wxPAT_LONGLONGINT:
601 p->pad_longlongint = va_arg(argptr, wxLongLong_t);
602 break;
603 #endif // wxLongLong_t
604 case wxPAT_SIZET:
605 p->pad_sizet = va_arg(argptr, size_t);
606 break;
607 case wxPAT_DOUBLE:
608 p->pad_double = va_arg(argptr, double);
609 break;
610 case wxPAT_LONGDOUBLE:
611 p->pad_longdouble = va_arg(argptr, long double);
612 break;
613 case wxPAT_POINTER:
614 p->pad_pointer = va_arg(argptr, void *);
615 break;
616
617 case wxPAT_CHAR:
618 p->pad_char = (char)va_arg(argptr, int); // char is promoted to int when passed through '...'
619 break;
620 case wxPAT_WCHAR:
621 p->pad_wchar = (wchar_t)va_arg(argptr, int); // char is promoted to int when passed through '...'
622 break;
623
624 case wxPAT_PCHAR:
625 case wxPAT_PWCHAR:
626 p->pad_str = va_arg(argptr, void *);
627 break;
628
629 case wxPAT_NINT:
630 p->pad_nint = va_arg(argptr, int *);
631 break;
632 case wxPAT_NSHORTINT:
633 p->pad_nshortint = va_arg(argptr, short int *);
634 break;
635 case wxPAT_NLONGINT:
636 p->pad_nlongint = va_arg(argptr, long int *);
637 break;
638
639 case wxPAT_INVALID:
640 default:
641 return false;
642 }
643
644 return true; // loading was successful
645 }
646
647 template<typename CharType>
648 int wxPrintfConvSpec<CharType>::Process(CharType *buf, size_t lenMax, wxPrintfArg *p, size_t written)
649 {
650 // buffer to avoid dynamic memory allocation each time for small strings;
651 // note that this buffer is used only to hold results of number formatting,
652 // %s directly writes user's string in buf, without using szScratch
653 char szScratch[wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN];
654 size_t lenScratch = 0, lenCur = 0;
655
656 #define APPEND_CH(ch) \
657 { \
658 if ( lenCur == lenMax ) \
659 return -1; \
660 \
661 buf[lenCur++] = ch; \
662 }
663
664 switch ( m_type )
665 {
666 case wxPAT_INT:
667 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_int);
668 break;
669
670 case wxPAT_LONGINT:
671 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_longint);
672 break;
673
674 #ifdef wxLongLong_t
675 case wxPAT_LONGLONGINT:
676 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_longlongint);
677 break;
678 #endif // SIZEOF_LONG_LONG
679
680 case wxPAT_SIZET:
681 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_sizet);
682 break;
683
684 case wxPAT_LONGDOUBLE:
685 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_longdouble);
686 break;
687
688 case wxPAT_DOUBLE:
689 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_double);
690 break;
691
692 case wxPAT_POINTER:
693 lenScratch = system_sprintf(szScratch, wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN, m_szFlags, p->pad_pointer);
694 break;
695
696 case wxPAT_CHAR:
697 case wxPAT_WCHAR:
698 {
699 wxUniChar ch;
700 if (m_type == wxPAT_CHAR)
701 ch = p->pad_char;
702 else // m_type == wxPAT_WCHAR
703 ch = p->pad_wchar;
704
705 CharType val = ch;
706
707 size_t i;
708
709 if (!m_bAlignLeft)
710 for (i = 1; i < (size_t)m_nMinWidth; i++)
711 APPEND_CH(_T(' '));
712
713 APPEND_CH(val);
714
715 if (m_bAlignLeft)
716 for (i = 1; i < (size_t)m_nMinWidth; i++)
717 APPEND_CH(_T(' '));
718 }
719 break;
720
721 case wxPAT_PCHAR:
722 case wxPAT_PWCHAR:
723 {
724 wxArgNormalizedString arg(p->pad_str);
725 wxString s = arg;
726
727 if ( !arg.IsValid() && m_nMaxWidth >= 6 )
728 s = wxT("(null)");
729
730 typename wxPrintfStringHelper<CharType>::ConvertedType strbuf(
731 wxPrintfStringHelper<CharType>::Convert(s));
732
733 // at this point we are sure that m_nMaxWidth is positive or
734 // null (see top of wxPrintfConvSpec::LoadArg)
735 int len = wxMin((unsigned int)m_nMaxWidth, wxStrlen(strbuf));
736
737 int i;
738
739 if (!m_bAlignLeft)
740 {
741 for (i = len; i < m_nMinWidth; i++)
742 APPEND_CH(_T(' '));
743 }
744
745 len = wxMin((unsigned int)len, lenMax-lenCur);
746 wxStrncpy(buf+lenCur, strbuf, len);
747 lenCur += len;
748
749 if (m_bAlignLeft)
750 {
751 for (i = len; i < m_nMinWidth; i++)
752 APPEND_CH(_T(' '));
753 }
754 }
755 break;
756
757 case wxPAT_NINT:
758 *p->pad_nint = written;
759 break;
760
761 case wxPAT_NSHORTINT:
762 *p->pad_nshortint = (short int)written;
763 break;
764
765 case wxPAT_NLONGINT:
766 *p->pad_nlongint = written;
767 break;
768
769 case wxPAT_INVALID:
770 default:
771 return -1;
772 }
773
774 // if we used system's sprintf() then we now need to append the s_szScratch
775 // buffer to the given one...
776 switch (m_type)
777 {
778 case wxPAT_INT:
779 case wxPAT_LONGINT:
780 #ifdef wxLongLong_t
781 case wxPAT_LONGLONGINT:
782 #endif
783 case wxPAT_SIZET:
784 case wxPAT_LONGDOUBLE:
785 case wxPAT_DOUBLE:
786 case wxPAT_POINTER:
787 wxASSERT(lenScratch < wxMAX_SVNPRINTF_SCRATCHBUFFER_LEN);
788 // NB: 1) we can compare lenMax (for CharType*, i.e. possibly
789 // wchar_t*) with lenScratch (char*) because this code is
790 // formatting integers and that will have the same length
791 // even in UTF-8 (the only case when char* length may be
792 // more than wchar_t* length of the same string)
793 // 2) wxStrncpy converts the 2nd argument to 1st argument's
794 // type transparently if their types differ, so this code
795 // works for both instantiations
796 if (lenMax < lenScratch)
797 {
798 // fill output buffer and then return -1
799 wxStrncpy(buf, szScratch, lenMax);
800 return -1;
801 }
802 wxStrncpy(buf, szScratch, lenScratch);
803 lenCur += lenScratch;
804 break;
805
806 default:
807 break; // all other cases were completed previously
808 }
809
810 return lenCur;
811 }
812
813 // Copy chars from source to dest converting '%%' to '%'. Takes at most maxIn
814 // chars from source and write at most outMax chars to dest, returns the
815 // number of chars actually written. Does not treat null specially.
816 template<typename CharType>
817 static int wxCopyStrWithPercents(
818 size_t maxOut,
819 CharType *dest,
820 size_t maxIn,
821 const CharType *source)
822 {
823 size_t written = 0;
824
825 if (maxIn == 0)
826 return 0;
827
828 size_t i;
829 for ( i = 0; i < maxIn-1 && written < maxOut; source++, i++)
830 {
831 dest[written++] = *source;
832 if (*(source+1) == wxT('%'))
833 {
834 // skip this additional '%' character
835 source++;
836 i++;
837 }
838 }
839
840 if (i < maxIn && written < maxOut)
841 // copy last character inconditionally
842 dest[written++] = *source;
843
844 return written;
845 }
846
847 template<typename CharType>
848 static int wxDoVsnprintf(CharType *buf, size_t lenMax,
849 const CharType *format, va_list argptr)
850 {
851 // useful for debugging, to understand if we are really using this function
852 // rather than the system implementation
853 #if 0
854 wprintf(L"Using wxCRT_VsnprintfW\n");
855 #endif
856
857 // required memory:
858 wxPrintfConvSpec<CharType> arg[wxMAX_SVNPRINTF_ARGUMENTS];
859 wxPrintfArg argdata[wxMAX_SVNPRINTF_ARGUMENTS];
860 wxPrintfConvSpec<CharType> *pspec[wxMAX_SVNPRINTF_ARGUMENTS] = { NULL };
861
862 size_t i;
863
864 // number of characters in the buffer so far, must be less than lenMax
865 size_t lenCur = 0;
866
867 size_t nargs = 0;
868 const CharType *toparse = format;
869
870 // parse the format string
871 bool posarg_present = false, nonposarg_present = false;
872 for (; *toparse != wxT('\0'); toparse++)
873 {
874 if (*toparse == wxT('%') )
875 {
876 arg[nargs].Init();
877
878 // let's see if this is a (valid) conversion specifier...
879 if (arg[nargs].Parse(toparse))
880 {
881 // ...yes it is
882 wxPrintfConvSpec<CharType> *current = &arg[nargs];
883
884 // make toparse point to the end of this specifier
885 toparse = current->m_pArgEnd;
886
887 if (current->m_pos > 0)
888 {
889 // the positionals start from number 1... adjust the index
890 current->m_pos--;
891 posarg_present = true;
892 }
893 else
894 {
895 // not a positional argument...
896 current->m_pos = nargs;
897 nonposarg_present = true;
898 }
899
900 // this conversion specifier is tied to the pos-th argument...
901 pspec[current->m_pos] = current;
902 nargs++;
903
904 if (nargs == wxMAX_SVNPRINTF_ARGUMENTS)
905 {
906 wxLogDebug(wxT("A single call to wxVsnprintf() has more than %d arguments; ")
907 wxT("ignoring all remaining arguments."), wxMAX_SVNPRINTF_ARGUMENTS);
908 break; // cannot handle any additional conv spec
909 }
910 }
911 else
912 {
913 // it's safe to look in the next character of toparse as at worst
914 // we'll hit its \0
915 if (*(toparse+1) == wxT('%'))
916 toparse++; // the Parse() returned false because we've found a %%
917 }
918 }
919 }
920
921 if (posarg_present && nonposarg_present)
922 {
923 buf[0] = 0;
924 return -1; // format strings with both positional and
925 } // non-positional conversion specifier are unsupported !!
926
927 // on platforms where va_list is an array type, it is necessary to make a
928 // copy to be able to pass it to LoadArg as a reference.
929 bool ok = true;
930 va_list ap;
931 wxVaCopy(ap, argptr);
932
933 // now load arguments from stack
934 for (i=0; i < nargs && ok; i++)
935 {
936 // !pspec[i] means that the user forgot a positional parameter (e.g. %$1s %$3s);
937 // LoadArg == false means that wxPrintfConvSpec::Parse failed to set the
938 // conversion specifier 'type' to a valid value...
939 ok = pspec[i] && pspec[i]->LoadArg(&argdata[i], ap);
940 }
941
942 va_end(ap);
943
944 // something failed while loading arguments from the variable list...
945 // (e.g. the user repeated twice the same positional argument)
946 if (!ok)
947 {
948 buf[0] = 0;
949 return -1;
950 }
951
952 // finally, process each conversion specifier with its own argument
953 toparse = format;
954 for (i=0; i < nargs; i++)
955 {
956 // copy in the output buffer the portion of the format string between
957 // last specifier and the current one
958 size_t tocopy = ( arg[i].m_pArgPos - toparse );
959
960 lenCur += wxCopyStrWithPercents(lenMax - lenCur, buf + lenCur,
961 tocopy, toparse);
962 if (lenCur == lenMax)
963 {
964 buf[lenMax - 1] = 0;
965 return lenMax+1; // not enough space in the output buffer !
966 }
967
968 // process this specifier directly in the output buffer
969 int n = arg[i].Process(buf+lenCur, lenMax - lenCur, &argdata[arg[i].m_pos], lenCur);
970 if (n == -1)
971 {
972 buf[lenMax-1] = wxT('\0'); // be sure to always NUL-terminate the string
973 return lenMax+1; // not enough space in the output buffer !
974 }
975 lenCur += n;
976
977 // the +1 is because wxPrintfConvSpec::m_pArgEnd points to the last character
978 // of the format specifier, but we are not interested to it...
979 toparse = arg[i].m_pArgEnd + 1;
980 }
981
982 // copy portion of the format string after last specifier
983 // NOTE: toparse is pointing to the character just after the last processed
984 // conversion specifier
985 // NOTE2: the +1 is because we want to copy also the '\0'
986 size_t tocopy = wxStrlen(format) + 1 - ( toparse - format ) ;
987
988 lenCur += wxCopyStrWithPercents(lenMax - lenCur, buf + lenCur,
989 tocopy, toparse) - 1;
990 if (buf[lenCur])
991 {
992 buf[lenCur] = 0;
993 return lenMax+1; // not enough space in the output buffer !
994 }
995
996 // Don't do:
997 // wxASSERT(lenCur == wxStrlen(buf));
998 // in fact if we embedded NULLs in the output buffer (using %c with a '\0')
999 // such check would fail
1000
1001 return lenCur;
1002 }
1003
1004 #undef APPEND_CH
1005 #undef CHECK_PREC
1006
1007 } // anonymous namespace
1008
1009 #endif // !defined(wxCRT_VsnprintfW) || !defined(wxCRT_VsnprintfA)
1010
1011 // ----------------------------------------------------------------------------
1012 // wxCRT_VsnprintfW
1013 // ----------------------------------------------------------------------------
1014
1015 #if !defined(wxCRT_VsnprintfW)
1016
1017 #if !wxUSE_WXVSNPRINTFW
1018 #error "wxUSE_WXVSNPRINTFW must be 1 if our wxCRT_VsnprintfW is used"
1019 #endif
1020
1021 int wxCRT_VsnprintfW(wchar_t *buf, size_t len,
1022 const wchar_t *format, va_list argptr)
1023 {
1024 return wxDoVsnprintf(buf, len, format, argptr);
1025 }
1026
1027 #else // wxCRT_VsnprintfW is defined
1028
1029 #if wxUSE_WXVSNPRINTFW
1030 #error "wxUSE_WXVSNPRINTFW must be 0 if our wxCRT_VsnprintfW is not used"
1031 #endif
1032
1033 #endif // !wxCRT_VsnprintfW
1034
1035 // ----------------------------------------------------------------------------
1036 // wxCRT_VsnprintfA
1037 // ----------------------------------------------------------------------------
1038
1039 #ifndef wxCRT_VsnprintfA
1040
1041 #if !wxUSE_WXVSNPRINTFA
1042 #error "wxUSE_WXVSNPRINTFA must be 1 if our wxCRT_VsnprintfA is used"
1043 #endif
1044
1045 int wxCRT_VsnprintfA(char *buf, size_t len,
1046 const char *format, va_list argptr)
1047 {
1048 return wxDoVsnprintf(buf, len, format, argptr);
1049 }
1050
1051 #else // wxCRT_VsnprintfA is defined
1052
1053 #if wxUSE_WXVSNPRINTFA
1054 #error "wxUSE_WXVSNPRINTFA must be 0 if our wxCRT_VsnprintfA is not used"
1055 #endif
1056
1057 #endif // !wxCRT_VsnprintfA