1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/strconv.cpp
3 // Purpose: Unicode conversion classes
4 // Author: Ove Kaaven, Robert Roebling, Vadim Zeitlin, Vaclav Slavik,
5 // Ryan Norton, Fredrik Roubert (UTF7)
9 // Copyright: (c) 1999 Ove Kaaven, Robert Roebling, Vaclav Slavik
10 // (c) 2000-2003 Vadim Zeitlin
11 // (c) 2004 Ryan Norton, Fredrik Roubert
12 // Licence: wxWindows licence
13 /////////////////////////////////////////////////////////////////////////////
15 // For compilers that support precompilation, includes "wx.h".
16 #include "wx/wxprec.h"
26 #include "wx/hashmap.h"
29 #include "wx/strconv.h"
41 #if defined(__WIN32__) && !defined(__WXMICROWIN__)
42 #include "wx/msw/private.h"
43 #include "wx/msw/missing.h"
44 #define wxHAVE_WIN32_MB2WC
53 #include "wx/thread.h"
56 #include "wx/encconv.h"
57 #include "wx/fontmap.h"
61 #include <ATSUnicode.h>
62 #include <TextCommon.h>
63 #include <TextEncodingConverter.h>
66 // includes Mac headers
67 #include "wx/mac/private.h"
71 #define TRACE_STRCONV _T("strconv")
73 // WC_UTF16 is defined only if sizeof(wchar_t) == 2, otherwise it's supposed to
75 #if SIZEOF_WCHAR_T == 2
80 // ============================================================================
82 // ============================================================================
84 // helper function of cMB2WC(): check if n bytes at this location are all NUL
85 static bool NotAllNULs(const char *p
, size_t n
)
87 while ( n
&& *p
++ == '\0' )
93 // ----------------------------------------------------------------------------
94 // UTF-16 en/decoding to/from UCS-4 with surrogates handling
95 // ----------------------------------------------------------------------------
97 static size_t encode_utf16(wxUint32 input
, wxUint16
*output
)
102 *output
= (wxUint16
) input
;
106 else if (input
>= 0x110000)
108 return wxCONV_FAILED
;
114 *output
++ = (wxUint16
) ((input
>> 10) + 0xd7c0);
115 *output
= (wxUint16
) ((input
& 0x3ff) + 0xdc00);
122 static size_t decode_utf16(const wxUint16
* input
, wxUint32
& output
)
124 if ((*input
< 0xd800) || (*input
> 0xdfff))
129 else if ((input
[1] < 0xdc00) || (input
[1] > 0xdfff))
132 return wxCONV_FAILED
;
136 output
= ((input
[0] - 0xd7c0) << 10) + (input
[1] - 0xdc00);
142 typedef wchar_t wxDecodeSurrogate_t
;
144 typedef wxUint16 wxDecodeSurrogate_t
;
145 #endif // WC_UTF16/!WC_UTF16
147 // returns the next UTF-32 character from the wchar_t buffer and advances the
148 // pointer to the character after this one
150 // if an invalid character is found, *pSrc is set to NULL, the caller must
152 static wxUint32
wxDecodeSurrogate(const wxDecodeSurrogate_t
**pSrc
)
156 n
= decode_utf16(wx_reinterpret_cast(const wxUint16
*, *pSrc
), out
);
157 if ( n
== wxCONV_FAILED
)
165 // ----------------------------------------------------------------------------
167 // ----------------------------------------------------------------------------
170 wxMBConv::ToWChar(wchar_t *dst
, size_t dstLen
,
171 const char *src
, size_t srcLen
) const
173 // although new conversion classes are supposed to implement this function
174 // directly, the existins ones only implement the old MB2WC() and so, to
175 // avoid to have to rewrite all conversion classes at once, we provide a
176 // default (but not efficient) implementation of this one in terms of the
177 // old function by copying the input to ensure that it's NUL-terminated and
178 // then using MB2WC() to convert it
180 // the number of chars [which would be] written to dst [if it were not NULL]
181 size_t dstWritten
= 0;
183 // the number of NULs terminating this string
184 size_t nulLen
= 0; // not really needed, but just to avoid warnings
186 // if we were not given the input size we just have to assume that the
187 // string is properly terminated as we have no way of knowing how long it
188 // is anyhow, but if we do have the size check whether there are enough
192 if ( srcLen
!= wxNO_LEN
)
194 // we need to know how to find the end of this string
195 nulLen
= GetMBNulLen();
196 if ( nulLen
== wxCONV_FAILED
)
197 return wxCONV_FAILED
;
199 // if there are enough NULs we can avoid the copy
200 if ( srcLen
< nulLen
|| NotAllNULs(src
+ srcLen
- nulLen
, nulLen
) )
202 // make a copy in order to properly NUL-terminate the string
203 bufTmp
= wxCharBuffer(srcLen
+ nulLen
- 1 /* 1 will be added */);
204 char * const p
= bufTmp
.data();
205 memcpy(p
, src
, srcLen
);
206 for ( char *s
= p
+ srcLen
; s
< p
+ srcLen
+ nulLen
; s
++ )
212 srcEnd
= src
+ srcLen
;
214 else // quit after the first loop iteration
221 // try to convert the current chunk
222 size_t lenChunk
= MB2WC(NULL
, src
, 0);
223 if ( lenChunk
== wxCONV_FAILED
)
224 return wxCONV_FAILED
;
226 lenChunk
++; // for the L'\0' at the end of this chunk
228 dstWritten
+= lenChunk
;
232 // nothing left in the input string, conversion succeeded
238 if ( dstWritten
> dstLen
)
239 return wxCONV_FAILED
;
241 if ( MB2WC(dst
, src
, lenChunk
) == wxCONV_FAILED
)
242 return wxCONV_FAILED
;
249 // we convert just one chunk in this case as this is the entire
254 // advance the input pointer past the end of this chunk
255 while ( NotAllNULs(src
, nulLen
) )
257 // notice that we must skip over multiple bytes here as we suppose
258 // that if NUL takes 2 or 4 bytes, then all the other characters do
259 // too and so if advanced by a single byte we might erroneously
260 // detect sequences of NUL bytes in the middle of the input
264 src
+= nulLen
; // skipping over its terminator as well
266 // note that ">=" (and not just "==") is needed here as the terminator
267 // we skipped just above could be inside or just after the buffer
268 // delimited by inEnd
277 wxMBConv::FromWChar(char *dst
, size_t dstLen
,
278 const wchar_t *src
, size_t srcLen
) const
280 // the number of chars [which would be] written to dst [if it were not NULL]
281 size_t dstWritten
= 0;
283 // make a copy of the input string unless it is already properly
286 // if we don't know its length we have no choice but to assume that it is,
287 // indeed, properly terminated
288 wxWCharBuffer bufTmp
;
289 if ( srcLen
== wxNO_LEN
)
291 srcLen
= wxWcslen(src
) + 1;
293 else if ( srcLen
!= 0 && src
[srcLen
- 1] != L
'\0' )
295 // make a copy in order to properly NUL-terminate the string
296 bufTmp
= wxWCharBuffer(srcLen
);
297 memcpy(bufTmp
.data(), src
, srcLen
* sizeof(wchar_t));
301 const size_t lenNul
= GetMBNulLen();
302 for ( const wchar_t * const srcEnd
= src
+ srcLen
;
304 src
+= wxWcslen(src
) + 1 /* skip L'\0' too */ )
306 // try to convert the current chunk
307 size_t lenChunk
= WC2MB(NULL
, src
, 0);
309 if ( lenChunk
== wxCONV_FAILED
)
310 return wxCONV_FAILED
;
313 dstWritten
+= lenChunk
;
317 if ( dstWritten
> dstLen
)
318 return wxCONV_FAILED
;
320 if ( WC2MB(dst
, src
, lenChunk
) == wxCONV_FAILED
)
321 return wxCONV_FAILED
;
330 size_t wxMBConv::MB2WC(wchar_t *outBuff
, const char *inBuff
, size_t outLen
) const
332 size_t rc
= ToWChar(outBuff
, outLen
, inBuff
);
333 if ( rc
!= wxCONV_FAILED
)
335 // ToWChar() returns the buffer length, i.e. including the trailing
336 // NUL, while this method doesn't take it into account
343 size_t wxMBConv::WC2MB(char *outBuff
, const wchar_t *inBuff
, size_t outLen
) const
345 size_t rc
= FromWChar(outBuff
, outLen
, inBuff
);
346 if ( rc
!= wxCONV_FAILED
)
354 wxMBConv::~wxMBConv()
356 // nothing to do here (necessary for Darwin linking probably)
359 const wxWCharBuffer
wxMBConv::cMB2WC(const char *psz
) const
363 // calculate the length of the buffer needed first
364 const size_t nLen
= MB2WC(NULL
, psz
, 0);
365 if ( nLen
!= wxCONV_FAILED
)
367 // now do the actual conversion
368 wxWCharBuffer
buf(nLen
/* +1 added implicitly */);
370 // +1 for the trailing NULL
371 if ( MB2WC(buf
.data(), psz
, nLen
+ 1) != wxCONV_FAILED
)
376 return wxWCharBuffer();
379 const wxCharBuffer
wxMBConv::cWC2MB(const wchar_t *pwz
) const
383 const size_t nLen
= WC2MB(NULL
, pwz
, 0);
384 if ( nLen
!= wxCONV_FAILED
)
386 // extra space for trailing NUL(s)
387 static const size_t extraLen
= GetMaxMBNulLen();
389 wxCharBuffer
buf(nLen
+ extraLen
- 1);
390 if ( WC2MB(buf
.data(), pwz
, nLen
+ extraLen
) != wxCONV_FAILED
)
395 return wxCharBuffer();
399 wxMBConv::cMB2WC(const char *inBuff
, size_t inLen
, size_t *outLen
) const
401 const size_t dstLen
= ToWChar(NULL
, 0, inBuff
, inLen
);
402 if ( dstLen
!= wxCONV_FAILED
)
404 wxWCharBuffer
wbuf(dstLen
- 1);
405 if ( ToWChar(wbuf
.data(), dstLen
, inBuff
, inLen
) != wxCONV_FAILED
)
410 if ( wbuf
[dstLen
- 1] == L
'\0' )
421 return wxWCharBuffer();
425 wxMBConv::cWC2MB(const wchar_t *inBuff
, size_t inLen
, size_t *outLen
) const
427 size_t dstLen
= FromWChar(NULL
, 0, inBuff
, inLen
);
428 if ( dstLen
!= wxCONV_FAILED
)
430 // special case of empty input: can't allocate 0 size buffer below as
431 // wxCharBuffer insists on NUL-terminating it
432 wxCharBuffer
buf(dstLen
? dstLen
- 1 : 1);
433 if ( FromWChar(buf
.data(), dstLen
, inBuff
, inLen
) != wxCONV_FAILED
)
439 const size_t nulLen
= GetMBNulLen();
440 if ( dstLen
>= nulLen
&&
441 !NotAllNULs(buf
.data() + dstLen
- nulLen
, nulLen
) )
443 // in this case the output is NUL-terminated and we're not
444 // supposed to count NUL
456 return wxCharBuffer();
459 // ----------------------------------------------------------------------------
461 // ----------------------------------------------------------------------------
463 size_t wxMBConvLibc::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
465 return wxMB2WC(buf
, psz
, n
);
468 size_t wxMBConvLibc::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
470 return wxWC2MB(buf
, psz
, n
);
473 // ----------------------------------------------------------------------------
474 // wxConvBrokenFileNames
475 // ----------------------------------------------------------------------------
479 wxConvBrokenFileNames::wxConvBrokenFileNames(const wxChar
*charset
)
481 if ( !charset
|| wxStricmp(charset
, _T("UTF-8")) == 0
482 || wxStricmp(charset
, _T("UTF8")) == 0 )
483 m_conv
= new wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_PUA
);
485 m_conv
= new wxCSConv(charset
);
490 // ----------------------------------------------------------------------------
492 // ----------------------------------------------------------------------------
494 // Implementation (C) 2004 Fredrik Roubert
497 // BASE64 decoding table
499 static const unsigned char utf7unb64
[] =
501 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
502 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
503 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
504 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
505 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
506 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f,
507 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
508 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
509 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
510 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
511 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
512 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
513 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
514 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
515 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
516 0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
517 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
518 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
519 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
520 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
521 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
522 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
523 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
524 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
525 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
526 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
527 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
528 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
529 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
530 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
531 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
532 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
535 size_t wxMBConvUTF7::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
539 while ( *psz
&& (!buf
|| (len
< n
)) )
541 unsigned char cc
= *psz
++;
549 else if (*psz
== '-')
557 else // start of BASE64 encoded string
561 for ( ok
= lsb
= false, d
= 0, l
= 0;
562 (cc
= utf7unb64
[(unsigned char)*psz
]) != 0xff;
567 for (l
+= 6; l
>= 8; lsb
= !lsb
)
569 unsigned char c
= (unsigned char)((d
>> (l
-= 8)) % 256);
579 *buf
= (wchar_t)(c
<< 8);
588 // in valid UTF7 we should have valid characters after '+'
589 return wxCONV_FAILED
;
597 if ( buf
&& (len
< n
) )
604 // BASE64 encoding table
606 static const unsigned char utf7enb64
[] =
608 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
609 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
610 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
611 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
612 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
613 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
614 'w', 'x', 'y', 'z', '0', '1', '2', '3',
615 '4', '5', '6', '7', '8', '9', '+', '/'
619 // UTF-7 encoding table
621 // 0 - Set D (directly encoded characters)
622 // 1 - Set O (optional direct characters)
623 // 2 - whitespace characters (optional)
624 // 3 - special characters
626 static const unsigned char utf7encode
[128] =
628 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
629 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
630 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 3,
631 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
632 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
633 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
634 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
635 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3
638 size_t wxMBConvUTF7::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
642 while (*psz
&& ((!buf
) || (len
< n
)))
645 if (cc
< 0x80 && utf7encode
[cc
] < 1)
654 else if (((wxUint32
)cc
) > 0xffff)
656 // no surrogate pair generation (yet?)
657 return wxCONV_FAILED
;
668 // BASE64 encode string
669 unsigned int lsb
, d
, l
;
670 for (d
= 0, l
= 0; /*nothing*/; psz
++)
672 for (lsb
= 0; lsb
< 2; lsb
++)
675 d
+= lsb
? cc
& 0xff : (cc
& 0xff00) >> 8;
677 for (l
+= 8; l
>= 6; )
681 *buf
++ = utf7enb64
[(d
>> l
) % 64];
687 if (!(cc
) || (cc
< 0x80 && utf7encode
[cc
] < 1))
694 *buf
++ = utf7enb64
[((d
% 16) << (6 - l
)) % 64];
706 if (buf
&& (len
< n
))
712 // ----------------------------------------------------------------------------
714 // ----------------------------------------------------------------------------
716 static wxUint32 utf8_max
[]=
717 { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff, 0xffffffff };
719 // boundaries of the private use area we use to (temporarily) remap invalid
720 // characters invalid in a UTF-8 encoded string
721 const wxUint32 wxUnicodePUA
= 0x100000;
722 const wxUint32 wxUnicodePUAEnd
= wxUnicodePUA
+ 256;
724 size_t wxMBConvUTF8::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
728 while (*psz
&& ((!buf
) || (len
< n
)))
730 const char *opsz
= psz
;
731 bool invalid
= false;
732 unsigned char cc
= *psz
++, fc
= cc
;
734 for (cnt
= 0; fc
& 0x80; cnt
++)
744 // escape the escape character for octal escapes
745 if ((m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
746 && cc
== '\\' && (!buf
|| len
< n
))
758 // invalid UTF-8 sequence
763 unsigned ocnt
= cnt
- 1;
764 wxUint32 res
= cc
& (0x3f >> cnt
);
768 if ((cc
& 0xC0) != 0x80)
770 // invalid UTF-8 sequence
776 res
= (res
<< 6) | (cc
& 0x3f);
779 if (invalid
|| res
<= utf8_max
[ocnt
])
781 // illegal UTF-8 encoding
784 else if ((m_options
& MAP_INVALID_UTF8_TO_PUA
) &&
785 res
>= wxUnicodePUA
&& res
< wxUnicodePUAEnd
)
787 // if one of our PUA characters turns up externally
788 // it must also be treated as an illegal sequence
789 // (a bit like you have to escape an escape character)
795 // cast is ok because wchar_t == wxUuint16 if WC_UTF16
796 size_t pa
= encode_utf16(res
, (wxUint16
*)buf
);
797 if (pa
== wxCONV_FAILED
)
809 *buf
++ = (wchar_t)res
;
811 #endif // WC_UTF16/!WC_UTF16
817 if (m_options
& MAP_INVALID_UTF8_TO_PUA
)
819 while (opsz
< psz
&& (!buf
|| len
< n
))
822 // cast is ok because wchar_t == wxUuint16 if WC_UTF16
823 size_t pa
= encode_utf16((unsigned char)*opsz
+ wxUnicodePUA
, (wxUint16
*)buf
);
824 wxASSERT(pa
!= wxCONV_FAILED
);
831 *buf
++ = (wchar_t)(wxUnicodePUA
+ (unsigned char)*opsz
);
837 else if (m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
839 while (opsz
< psz
&& (!buf
|| len
< n
))
841 if ( buf
&& len
+ 3 < n
)
843 unsigned char on
= *opsz
;
845 *buf
++ = (wchar_t)( L
'0' + on
/ 0100 );
846 *buf
++ = (wchar_t)( L
'0' + (on
% 0100) / 010 );
847 *buf
++ = (wchar_t)( L
'0' + on
% 010 );
854 else // MAP_INVALID_UTF8_NOT
856 return wxCONV_FAILED
;
862 if (buf
&& (len
< n
))
868 static inline bool isoctal(wchar_t wch
)
870 return L
'0' <= wch
&& wch
<= L
'7';
873 size_t wxMBConvUTF8::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
877 while (*psz
&& ((!buf
) || (len
< n
)))
882 // cast is ok for WC_UTF16
883 size_t pa
= decode_utf16((const wxUint16
*)psz
, cc
);
884 psz
+= (pa
== wxCONV_FAILED
) ? 1 : pa
;
886 cc
= (*psz
++) & 0x7fffffff;
889 if ( (m_options
& MAP_INVALID_UTF8_TO_PUA
)
890 && cc
>= wxUnicodePUA
&& cc
< wxUnicodePUAEnd
)
893 *buf
++ = (char)(cc
- wxUnicodePUA
);
896 else if ( (m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
897 && cc
== L
'\\' && psz
[0] == L
'\\' )
904 else if ( (m_options
& MAP_INVALID_UTF8_TO_OCTAL
) &&
906 isoctal(psz
[0]) && isoctal(psz
[1]) && isoctal(psz
[2]) )
910 *buf
++ = (char) ((psz
[0] - L
'0') * 0100 +
911 (psz
[1] - L
'0') * 010 +
921 for (cnt
= 0; cc
> utf8_max
[cnt
]; cnt
++)
937 *buf
++ = (char) ((-128 >> cnt
) | ((cc
>> (cnt
* 6)) & (0x3f >> cnt
)));
939 *buf
++ = (char) (0x80 | ((cc
>> (cnt
* 6)) & 0x3f));
945 if (buf
&& (len
< n
))
951 // ============================================================================
953 // ============================================================================
955 #ifdef WORDS_BIGENDIAN
956 #define wxMBConvUTF16straight wxMBConvUTF16BE
957 #define wxMBConvUTF16swap wxMBConvUTF16LE
959 #define wxMBConvUTF16swap wxMBConvUTF16BE
960 #define wxMBConvUTF16straight wxMBConvUTF16LE
964 size_t wxMBConvUTF16Base::GetLength(const char *src
, size_t srcLen
)
966 if ( srcLen
== wxNO_LEN
)
968 // count the number of bytes in input, including the trailing NULs
969 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
970 for ( srcLen
= 1; *inBuff
++; srcLen
++ )
973 srcLen
*= BYTES_PER_CHAR
;
975 else // we already have the length
977 // we can only convert an entire number of UTF-16 characters
978 if ( srcLen
% BYTES_PER_CHAR
)
979 return wxCONV_FAILED
;
985 // case when in-memory representation is UTF-16 too
988 // ----------------------------------------------------------------------------
989 // conversions without endianness change
990 // ----------------------------------------------------------------------------
993 wxMBConvUTF16straight::ToWChar(wchar_t *dst
, size_t dstLen
,
994 const char *src
, size_t srcLen
) const
996 // set up the scene for using memcpy() (which is presumably more efficient
997 // than copying the bytes one by one)
998 srcLen
= GetLength(src
, srcLen
);
999 if ( srcLen
== wxNO_LEN
)
1000 return wxCONV_FAILED
;
1002 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1005 if ( dstLen
< inLen
)
1006 return wxCONV_FAILED
;
1008 memcpy(dst
, src
, srcLen
);
1015 wxMBConvUTF16straight::FromWChar(char *dst
, size_t dstLen
,
1016 const wchar_t *src
, size_t srcLen
) const
1018 if ( srcLen
== wxNO_LEN
)
1019 srcLen
= wxWcslen(src
) + 1;
1021 srcLen
*= BYTES_PER_CHAR
;
1025 if ( dstLen
< srcLen
)
1026 return wxCONV_FAILED
;
1028 memcpy(dst
, src
, srcLen
);
1034 // ----------------------------------------------------------------------------
1035 // endian-reversing conversions
1036 // ----------------------------------------------------------------------------
1039 wxMBConvUTF16swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1040 const char *src
, size_t srcLen
) const
1042 srcLen
= GetLength(src
, srcLen
);
1043 if ( srcLen
== wxNO_LEN
)
1044 return wxCONV_FAILED
;
1046 srcLen
/= BYTES_PER_CHAR
;
1050 if ( dstLen
< srcLen
)
1051 return wxCONV_FAILED
;
1053 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1054 for ( size_t n
= 0; n
< srcLen
; n
++, inBuff
++ )
1056 *dst
++ = wxUINT16_SWAP_ALWAYS(*inBuff
);
1064 wxMBConvUTF16swap::FromWChar(char *dst
, size_t dstLen
,
1065 const wchar_t *src
, size_t srcLen
) const
1067 if ( srcLen
== wxNO_LEN
)
1068 srcLen
= wxWcslen(src
) + 1;
1070 srcLen
*= BYTES_PER_CHAR
;
1074 if ( dstLen
< srcLen
)
1075 return wxCONV_FAILED
;
1077 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1078 for ( size_t n
= 0; n
< srcLen
; n
+= BYTES_PER_CHAR
, src
++ )
1080 *outBuff
++ = wxUINT16_SWAP_ALWAYS(*src
);
1087 #else // !WC_UTF16: wchar_t is UTF-32
1089 // ----------------------------------------------------------------------------
1090 // conversions without endianness change
1091 // ----------------------------------------------------------------------------
1094 wxMBConvUTF16straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1095 const char *src
, size_t srcLen
) const
1097 srcLen
= GetLength(src
, srcLen
);
1098 if ( srcLen
== wxNO_LEN
)
1099 return wxCONV_FAILED
;
1101 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1104 // optimization: return maximal space which could be needed for this
1105 // string even if the real size could be smaller if the buffer contains
1111 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1112 for ( const wxUint16
* const inEnd
= inBuff
+ inLen
; inBuff
< inEnd
; )
1114 const wxUint32 ch
= wxDecodeSurrogate(&inBuff
);
1116 return wxCONV_FAILED
;
1118 if ( ++outLen
> dstLen
)
1119 return wxCONV_FAILED
;
1129 wxMBConvUTF16straight::FromWChar(char *dst
, size_t dstLen
,
1130 const wchar_t *src
, size_t srcLen
) const
1132 if ( srcLen
== wxNO_LEN
)
1133 srcLen
= wxWcslen(src
) + 1;
1136 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1137 for ( size_t n
= 0; n
< srcLen
; n
++ )
1140 const size_t numChars
= encode_utf16(*src
++, cc
);
1141 if ( numChars
== wxCONV_FAILED
)
1142 return wxCONV_FAILED
;
1144 outLen
+= numChars
* BYTES_PER_CHAR
;
1147 if ( outLen
> dstLen
)
1148 return wxCONV_FAILED
;
1151 if ( numChars
== 2 )
1153 // second character of a surrogate
1162 // ----------------------------------------------------------------------------
1163 // endian-reversing conversions
1164 // ----------------------------------------------------------------------------
1167 wxMBConvUTF16swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1168 const char *src
, size_t srcLen
) const
1170 srcLen
= GetLength(src
, srcLen
);
1171 if ( srcLen
== wxNO_LEN
)
1172 return wxCONV_FAILED
;
1174 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1177 // optimization: return maximal space which could be needed for this
1178 // string even if the real size could be smaller if the buffer contains
1184 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1185 for ( const wxUint16
* const inEnd
= inBuff
+ inLen
; inBuff
< inEnd
; )
1190 tmp
[0] = wxUINT16_SWAP_ALWAYS(*inBuff
);
1192 tmp
[1] = wxUINT16_SWAP_ALWAYS(*inBuff
);
1194 const size_t numChars
= decode_utf16(tmp
, ch
);
1195 if ( numChars
== wxCONV_FAILED
)
1196 return wxCONV_FAILED
;
1198 if ( numChars
== 2 )
1201 if ( ++outLen
> dstLen
)
1202 return wxCONV_FAILED
;
1212 wxMBConvUTF16swap::FromWChar(char *dst
, size_t dstLen
,
1213 const wchar_t *src
, size_t srcLen
) const
1215 if ( srcLen
== wxNO_LEN
)
1216 srcLen
= wxWcslen(src
) + 1;
1219 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1220 for ( const wchar_t *srcEnd
= src
+ srcLen
; src
< srcEnd
; src
++ )
1223 const size_t numChars
= encode_utf16(*src
, cc
);
1224 if ( numChars
== wxCONV_FAILED
)
1225 return wxCONV_FAILED
;
1227 outLen
+= numChars
* BYTES_PER_CHAR
;
1230 if ( outLen
> dstLen
)
1231 return wxCONV_FAILED
;
1233 *outBuff
++ = wxUINT16_SWAP_ALWAYS(cc
[0]);
1234 if ( numChars
== 2 )
1236 // second character of a surrogate
1237 *outBuff
++ = wxUINT16_SWAP_ALWAYS(cc
[1]);
1245 #endif // WC_UTF16/!WC_UTF16
1248 // ============================================================================
1250 // ============================================================================
1252 #ifdef WORDS_BIGENDIAN
1253 #define wxMBConvUTF32straight wxMBConvUTF32BE
1254 #define wxMBConvUTF32swap wxMBConvUTF32LE
1256 #define wxMBConvUTF32swap wxMBConvUTF32BE
1257 #define wxMBConvUTF32straight wxMBConvUTF32LE
1261 WXDLLIMPEXP_DATA_BASE(wxMBConvUTF32LE
) wxConvUTF32LE
;
1262 WXDLLIMPEXP_DATA_BASE(wxMBConvUTF32BE
) wxConvUTF32BE
;
1265 size_t wxMBConvUTF32Base::GetLength(const char *src
, size_t srcLen
)
1267 if ( srcLen
== wxNO_LEN
)
1269 // count the number of bytes in input, including the trailing NULs
1270 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1271 for ( srcLen
= 1; *inBuff
++; srcLen
++ )
1274 srcLen
*= BYTES_PER_CHAR
;
1276 else // we already have the length
1278 // we can only convert an entire number of UTF-32 characters
1279 if ( srcLen
% BYTES_PER_CHAR
)
1280 return wxCONV_FAILED
;
1286 // case when in-memory representation is UTF-16
1289 // ----------------------------------------------------------------------------
1290 // conversions without endianness change
1291 // ----------------------------------------------------------------------------
1294 wxMBConvUTF32straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1295 const char *src
, size_t srcLen
) const
1297 srcLen
= GetLength(src
, srcLen
);
1298 if ( srcLen
== wxNO_LEN
)
1299 return wxCONV_FAILED
;
1301 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1302 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1304 for ( size_t n
= 0; n
< inLen
; n
++ )
1307 const size_t numChars
= encode_utf16(*inBuff
++, cc
);
1308 if ( numChars
== wxCONV_FAILED
)
1309 return wxCONV_FAILED
;
1314 if ( outLen
> dstLen
)
1315 return wxCONV_FAILED
;
1318 if ( numChars
== 2 )
1320 // second character of a surrogate
1330 wxMBConvUTF32straight::FromWChar(char *dst
, size_t dstLen
,
1331 const wchar_t *src
, size_t srcLen
) const
1333 if ( srcLen
== wxNO_LEN
)
1334 srcLen
= wxWcslen(src
) + 1;
1338 // optimization: return maximal space which could be needed for this
1339 // string instead of the exact amount which could be less if there are
1340 // any surrogates in the input
1342 // we consider that surrogates are rare enough to make it worthwhile to
1343 // avoid running the loop below at the cost of slightly extra memory
1345 return srcLen
* BYTES_PER_CHAR
;
1348 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1350 for ( const wchar_t * const srcEnd
= src
+ srcLen
; src
< srcEnd
; )
1352 const wxUint32 ch
= wxDecodeSurrogate(&src
);
1354 return wxCONV_FAILED
;
1356 outLen
+= BYTES_PER_CHAR
;
1358 if ( outLen
> dstLen
)
1359 return wxCONV_FAILED
;
1367 // ----------------------------------------------------------------------------
1368 // endian-reversing conversions
1369 // ----------------------------------------------------------------------------
1372 wxMBConvUTF32swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1373 const char *src
, size_t srcLen
) const
1375 srcLen
= GetLength(src
, srcLen
);
1376 if ( srcLen
== wxNO_LEN
)
1377 return wxCONV_FAILED
;
1379 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1380 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1382 for ( size_t n
= 0; n
< inLen
; n
++, inBuff
++ )
1385 const size_t numChars
= encode_utf16(wxUINT32_SWAP_ALWAYS(*inBuff
), cc
);
1386 if ( numChars
== wxCONV_FAILED
)
1387 return wxCONV_FAILED
;
1392 if ( outLen
> dstLen
)
1393 return wxCONV_FAILED
;
1396 if ( numChars
== 2 )
1398 // second character of a surrogate
1408 wxMBConvUTF32swap::FromWChar(char *dst
, size_t dstLen
,
1409 const wchar_t *src
, size_t srcLen
) const
1411 if ( srcLen
== wxNO_LEN
)
1412 srcLen
= wxWcslen(src
) + 1;
1416 // optimization: return maximal space which could be needed for this
1417 // string instead of the exact amount which could be less if there are
1418 // any surrogates in the input
1420 // we consider that surrogates are rare enough to make it worthwhile to
1421 // avoid running the loop below at the cost of slightly extra memory
1423 return srcLen
*BYTES_PER_CHAR
;
1426 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1428 for ( const wchar_t * const srcEnd
= src
+ srcLen
; src
< srcEnd
; )
1430 const wxUint32 ch
= wxDecodeSurrogate(&src
);
1432 return wxCONV_FAILED
;
1434 outLen
+= BYTES_PER_CHAR
;
1436 if ( outLen
> dstLen
)
1437 return wxCONV_FAILED
;
1439 *outBuff
++ = wxUINT32_SWAP_ALWAYS(ch
);
1445 #else // !WC_UTF16: wchar_t is UTF-32
1447 // ----------------------------------------------------------------------------
1448 // conversions without endianness change
1449 // ----------------------------------------------------------------------------
1452 wxMBConvUTF32straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1453 const char *src
, size_t srcLen
) const
1455 // use memcpy() as it should be much faster than hand-written loop
1456 srcLen
= GetLength(src
, srcLen
);
1457 if ( srcLen
== wxNO_LEN
)
1458 return wxCONV_FAILED
;
1460 const size_t inLen
= srcLen
/BYTES_PER_CHAR
;
1463 if ( dstLen
< inLen
)
1464 return wxCONV_FAILED
;
1466 memcpy(dst
, src
, srcLen
);
1473 wxMBConvUTF32straight::FromWChar(char *dst
, size_t dstLen
,
1474 const wchar_t *src
, size_t srcLen
) const
1476 if ( srcLen
== wxNO_LEN
)
1477 srcLen
= wxWcslen(src
) + 1;
1479 srcLen
*= BYTES_PER_CHAR
;
1483 if ( dstLen
< srcLen
)
1484 return wxCONV_FAILED
;
1486 memcpy(dst
, src
, srcLen
);
1492 // ----------------------------------------------------------------------------
1493 // endian-reversing conversions
1494 // ----------------------------------------------------------------------------
1497 wxMBConvUTF32swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1498 const char *src
, size_t srcLen
) const
1500 srcLen
= GetLength(src
, srcLen
);
1501 if ( srcLen
== wxNO_LEN
)
1502 return wxCONV_FAILED
;
1504 srcLen
/= BYTES_PER_CHAR
;
1508 if ( dstLen
< srcLen
)
1509 return wxCONV_FAILED
;
1511 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1512 for ( size_t n
= 0; n
< srcLen
; n
++, inBuff
++ )
1514 *dst
++ = wxUINT32_SWAP_ALWAYS(*inBuff
);
1522 wxMBConvUTF32swap::FromWChar(char *dst
, size_t dstLen
,
1523 const wchar_t *src
, size_t srcLen
) const
1525 if ( srcLen
== wxNO_LEN
)
1526 srcLen
= wxWcslen(src
) + 1;
1528 srcLen
*= BYTES_PER_CHAR
;
1532 if ( dstLen
< srcLen
)
1533 return wxCONV_FAILED
;
1535 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1536 for ( size_t n
= 0; n
< srcLen
; n
+= BYTES_PER_CHAR
, src
++ )
1538 *outBuff
++ = wxUINT32_SWAP_ALWAYS(*src
);
1545 #endif // WC_UTF16/!WC_UTF16
1548 // ============================================================================
1549 // The classes doing conversion using the iconv_xxx() functions
1550 // ============================================================================
1554 // VS: glibc 2.1.3 is broken in that iconv() conversion to/from UCS4 fails with
1555 // E2BIG if output buffer is _exactly_ as big as needed. Such case is
1556 // (unless there's yet another bug in glibc) the only case when iconv()
1557 // returns with (size_t)-1 (which means error) and says there are 0 bytes
1558 // left in the input buffer -- when _real_ error occurs,
1559 // bytes-left-in-input buffer is non-zero. Hence, this alternative test for
1561 // [This bug does not appear in glibc 2.2.]
1562 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ <= 1
1563 #define ICONV_FAILED(cres, bufLeft) ((cres == (size_t)-1) && \
1564 (errno != E2BIG || bufLeft != 0))
1566 #define ICONV_FAILED(cres, bufLeft) (cres == (size_t)-1)
1569 #define ICONV_CHAR_CAST(x) ((ICONV_CONST char **)(x))
1571 #define ICONV_T_INVALID ((iconv_t)-1)
1573 #if SIZEOF_WCHAR_T == 4
1574 #define WC_BSWAP wxUINT32_SWAP_ALWAYS
1575 #define WC_ENC wxFONTENCODING_UTF32
1576 #elif SIZEOF_WCHAR_T == 2
1577 #define WC_BSWAP wxUINT16_SWAP_ALWAYS
1578 #define WC_ENC wxFONTENCODING_UTF16
1579 #else // sizeof(wchar_t) != 2 nor 4
1580 // does this ever happen?
1581 #error "Unknown sizeof(wchar_t): please report this to wx-dev@lists.wxwindows.org"
1584 // ----------------------------------------------------------------------------
1585 // wxMBConv_iconv: encapsulates an iconv character set
1586 // ----------------------------------------------------------------------------
1588 class wxMBConv_iconv
: public wxMBConv
1591 wxMBConv_iconv(const wxChar
*name
);
1592 virtual ~wxMBConv_iconv();
1594 virtual size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const;
1595 virtual size_t WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const;
1597 // classify this encoding as explained in wxMBConv::GetMBNulLen() comment
1598 virtual size_t GetMBNulLen() const;
1600 #if wxUSE_UNICODE_UTF8
1601 virtual bool IsUTF8() const;
1604 virtual wxMBConv
*Clone() const
1606 wxMBConv_iconv
*p
= new wxMBConv_iconv(m_name
);
1607 p
->m_minMBCharWidth
= m_minMBCharWidth
;
1612 { return (m2w
!= ICONV_T_INVALID
) && (w2m
!= ICONV_T_INVALID
); }
1615 // the iconv handlers used to translate from multibyte
1616 // to wide char and in the other direction
1621 // guards access to m2w and w2m objects
1622 wxMutex m_iconvMutex
;
1626 // the name (for iconv_open()) of a wide char charset -- if none is
1627 // available on this machine, it will remain NULL
1628 static wxString ms_wcCharsetName
;
1630 // true if the wide char encoding we use (i.e. ms_wcCharsetName) has
1631 // different endian-ness than the native one
1632 static bool ms_wcNeedsSwap
;
1635 // name of the encoding handled by this conversion
1638 // cached result of GetMBNulLen(); set to 0 meaning "unknown"
1640 size_t m_minMBCharWidth
;
1643 // make the constructor available for unit testing
1644 WXDLLIMPEXP_BASE wxMBConv
* new_wxMBConv_iconv( const wxChar
* name
)
1646 wxMBConv_iconv
* result
= new wxMBConv_iconv( name
);
1647 if ( !result
->IsOk() )
1656 wxString
wxMBConv_iconv::ms_wcCharsetName
;
1657 bool wxMBConv_iconv::ms_wcNeedsSwap
= false;
1659 wxMBConv_iconv::wxMBConv_iconv(const wxChar
*name
)
1662 m_minMBCharWidth
= 0;
1664 // iconv operates with chars, not wxChars, but luckily it uses only ASCII
1665 // names for the charsets
1666 const wxCharBuffer
cname(wxString(name
).ToAscii());
1668 // check for charset that represents wchar_t:
1669 if ( ms_wcCharsetName
.empty() )
1671 wxLogTrace(TRACE_STRCONV
, _T("Looking for wide char codeset:"));
1674 const wxChar
**names
= wxFontMapperBase::GetAllEncodingNames(WC_ENC
);
1675 #else // !wxUSE_FONTMAP
1676 static const wxChar
*names_static
[] =
1678 #if SIZEOF_WCHAR_T == 4
1680 #elif SIZEOF_WCHAR_T = 2
1685 const wxChar
**names
= names_static
;
1686 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1688 for ( ; *names
&& ms_wcCharsetName
.empty(); ++names
)
1690 const wxString
nameCS(*names
);
1692 // first try charset with explicit bytesex info (e.g. "UCS-4LE"):
1693 wxString
nameXE(nameCS
);
1695 #ifdef WORDS_BIGENDIAN
1697 #else // little endian
1701 wxLogTrace(TRACE_STRCONV
, _T(" trying charset \"%s\""),
1704 m2w
= iconv_open(nameXE
.ToAscii(), cname
);
1705 if ( m2w
== ICONV_T_INVALID
)
1707 // try charset w/o bytesex info (e.g. "UCS4")
1708 wxLogTrace(TRACE_STRCONV
, _T(" trying charset \"%s\""),
1710 m2w
= iconv_open(nameCS
.ToAscii(), cname
);
1712 // and check for bytesex ourselves:
1713 if ( m2w
!= ICONV_T_INVALID
)
1715 char buf
[2], *bufPtr
;
1716 wchar_t wbuf
[2], *wbufPtr
;
1724 outsz
= SIZEOF_WCHAR_T
* 2;
1729 m2w
, ICONV_CHAR_CAST(&bufPtr
), &insz
,
1730 (char**)&wbufPtr
, &outsz
);
1732 if (ICONV_FAILED(res
, insz
))
1734 wxLogLastError(wxT("iconv"));
1735 wxLogError(_("Conversion to charset '%s' doesn't work."),
1738 else // ok, can convert to this encoding, remember it
1740 ms_wcCharsetName
= nameCS
;
1741 ms_wcNeedsSwap
= wbuf
[0] != (wchar_t)buf
[0];
1745 else // use charset not requiring byte swapping
1747 ms_wcCharsetName
= nameXE
;
1751 wxLogTrace(TRACE_STRCONV
,
1752 wxT("iconv wchar_t charset is \"%s\"%s"),
1753 ms_wcCharsetName
.empty() ? _T("<none>")
1754 : ms_wcCharsetName
.c_str(),
1755 ms_wcNeedsSwap
? _T(" (needs swap)")
1758 else // we already have ms_wcCharsetName
1760 m2w
= iconv_open(ms_wcCharsetName
.ToAscii(), cname
);
1763 if ( ms_wcCharsetName
.empty() )
1765 w2m
= ICONV_T_INVALID
;
1769 w2m
= iconv_open(cname
, ms_wcCharsetName
.ToAscii());
1770 if ( w2m
== ICONV_T_INVALID
)
1772 wxLogTrace(TRACE_STRCONV
,
1773 wxT("\"%s\" -> \"%s\" works but not the converse!?"),
1774 ms_wcCharsetName
.c_str(), cname
.data());
1779 wxMBConv_iconv::~wxMBConv_iconv()
1781 if ( m2w
!= ICONV_T_INVALID
)
1783 if ( w2m
!= ICONV_T_INVALID
)
1787 size_t wxMBConv_iconv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
1789 // find the string length: notice that must be done differently for
1790 // NUL-terminated strings and UTF-16/32 which are terminated with 2/4 NULs
1792 const size_t nulLen
= GetMBNulLen();
1796 return wxCONV_FAILED
;
1799 inbuf
= strlen(psz
); // arguably more optimized than our version
1804 // for UTF-16/32 not only we need to have 2/4 consecutive NULs but
1805 // they also have to start at character boundary and not span two
1806 // adjacent characters
1808 for ( p
= psz
; NotAllNULs(p
, nulLen
); p
+= nulLen
)
1815 // NB: iconv() is MT-safe, but each thread must use its own iconv_t handle.
1816 // Unfortunately there are a couple of global wxCSConv objects such as
1817 // wxConvLocal that are used all over wx code, so we have to make sure
1818 // the handle is used by at most one thread at the time. Otherwise
1819 // only a few wx classes would be safe to use from non-main threads
1820 // as MB<->WC conversion would fail "randomly".
1821 wxMutexLocker
lock(wxConstCast(this, wxMBConv_iconv
)->m_iconvMutex
);
1822 #endif // wxUSE_THREADS
1824 size_t outbuf
= n
* SIZEOF_WCHAR_T
;
1826 // VS: Use these instead of psz, buf because iconv() modifies its arguments:
1827 wchar_t *bufPtr
= buf
;
1828 const char *pszPtr
= psz
;
1832 // have destination buffer, convert there
1834 ICONV_CHAR_CAST(&pszPtr
), &inbuf
,
1835 (char**)&bufPtr
, &outbuf
);
1836 res
= n
- (outbuf
/ SIZEOF_WCHAR_T
);
1840 // convert to native endianness
1841 for ( unsigned i
= 0; i
< res
; i
++ )
1842 buf
[n
] = WC_BSWAP(buf
[i
]);
1845 // NUL-terminate the string if there is any space left
1851 // no destination buffer... convert using temp buffer
1852 // to calculate destination buffer requirement
1859 outbuf
= 8 * SIZEOF_WCHAR_T
;
1862 ICONV_CHAR_CAST(&pszPtr
), &inbuf
,
1863 (char**)&bufPtr
, &outbuf
);
1865 res
+= 8 - (outbuf
/ SIZEOF_WCHAR_T
);
1867 while ((cres
== (size_t)-1) && (errno
== E2BIG
));
1870 if (ICONV_FAILED(cres
, inbuf
))
1872 //VS: it is ok if iconv fails, hence trace only
1873 wxLogTrace(TRACE_STRCONV
, wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
1874 return wxCONV_FAILED
;
1880 size_t wxMBConv_iconv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
1883 // NB: explained in MB2WC
1884 wxMutexLocker
lock(wxConstCast(this, wxMBConv_iconv
)->m_iconvMutex
);
1887 size_t inlen
= wxWcslen(psz
);
1888 size_t inbuf
= inlen
* SIZEOF_WCHAR_T
;
1892 wchar_t *tmpbuf
= 0;
1896 // need to copy to temp buffer to switch endianness
1897 // (doing WC_BSWAP twice on the original buffer won't help, as it
1898 // could be in read-only memory, or be accessed in some other thread)
1899 tmpbuf
= (wchar_t *)malloc(inbuf
+ SIZEOF_WCHAR_T
);
1900 for ( size_t i
= 0; i
< inlen
; i
++ )
1901 tmpbuf
[n
] = WC_BSWAP(psz
[i
]);
1903 tmpbuf
[inlen
] = L
'\0';
1909 // have destination buffer, convert there
1910 cres
= iconv( w2m
, ICONV_CHAR_CAST(&psz
), &inbuf
, &buf
, &outbuf
);
1914 // NB: iconv was given only wcslen(psz) characters on input, and so
1915 // it couldn't convert the trailing zero. Let's do it ourselves
1916 // if there's some room left for it in the output buffer.
1922 // no destination buffer: convert using temp buffer
1923 // to calculate destination buffer requirement
1931 cres
= iconv( w2m
, ICONV_CHAR_CAST(&psz
), &inbuf
, &buf
, &outbuf
);
1935 while ((cres
== (size_t)-1) && (errno
== E2BIG
));
1943 if (ICONV_FAILED(cres
, inbuf
))
1945 wxLogTrace(TRACE_STRCONV
, wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
1946 return wxCONV_FAILED
;
1952 size_t wxMBConv_iconv::GetMBNulLen() const
1954 if ( m_minMBCharWidth
== 0 )
1956 wxMBConv_iconv
* const self
= wxConstCast(this, wxMBConv_iconv
);
1959 // NB: explained in MB2WC
1960 wxMutexLocker
lock(self
->m_iconvMutex
);
1963 wchar_t *wnul
= L
"";
1964 char buf
[8]; // should be enough for NUL in any encoding
1965 size_t inLen
= sizeof(wchar_t),
1966 outLen
= WXSIZEOF(buf
);
1967 char *inBuff
= (char *)wnul
;
1968 char *outBuff
= buf
;
1969 if ( iconv(w2m
, ICONV_CHAR_CAST(&inBuff
), &inLen
, &outBuff
, &outLen
) == (size_t)-1 )
1971 self
->m_minMBCharWidth
= (size_t)-1;
1975 self
->m_minMBCharWidth
= outBuff
- buf
;
1979 return m_minMBCharWidth
;
1982 #if wxUSE_UNICODE_UTF8
1983 bool wxMBConv_iconv::IsUTF8() const
1985 return wxStricmp(m_name
, "UTF-8") == 0 ||
1986 wxStricmp(m_name
, "UTF8") == 0;
1990 #endif // HAVE_ICONV
1993 // ============================================================================
1994 // Win32 conversion classes
1995 // ============================================================================
1997 #ifdef wxHAVE_WIN32_MB2WC
2001 extern WXDLLIMPEXP_BASE
long wxCharsetToCodepage(const wxChar
*charset
);
2002 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
);
2005 class wxMBConv_win32
: public wxMBConv
2010 m_CodePage
= CP_ACP
;
2011 m_minMBCharWidth
= 0;
2014 wxMBConv_win32(const wxMBConv_win32
& conv
)
2017 m_CodePage
= conv
.m_CodePage
;
2018 m_minMBCharWidth
= conv
.m_minMBCharWidth
;
2022 wxMBConv_win32(const wxChar
* name
)
2024 m_CodePage
= wxCharsetToCodepage(name
);
2025 m_minMBCharWidth
= 0;
2028 wxMBConv_win32(wxFontEncoding encoding
)
2030 m_CodePage
= wxEncodingToCodepage(encoding
);
2031 m_minMBCharWidth
= 0;
2033 #endif // wxUSE_FONTMAP
2035 virtual size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2037 // note that we have to use MB_ERR_INVALID_CHARS flag as it without it
2038 // the behaviour is not compatible with the Unix version (using iconv)
2039 // and break the library itself, e.g. wxTextInputStream::NextChar()
2040 // wouldn't work if reading an incomplete MB char didn't result in an
2043 // Moreover, MB_ERR_INVALID_CHARS is only supported on Win 2K SP4 or
2044 // Win XP or newer and it is not supported for UTF-[78] so we always
2045 // use our own conversions in this case. See
2046 // http://blogs.msdn.com/michkap/archive/2005/04/19/409566.aspx
2047 // http://msdn.microsoft.com/library/en-us/intl/unicode_17si.asp
2048 if ( m_CodePage
== CP_UTF8
)
2050 return wxMBConvUTF8().MB2WC(buf
, psz
, n
);
2053 if ( m_CodePage
== CP_UTF7
)
2055 return wxMBConvUTF7().MB2WC(buf
, psz
, n
);
2059 if ( (m_CodePage
< 50000 && m_CodePage
!= CP_SYMBOL
) &&
2060 IsAtLeastWin2kSP4() )
2062 flags
= MB_ERR_INVALID_CHARS
;
2065 const size_t len
= ::MultiByteToWideChar
2067 m_CodePage
, // code page
2068 flags
, // flags: fall on error
2069 psz
, // input string
2070 -1, // its length (NUL-terminated)
2071 buf
, // output string
2072 buf
? n
: 0 // size of output buffer
2076 // function totally failed
2077 return wxCONV_FAILED
;
2080 // if we were really converting and didn't use MB_ERR_INVALID_CHARS,
2081 // check if we succeeded, by doing a double trip:
2082 if ( !flags
&& buf
)
2084 const size_t mbLen
= strlen(psz
);
2085 wxCharBuffer
mbBuf(mbLen
);
2086 if ( ::WideCharToMultiByte
2093 mbLen
+ 1, // size in bytes, not length
2097 strcmp(mbBuf
, psz
) != 0 )
2099 // we didn't obtain the same thing we started from, hence
2100 // the conversion was lossy and we consider that it failed
2101 return wxCONV_FAILED
;
2105 // note that it returns count of written chars for buf != NULL and size
2106 // of the needed buffer for buf == NULL so in either case the length of
2107 // the string (which never includes the terminating NUL) is one less
2111 virtual size_t WC2MB(char *buf
, const wchar_t *pwz
, size_t n
) const
2114 we have a problem here: by default, WideCharToMultiByte() may
2115 replace characters unrepresentable in the target code page with bad
2116 quality approximations such as turning "1/2" symbol (U+00BD) into
2117 "1" for the code pages which don't have it and we, obviously, want
2118 to avoid this at any price
2120 the trouble is that this function does it _silently_, i.e. it won't
2121 even tell us whether it did or not... Win98/2000 and higher provide
2122 WC_NO_BEST_FIT_CHARS but it doesn't work for the older systems and
2123 we have to resort to a round trip, i.e. check that converting back
2124 results in the same string -- this is, of course, expensive but
2125 otherwise we simply can't be sure to not garble the data.
2128 // determine if we can rely on WC_NO_BEST_FIT_CHARS: according to MSDN
2129 // it doesn't work with CJK encodings (which we test for rather roughly
2130 // here...) nor with UTF-7/8 nor, of course, with Windows versions not
2132 BOOL usedDef
wxDUMMY_INITIALIZE(false);
2135 if ( CanUseNoBestFit() && m_CodePage
< 50000 )
2137 // it's our lucky day
2138 flags
= WC_NO_BEST_FIT_CHARS
;
2139 pUsedDef
= &usedDef
;
2141 else // old system or unsupported encoding
2147 const size_t len
= ::WideCharToMultiByte
2149 m_CodePage
, // code page
2150 flags
, // either none or no best fit
2151 pwz
, // input string
2152 -1, // it is (wide) NUL-terminated
2153 buf
, // output buffer
2154 buf
? n
: 0, // and its size
2155 NULL
, // default "replacement" char
2156 pUsedDef
// [out] was it used?
2161 // function totally failed
2162 return wxCONV_FAILED
;
2165 // if we were really converting, check if we succeeded
2170 // check if the conversion failed, i.e. if any replacements
2173 return wxCONV_FAILED
;
2175 else // we must resort to double tripping...
2177 wxWCharBuffer
wcBuf(n
);
2178 if ( MB2WC(wcBuf
.data(), buf
, n
) == wxCONV_FAILED
||
2179 wcscmp(wcBuf
, pwz
) != 0 )
2181 // we didn't obtain the same thing we started from, hence
2182 // the conversion was lossy and we consider that it failed
2183 return wxCONV_FAILED
;
2188 // see the comment above for the reason of "len - 1"
2192 virtual size_t GetMBNulLen() const
2194 if ( m_minMBCharWidth
== 0 )
2196 int len
= ::WideCharToMultiByte
2198 m_CodePage
, // code page
2200 L
"", // input string
2201 1, // translate just the NUL
2202 NULL
, // output buffer
2204 NULL
, // no replacement char
2205 NULL
// [out] don't care if it was used
2208 wxMBConv_win32
* const self
= wxConstCast(this, wxMBConv_win32
);
2212 wxLogDebug(_T("Unexpected NUL length %d"), len
);
2213 self
->m_minMBCharWidth
= (size_t)-1;
2217 self
->m_minMBCharWidth
= (size_t)-1;
2223 self
->m_minMBCharWidth
= len
;
2228 return m_minMBCharWidth
;
2231 virtual wxMBConv
*Clone() const { return new wxMBConv_win32(*this); }
2233 bool IsOk() const { return m_CodePage
!= -1; }
2236 static bool CanUseNoBestFit()
2238 static int s_isWin98Or2k
= -1;
2240 if ( s_isWin98Or2k
== -1 )
2243 switch ( wxGetOsVersion(&verMaj
, &verMin
) )
2245 case wxOS_WINDOWS_9X
:
2246 s_isWin98Or2k
= verMaj
>= 4 && verMin
>= 10;
2249 case wxOS_WINDOWS_NT
:
2250 s_isWin98Or2k
= verMaj
>= 5;
2254 // unknown: be conservative by default
2259 wxASSERT_MSG( s_isWin98Or2k
!= -1, _T("should be set above") );
2262 return s_isWin98Or2k
== 1;
2265 static bool IsAtLeastWin2kSP4()
2270 static int s_isAtLeastWin2kSP4
= -1;
2272 if ( s_isAtLeastWin2kSP4
== -1 )
2274 OSVERSIONINFOEX ver
;
2276 memset(&ver
, 0, sizeof(ver
));
2277 ver
.dwOSVersionInfoSize
= sizeof(ver
);
2278 GetVersionEx((OSVERSIONINFO
*)&ver
);
2280 s_isAtLeastWin2kSP4
=
2281 ((ver
.dwMajorVersion
> 5) || // Vista+
2282 (ver
.dwMajorVersion
== 5 && ver
.dwMinorVersion
> 0) || // XP/2003
2283 (ver
.dwMajorVersion
== 5 && ver
.dwMinorVersion
== 0 &&
2284 ver
.wServicePackMajor
>= 4)) // 2000 SP4+
2288 return s_isAtLeastWin2kSP4
== 1;
2293 // the code page we're working with
2296 // cached result of GetMBNulLen(), set to 0 initially meaning
2298 size_t m_minMBCharWidth
;
2301 #endif // wxHAVE_WIN32_MB2WC
2303 // ============================================================================
2304 // Cocoa conversion classes
2305 // ============================================================================
2307 #if defined(__WXCOCOA__)
2309 // RN: There is no UTF-32 support in either Core Foundation or Cocoa.
2310 // Strangely enough, internally Core Foundation uses
2311 // UTF-32 internally quite a bit - its just not public (yet).
2313 #include <CoreFoundation/CFString.h>
2314 #include <CoreFoundation/CFStringEncodingExt.h>
2316 CFStringEncoding
wxCFStringEncFromFontEnc(wxFontEncoding encoding
)
2318 CFStringEncoding enc
= kCFStringEncodingInvalidId
;
2322 case wxFONTENCODING_DEFAULT
:
2323 enc
= CFStringGetSystemEncoding();
2326 case wxFONTENCODING_ISO8859_1
:
2327 enc
= kCFStringEncodingISOLatin1
;
2329 case wxFONTENCODING_ISO8859_2
:
2330 enc
= kCFStringEncodingISOLatin2
;
2332 case wxFONTENCODING_ISO8859_3
:
2333 enc
= kCFStringEncodingISOLatin3
;
2335 case wxFONTENCODING_ISO8859_4
:
2336 enc
= kCFStringEncodingISOLatin4
;
2338 case wxFONTENCODING_ISO8859_5
:
2339 enc
= kCFStringEncodingISOLatinCyrillic
;
2341 case wxFONTENCODING_ISO8859_6
:
2342 enc
= kCFStringEncodingISOLatinArabic
;
2344 case wxFONTENCODING_ISO8859_7
:
2345 enc
= kCFStringEncodingISOLatinGreek
;
2347 case wxFONTENCODING_ISO8859_8
:
2348 enc
= kCFStringEncodingISOLatinHebrew
;
2350 case wxFONTENCODING_ISO8859_9
:
2351 enc
= kCFStringEncodingISOLatin5
;
2353 case wxFONTENCODING_ISO8859_10
:
2354 enc
= kCFStringEncodingISOLatin6
;
2356 case wxFONTENCODING_ISO8859_11
:
2357 enc
= kCFStringEncodingISOLatinThai
;
2359 case wxFONTENCODING_ISO8859_13
:
2360 enc
= kCFStringEncodingISOLatin7
;
2362 case wxFONTENCODING_ISO8859_14
:
2363 enc
= kCFStringEncodingISOLatin8
;
2365 case wxFONTENCODING_ISO8859_15
:
2366 enc
= kCFStringEncodingISOLatin9
;
2369 case wxFONTENCODING_KOI8
:
2370 enc
= kCFStringEncodingKOI8_R
;
2372 case wxFONTENCODING_ALTERNATIVE
: // MS-DOS CP866
2373 enc
= kCFStringEncodingDOSRussian
;
2376 // case wxFONTENCODING_BULGARIAN :
2380 case wxFONTENCODING_CP437
:
2381 enc
= kCFStringEncodingDOSLatinUS
;
2383 case wxFONTENCODING_CP850
:
2384 enc
= kCFStringEncodingDOSLatin1
;
2386 case wxFONTENCODING_CP852
:
2387 enc
= kCFStringEncodingDOSLatin2
;
2389 case wxFONTENCODING_CP855
:
2390 enc
= kCFStringEncodingDOSCyrillic
;
2392 case wxFONTENCODING_CP866
:
2393 enc
= kCFStringEncodingDOSRussian
;
2395 case wxFONTENCODING_CP874
:
2396 enc
= kCFStringEncodingDOSThai
;
2398 case wxFONTENCODING_CP932
:
2399 enc
= kCFStringEncodingDOSJapanese
;
2401 case wxFONTENCODING_CP936
:
2402 enc
= kCFStringEncodingDOSChineseSimplif
;
2404 case wxFONTENCODING_CP949
:
2405 enc
= kCFStringEncodingDOSKorean
;
2407 case wxFONTENCODING_CP950
:
2408 enc
= kCFStringEncodingDOSChineseTrad
;
2410 case wxFONTENCODING_CP1250
:
2411 enc
= kCFStringEncodingWindowsLatin2
;
2413 case wxFONTENCODING_CP1251
:
2414 enc
= kCFStringEncodingWindowsCyrillic
;
2416 case wxFONTENCODING_CP1252
:
2417 enc
= kCFStringEncodingWindowsLatin1
;
2419 case wxFONTENCODING_CP1253
:
2420 enc
= kCFStringEncodingWindowsGreek
;
2422 case wxFONTENCODING_CP1254
:
2423 enc
= kCFStringEncodingWindowsLatin5
;
2425 case wxFONTENCODING_CP1255
:
2426 enc
= kCFStringEncodingWindowsHebrew
;
2428 case wxFONTENCODING_CP1256
:
2429 enc
= kCFStringEncodingWindowsArabic
;
2431 case wxFONTENCODING_CP1257
:
2432 enc
= kCFStringEncodingWindowsBalticRim
;
2434 // This only really encodes to UTF7 (if that) evidently
2435 // case wxFONTENCODING_UTF7 :
2436 // enc = kCFStringEncodingNonLossyASCII ;
2438 case wxFONTENCODING_UTF8
:
2439 enc
= kCFStringEncodingUTF8
;
2441 case wxFONTENCODING_EUC_JP
:
2442 enc
= kCFStringEncodingEUC_JP
;
2444 case wxFONTENCODING_UTF16
:
2445 enc
= kCFStringEncodingUnicode
;
2447 case wxFONTENCODING_MACROMAN
:
2448 enc
= kCFStringEncodingMacRoman
;
2450 case wxFONTENCODING_MACJAPANESE
:
2451 enc
= kCFStringEncodingMacJapanese
;
2453 case wxFONTENCODING_MACCHINESETRAD
:
2454 enc
= kCFStringEncodingMacChineseTrad
;
2456 case wxFONTENCODING_MACKOREAN
:
2457 enc
= kCFStringEncodingMacKorean
;
2459 case wxFONTENCODING_MACARABIC
:
2460 enc
= kCFStringEncodingMacArabic
;
2462 case wxFONTENCODING_MACHEBREW
:
2463 enc
= kCFStringEncodingMacHebrew
;
2465 case wxFONTENCODING_MACGREEK
:
2466 enc
= kCFStringEncodingMacGreek
;
2468 case wxFONTENCODING_MACCYRILLIC
:
2469 enc
= kCFStringEncodingMacCyrillic
;
2471 case wxFONTENCODING_MACDEVANAGARI
:
2472 enc
= kCFStringEncodingMacDevanagari
;
2474 case wxFONTENCODING_MACGURMUKHI
:
2475 enc
= kCFStringEncodingMacGurmukhi
;
2477 case wxFONTENCODING_MACGUJARATI
:
2478 enc
= kCFStringEncodingMacGujarati
;
2480 case wxFONTENCODING_MACORIYA
:
2481 enc
= kCFStringEncodingMacOriya
;
2483 case wxFONTENCODING_MACBENGALI
:
2484 enc
= kCFStringEncodingMacBengali
;
2486 case wxFONTENCODING_MACTAMIL
:
2487 enc
= kCFStringEncodingMacTamil
;
2489 case wxFONTENCODING_MACTELUGU
:
2490 enc
= kCFStringEncodingMacTelugu
;
2492 case wxFONTENCODING_MACKANNADA
:
2493 enc
= kCFStringEncodingMacKannada
;
2495 case wxFONTENCODING_MACMALAJALAM
:
2496 enc
= kCFStringEncodingMacMalayalam
;
2498 case wxFONTENCODING_MACSINHALESE
:
2499 enc
= kCFStringEncodingMacSinhalese
;
2501 case wxFONTENCODING_MACBURMESE
:
2502 enc
= kCFStringEncodingMacBurmese
;
2504 case wxFONTENCODING_MACKHMER
:
2505 enc
= kCFStringEncodingMacKhmer
;
2507 case wxFONTENCODING_MACTHAI
:
2508 enc
= kCFStringEncodingMacThai
;
2510 case wxFONTENCODING_MACLAOTIAN
:
2511 enc
= kCFStringEncodingMacLaotian
;
2513 case wxFONTENCODING_MACGEORGIAN
:
2514 enc
= kCFStringEncodingMacGeorgian
;
2516 case wxFONTENCODING_MACARMENIAN
:
2517 enc
= kCFStringEncodingMacArmenian
;
2519 case wxFONTENCODING_MACCHINESESIMP
:
2520 enc
= kCFStringEncodingMacChineseSimp
;
2522 case wxFONTENCODING_MACTIBETAN
:
2523 enc
= kCFStringEncodingMacTibetan
;
2525 case wxFONTENCODING_MACMONGOLIAN
:
2526 enc
= kCFStringEncodingMacMongolian
;
2528 case wxFONTENCODING_MACETHIOPIC
:
2529 enc
= kCFStringEncodingMacEthiopic
;
2531 case wxFONTENCODING_MACCENTRALEUR
:
2532 enc
= kCFStringEncodingMacCentralEurRoman
;
2534 case wxFONTENCODING_MACVIATNAMESE
:
2535 enc
= kCFStringEncodingMacVietnamese
;
2537 case wxFONTENCODING_MACARABICEXT
:
2538 enc
= kCFStringEncodingMacExtArabic
;
2540 case wxFONTENCODING_MACSYMBOL
:
2541 enc
= kCFStringEncodingMacSymbol
;
2543 case wxFONTENCODING_MACDINGBATS
:
2544 enc
= kCFStringEncodingMacDingbats
;
2546 case wxFONTENCODING_MACTURKISH
:
2547 enc
= kCFStringEncodingMacTurkish
;
2549 case wxFONTENCODING_MACCROATIAN
:
2550 enc
= kCFStringEncodingMacCroatian
;
2552 case wxFONTENCODING_MACICELANDIC
:
2553 enc
= kCFStringEncodingMacIcelandic
;
2555 case wxFONTENCODING_MACROMANIAN
:
2556 enc
= kCFStringEncodingMacRomanian
;
2558 case wxFONTENCODING_MACCELTIC
:
2559 enc
= kCFStringEncodingMacCeltic
;
2561 case wxFONTENCODING_MACGAELIC
:
2562 enc
= kCFStringEncodingMacGaelic
;
2564 // case wxFONTENCODING_MACKEYBOARD :
2565 // enc = kCFStringEncodingMacKeyboardGlyphs ;
2569 // because gcc is picky
2576 class wxMBConv_cocoa
: public wxMBConv
2581 Init(CFStringGetSystemEncoding()) ;
2584 wxMBConv_cocoa(const wxMBConv_cocoa
& conv
)
2586 m_encoding
= conv
.m_encoding
;
2590 wxMBConv_cocoa(const wxChar
* name
)
2592 Init( wxCFStringEncFromFontEnc(wxFontMapperBase::Get()->CharsetToEncoding(name
, false) ) ) ;
2596 wxMBConv_cocoa(wxFontEncoding encoding
)
2598 Init( wxCFStringEncFromFontEnc(encoding
) );
2601 virtual ~wxMBConv_cocoa()
2605 void Init( CFStringEncoding encoding
)
2607 m_encoding
= encoding
;
2610 size_t MB2WC(wchar_t * szOut
, const char * szUnConv
, size_t nOutSize
) const
2614 CFStringRef theString
= CFStringCreateWithBytes (
2615 NULL
, //the allocator
2616 (const UInt8
*)szUnConv
,
2619 false //no BOM/external representation
2622 wxASSERT(theString
);
2624 size_t nOutLength
= CFStringGetLength(theString
);
2628 CFRelease(theString
);
2632 CFRange theRange
= { 0, nOutSize
};
2634 #if SIZEOF_WCHAR_T == 4
2635 UniChar
* szUniCharBuffer
= new UniChar
[nOutSize
];
2638 CFStringGetCharacters(theString
, theRange
, szUniCharBuffer
);
2640 CFRelease(theString
);
2642 szUniCharBuffer
[nOutLength
] = '\0';
2644 #if SIZEOF_WCHAR_T == 4
2645 wxMBConvUTF16 converter
;
2646 converter
.MB2WC( szOut
, (const char*)szUniCharBuffer
, nOutSize
);
2647 delete [] szUniCharBuffer
;
2653 size_t WC2MB(char *szOut
, const wchar_t *szUnConv
, size_t nOutSize
) const
2657 size_t nRealOutSize
;
2658 size_t nBufSize
= wxWcslen(szUnConv
);
2659 UniChar
* szUniBuffer
= (UniChar
*) szUnConv
;
2661 #if SIZEOF_WCHAR_T == 4
2662 wxMBConvUTF16 converter
;
2663 nBufSize
= converter
.WC2MB( NULL
, szUnConv
, 0 );
2664 szUniBuffer
= new UniChar
[ (nBufSize
/ sizeof(UniChar
)) + 1];
2665 converter
.WC2MB( (char*) szUniBuffer
, szUnConv
, nBufSize
+ sizeof(UniChar
));
2666 nBufSize
/= sizeof(UniChar
);
2669 CFStringRef theString
= CFStringCreateWithCharactersNoCopy(
2673 kCFAllocatorNull
//deallocator - we want to deallocate it ourselves
2676 wxASSERT(theString
);
2678 //Note that CER puts a BOM when converting to unicode
2679 //so we check and use getchars instead in that case
2680 if (m_encoding
== kCFStringEncodingUnicode
)
2683 CFStringGetCharacters(theString
, CFRangeMake(0, nOutSize
- 1), (UniChar
*) szOut
);
2685 nRealOutSize
= CFStringGetLength(theString
) + 1;
2691 CFRangeMake(0, CFStringGetLength(theString
)),
2693 0, //what to put in characters that can't be converted -
2694 //0 tells CFString to return NULL if it meets such a character
2695 false, //not an external representation
2698 (CFIndex
*) &nRealOutSize
2702 CFRelease(theString
);
2704 #if SIZEOF_WCHAR_T == 4
2705 delete[] szUniBuffer
;
2708 return nRealOutSize
- 1;
2711 virtual wxMBConv
*Clone() const { return new wxMBConv_cocoa(*this); }
2715 return m_encoding
!= kCFStringEncodingInvalidId
&&
2716 CFStringIsEncodingAvailable(m_encoding
);
2720 CFStringEncoding m_encoding
;
2723 #endif // defined(__WXCOCOA__)
2725 // ============================================================================
2726 // Mac conversion classes
2727 // ============================================================================
2729 #if defined(__WXMAC__) && defined(TARGET_CARBON)
2731 class wxMBConv_mac
: public wxMBConv
2736 Init(CFStringGetSystemEncoding()) ;
2739 wxMBConv_mac(const wxMBConv_mac
& conv
)
2741 Init(conv
.m_char_encoding
);
2745 wxMBConv_mac(const wxChar
* name
)
2747 Init( wxMacGetSystemEncFromFontEnc( wxFontMapperBase::Get()->CharsetToEncoding(name
, false) ) );
2751 wxMBConv_mac(wxFontEncoding encoding
)
2753 Init( wxMacGetSystemEncFromFontEnc(encoding
) );
2756 virtual ~wxMBConv_mac()
2758 OSStatus status
= noErr
;
2759 if (m_MB2WC_converter
)
2760 status
= TECDisposeConverter(m_MB2WC_converter
);
2761 if (m_WC2MB_converter
)
2762 status
= TECDisposeConverter(m_WC2MB_converter
);
2765 void Init( TextEncodingBase encoding
,TextEncodingVariant encodingVariant
= kTextEncodingDefaultVariant
,
2766 TextEncodingFormat encodingFormat
= kTextEncodingDefaultFormat
)
2768 m_MB2WC_converter
= NULL
;
2769 m_WC2MB_converter
= NULL
;
2770 m_char_encoding
= CreateTextEncoding(encoding
, encodingVariant
, encodingFormat
) ;
2771 m_unicode_encoding
= CreateTextEncoding(kTextEncodingUnicodeDefault
, 0, kUnicode16BitFormat
) ;
2774 virtual void CreateIfNeeded() const
2776 if ( m_MB2WC_converter
== NULL
&& m_WC2MB_converter
== NULL
)
2778 OSStatus status
= noErr
;
2779 status
= TECCreateConverter(&m_MB2WC_converter
,
2781 m_unicode_encoding
);
2782 wxASSERT_MSG( status
== noErr
, _("Unable to create TextEncodingConverter")) ;
2783 status
= TECCreateConverter(&m_WC2MB_converter
,
2786 wxASSERT_MSG( status
== noErr
, _("Unable to create TextEncodingConverter")) ;
2790 size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2793 OSStatus status
= noErr
;
2794 ByteCount byteOutLen
;
2795 ByteCount byteInLen
= strlen(psz
) + 1;
2796 wchar_t *tbuf
= NULL
;
2797 UniChar
* ubuf
= NULL
;
2802 // Apple specs say at least 32
2803 n
= wxMax( 32, byteInLen
) ;
2804 tbuf
= (wchar_t*) malloc( n
* SIZEOF_WCHAR_T
) ;
2807 ByteCount byteBufferLen
= n
* sizeof( UniChar
) ;
2809 #if SIZEOF_WCHAR_T == 4
2810 ubuf
= (UniChar
*) malloc( byteBufferLen
+ 2 ) ;
2812 ubuf
= (UniChar
*) (buf
? buf
: tbuf
) ;
2815 status
= TECConvertText(
2816 m_MB2WC_converter
, (ConstTextPtr
) psz
, byteInLen
, &byteInLen
,
2817 (TextPtr
) ubuf
, byteBufferLen
, &byteOutLen
);
2819 #if SIZEOF_WCHAR_T == 4
2820 // we have to terminate here, because n might be larger for the trailing zero, and if UniChar
2821 // is not properly terminated we get random characters at the end
2822 ubuf
[byteOutLen
/ sizeof( UniChar
) ] = 0 ;
2823 wxMBConvUTF16 converter
;
2824 res
= converter
.MB2WC( (buf
? buf
: tbuf
), (const char*)ubuf
, n
) ;
2827 res
= byteOutLen
/ sizeof( UniChar
) ;
2833 if ( buf
&& res
< n
)
2839 size_t WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2842 OSStatus status
= noErr
;
2843 ByteCount byteOutLen
;
2844 ByteCount byteInLen
= wxWcslen(psz
) * SIZEOF_WCHAR_T
;
2850 // Apple specs say at least 32
2851 n
= wxMax( 32, ((byteInLen
/ SIZEOF_WCHAR_T
) * 8) + SIZEOF_WCHAR_T
);
2852 tbuf
= (char*) malloc( n
) ;
2855 ByteCount byteBufferLen
= n
;
2856 UniChar
* ubuf
= NULL
;
2858 #if SIZEOF_WCHAR_T == 4
2859 wxMBConvUTF16 converter
;
2860 size_t unicharlen
= converter
.WC2MB( NULL
, psz
, 0 ) ;
2861 byteInLen
= unicharlen
;
2862 ubuf
= (UniChar
*) malloc( byteInLen
+ 2 ) ;
2863 converter
.WC2MB( (char*) ubuf
, psz
, unicharlen
+ 2 ) ;
2865 ubuf
= (UniChar
*) psz
;
2868 status
= TECConvertText(
2869 m_WC2MB_converter
, (ConstTextPtr
) ubuf
, byteInLen
, &byteInLen
,
2870 (TextPtr
) (buf
? buf
: tbuf
), byteBufferLen
, &byteOutLen
);
2872 #if SIZEOF_WCHAR_T == 4
2879 size_t res
= byteOutLen
;
2880 if ( buf
&& res
< n
)
2884 //we need to double-trip to verify it didn't insert any ? in place
2885 //of bogus characters
2886 wxWCharBuffer
wcBuf(n
);
2887 size_t pszlen
= wxWcslen(psz
);
2888 if ( MB2WC(wcBuf
.data(), buf
, n
) == wxCONV_FAILED
||
2889 wxWcslen(wcBuf
) != pszlen
||
2890 memcmp(wcBuf
, psz
, pszlen
* sizeof(wchar_t)) != 0 )
2892 // we didn't obtain the same thing we started from, hence
2893 // the conversion was lossy and we consider that it failed
2894 return wxCONV_FAILED
;
2901 virtual wxMBConv
*Clone() const { return new wxMBConv_mac(*this); }
2906 return m_MB2WC_converter
!= NULL
&& m_WC2MB_converter
!= NULL
;
2910 mutable TECObjectRef m_MB2WC_converter
;
2911 mutable TECObjectRef m_WC2MB_converter
;
2913 TextEncodingBase m_char_encoding
;
2914 TextEncodingBase m_unicode_encoding
;
2917 // MB is decomposed (D) normalized UTF8
2919 class wxMBConv_macUTF8D
: public wxMBConv_mac
2924 Init( kTextEncodingUnicodeDefault
, kUnicodeNoSubset
, kUnicodeUTF8Format
) ;
2929 virtual ~wxMBConv_macUTF8D()
2932 DisposeUnicodeToTextInfo(&m_uni
);
2933 if (m_uniBack
!=NULL
)
2934 DisposeUnicodeToTextInfo(&m_uniBack
);
2937 size_t WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2940 OSStatus status
= noErr
;
2941 ByteCount byteOutLen
;
2942 ByteCount byteInLen
= wxWcslen(psz
) * SIZEOF_WCHAR_T
;
2948 // Apple specs say at least 32
2949 n
= wxMax( 32, ((byteInLen
/ SIZEOF_WCHAR_T
) * 8) + SIZEOF_WCHAR_T
);
2950 tbuf
= (char*) malloc( n
) ;
2953 ByteCount byteBufferLen
= n
;
2954 UniChar
* ubuf
= NULL
;
2956 #if SIZEOF_WCHAR_T == 4
2957 wxMBConvUTF16 converter
;
2958 size_t unicharlen
= converter
.WC2MB( NULL
, psz
, 0 ) ;
2959 byteInLen
= unicharlen
;
2960 ubuf
= (UniChar
*) malloc( byteInLen
+ 2 ) ;
2961 converter
.WC2MB( (char*) ubuf
, psz
, unicharlen
+ 2 ) ;
2963 ubuf
= (UniChar
*) psz
;
2966 // ubuf is a non-decomposed UniChar buffer
2968 ByteCount dcubuflen
= byteInLen
* 2 + 2 ;
2969 ByteCount dcubufread
, dcubufwritten
;
2970 UniChar
*dcubuf
= (UniChar
*) malloc( dcubuflen
) ;
2972 ConvertFromUnicodeToText( m_uni
, byteInLen
, ubuf
,
2973 kUnicodeDefaultDirectionMask
, 0, NULL
, NULL
, NULL
, dcubuflen
, &dcubufread
, &dcubufwritten
, dcubuf
) ;
2975 // we now convert that decomposed buffer into UTF8
2977 status
= TECConvertText(
2978 m_WC2MB_converter
, (ConstTextPtr
) dcubuf
, dcubufwritten
, &dcubufread
,
2979 (TextPtr
) (buf
? buf
: tbuf
), byteBufferLen
, &byteOutLen
);
2983 #if SIZEOF_WCHAR_T == 4
2990 size_t res
= byteOutLen
;
2991 if ( buf
&& res
< n
)
2994 // don't test for round-trip fidelity yet, we cannot guarantee it yet
3000 size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
3003 OSStatus status
= noErr
;
3004 ByteCount byteOutLen
;
3005 ByteCount byteInLen
= strlen(psz
) + 1;
3006 wchar_t *tbuf
= NULL
;
3007 UniChar
* ubuf
= NULL
;
3012 // Apple specs say at least 32
3013 n
= wxMax( 32, byteInLen
) ;
3014 tbuf
= (wchar_t*) malloc( n
* SIZEOF_WCHAR_T
) ;
3017 ByteCount byteBufferLen
= n
* sizeof( UniChar
) ;
3019 #if SIZEOF_WCHAR_T == 4
3020 ubuf
= (UniChar
*) malloc( byteBufferLen
+ 2 ) ;
3022 ubuf
= (UniChar
*) (buf
? buf
: tbuf
) ;
3025 ByteCount dcubuflen
= byteBufferLen
* 2 + 2 ;
3026 ByteCount dcubufread
, dcubufwritten
;
3027 UniChar
*dcubuf
= (UniChar
*) malloc( dcubuflen
) ;
3029 status
= TECConvertText(
3030 m_MB2WC_converter
, (ConstTextPtr
) psz
, byteInLen
, &byteInLen
,
3031 (TextPtr
) dcubuf
, dcubuflen
, &byteOutLen
);
3032 // we have to terminate here, because n might be larger for the trailing zero, and if UniChar
3033 // is not properly terminated we get random characters at the end
3034 dcubuf
[byteOutLen
/ sizeof( UniChar
) ] = 0 ;
3036 // now from the decomposed UniChar to properly composed uniChar
3037 ConvertFromUnicodeToText( m_uniBack
, byteOutLen
, dcubuf
,
3038 kUnicodeDefaultDirectionMask
, 0, NULL
, NULL
, NULL
, dcubuflen
, &dcubufread
, &dcubufwritten
, ubuf
) ;
3041 byteOutLen
= dcubufwritten
;
3042 ubuf
[byteOutLen
/ sizeof( UniChar
) ] = 0 ;
3045 #if SIZEOF_WCHAR_T == 4
3046 wxMBConvUTF16 converter
;
3047 res
= converter
.MB2WC( (buf
? buf
: tbuf
), (const char*)ubuf
, n
) ;
3050 res
= byteOutLen
/ sizeof( UniChar
) ;
3056 if ( buf
&& res
< n
)
3062 virtual void CreateIfNeeded() const
3064 wxMBConv_mac::CreateIfNeeded() ;
3065 if ( m_uni
== NULL
)
3067 m_map
.unicodeEncoding
= CreateTextEncoding(kTextEncodingUnicodeDefault
,
3068 kUnicodeNoSubset
, kTextEncodingDefaultFormat
);
3069 m_map
.otherEncoding
= CreateTextEncoding(kTextEncodingUnicodeDefault
,
3070 kUnicodeCanonicalDecompVariant
, kTextEncodingDefaultFormat
);
3071 m_map
.mappingVersion
= kUnicodeUseLatestMapping
;
3073 OSStatus err
= CreateUnicodeToTextInfo(&m_map
, &m_uni
);
3074 wxASSERT_MSG( err
== noErr
, _(" Couldn't create the UnicodeConverter")) ;
3076 m_map
.unicodeEncoding
= CreateTextEncoding(kTextEncodingUnicodeDefault
,
3077 kUnicodeNoSubset
, kTextEncodingDefaultFormat
);
3078 m_map
.otherEncoding
= CreateTextEncoding(kTextEncodingUnicodeDefault
,
3079 kUnicodeCanonicalCompVariant
, kTextEncodingDefaultFormat
);
3080 m_map
.mappingVersion
= kUnicodeUseLatestMapping
;
3081 err
= CreateUnicodeToTextInfo(&m_map
, &m_uniBack
);
3082 wxASSERT_MSG( err
== noErr
, _(" Couldn't create the UnicodeConverter")) ;
3086 mutable UnicodeToTextInfo m_uni
;
3087 mutable UnicodeToTextInfo m_uniBack
;
3088 mutable UnicodeMapping m_map
;
3090 #endif // defined(__WXMAC__) && defined(TARGET_CARBON)
3092 // ============================================================================
3093 // wxEncodingConverter based conversion classes
3094 // ============================================================================
3098 class wxMBConv_wxwin
: public wxMBConv
3103 m_ok
= m2w
.Init(m_enc
, wxFONTENCODING_UNICODE
) &&
3104 w2m
.Init(wxFONTENCODING_UNICODE
, m_enc
);
3108 // temporarily just use wxEncodingConverter stuff,
3109 // so that it works while a better implementation is built
3110 wxMBConv_wxwin(const wxChar
* name
)
3113 m_enc
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
3115 m_enc
= wxFONTENCODING_SYSTEM
;
3120 wxMBConv_wxwin(wxFontEncoding enc
)
3127 size_t MB2WC(wchar_t *buf
, const char *psz
, size_t WXUNUSED(n
)) const
3129 size_t inbuf
= strlen(psz
);
3132 if (!m2w
.Convert(psz
, buf
))
3133 return wxCONV_FAILED
;
3138 size_t WC2MB(char *buf
, const wchar_t *psz
, size_t WXUNUSED(n
)) const
3140 const size_t inbuf
= wxWcslen(psz
);
3143 if (!w2m
.Convert(psz
, buf
))
3144 return wxCONV_FAILED
;
3150 virtual size_t GetMBNulLen() const
3154 case wxFONTENCODING_UTF16BE
:
3155 case wxFONTENCODING_UTF16LE
:
3158 case wxFONTENCODING_UTF32BE
:
3159 case wxFONTENCODING_UTF32LE
:
3167 virtual wxMBConv
*Clone() const { return new wxMBConv_wxwin(m_enc
); }
3169 bool IsOk() const { return m_ok
; }
3172 wxFontEncoding m_enc
;
3173 wxEncodingConverter m2w
, w2m
;
3176 // were we initialized successfully?
3179 DECLARE_NO_COPY_CLASS(wxMBConv_wxwin
)
3182 // make the constructors available for unit testing
3183 WXDLLIMPEXP_BASE wxMBConv
* new_wxMBConv_wxwin( const wxChar
* name
)
3185 wxMBConv_wxwin
* result
= new wxMBConv_wxwin( name
);
3186 if ( !result
->IsOk() )
3195 #endif // wxUSE_FONTMAP
3197 // ============================================================================
3198 // wxCSConv implementation
3199 // ============================================================================
3201 void wxCSConv::Init()
3208 wxCSConv::wxCSConv(const wxChar
*charset
)
3218 m_encoding
= wxFontMapperBase::GetEncodingFromName(charset
);
3220 m_encoding
= wxFONTENCODING_SYSTEM
;
3224 wxCSConv::wxCSConv(wxFontEncoding encoding
)
3226 if ( encoding
== wxFONTENCODING_MAX
|| encoding
== wxFONTENCODING_DEFAULT
)
3228 wxFAIL_MSG( _T("invalid encoding value in wxCSConv ctor") );
3230 encoding
= wxFONTENCODING_SYSTEM
;
3235 m_encoding
= encoding
;
3238 wxCSConv::~wxCSConv()
3243 wxCSConv::wxCSConv(const wxCSConv
& conv
)
3248 SetName(conv
.m_name
);
3249 m_encoding
= conv
.m_encoding
;
3252 wxCSConv
& wxCSConv::operator=(const wxCSConv
& conv
)
3256 SetName(conv
.m_name
);
3257 m_encoding
= conv
.m_encoding
;
3262 void wxCSConv::Clear()
3271 void wxCSConv::SetName(const wxChar
*charset
)
3275 m_name
= wxStrdup(charset
);
3282 WX_DECLARE_HASH_MAP( wxFontEncoding
, wxString
, wxIntegerHash
, wxIntegerEqual
,
3283 wxEncodingNameCache
);
3285 static wxEncodingNameCache gs_nameCache
;
3288 wxMBConv
*wxCSConv::DoCreate() const
3291 wxLogTrace(TRACE_STRCONV
,
3292 wxT("creating conversion for %s"),
3294 : (const wxChar
*)wxFontMapperBase::GetEncodingName(m_encoding
).c_str()));
3295 #endif // wxUSE_FONTMAP
3297 // check for the special case of ASCII or ISO8859-1 charset: as we have
3298 // special knowledge of it anyhow, we don't need to create a special
3299 // conversion object
3300 if ( m_encoding
== wxFONTENCODING_ISO8859_1
||
3301 m_encoding
== wxFONTENCODING_DEFAULT
)
3303 // don't convert at all
3307 // we trust OS to do conversion better than we can so try external
3308 // conversion methods first
3310 // the full order is:
3311 // 1. OS conversion (iconv() under Unix or Win32 API)
3312 // 2. hard coded conversions for UTF
3313 // 3. wxEncodingConverter as fall back
3319 #endif // !wxUSE_FONTMAP
3321 wxString
name(m_name
);
3323 wxFontEncoding
encoding(m_encoding
);
3326 if ( !name
.empty() )
3328 wxMBConv_iconv
*conv
= new wxMBConv_iconv(name
);
3336 wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
3337 #endif // wxUSE_FONTMAP
3341 const wxEncodingNameCache::iterator it
= gs_nameCache
.find(encoding
);
3342 if ( it
!= gs_nameCache
.end() )
3344 if ( it
->second
.empty() )
3347 wxMBConv_iconv
*conv
= new wxMBConv_iconv(it
->second
);
3354 const wxChar
** names
= wxFontMapperBase::GetAllEncodingNames(encoding
);
3355 // CS : in case this does not return valid names (eg for MacRoman) encoding
3356 // got a 'failure' entry in the cache all the same, although it just has to
3357 // be created using a different method, so only store failed iconv creation
3358 // attempts (or perhaps we shoulnd't do this at all ?)
3359 if ( names
[0] != NULL
)
3361 for ( ; *names
; ++names
)
3363 wxMBConv_iconv
*conv
= new wxMBConv_iconv(*names
);
3366 gs_nameCache
[encoding
] = *names
;
3373 gs_nameCache
[encoding
] = _T(""); // cache the failure
3376 #endif // wxUSE_FONTMAP
3378 #endif // HAVE_ICONV
3380 #ifdef wxHAVE_WIN32_MB2WC
3383 wxMBConv_win32
*conv
= m_name
? new wxMBConv_win32(m_name
)
3384 : new wxMBConv_win32(m_encoding
);
3393 #endif // wxHAVE_WIN32_MB2WC
3395 #if defined(__WXMAC__)
3397 // leave UTF16 and UTF32 to the built-ins of wx
3398 if ( m_name
|| ( m_encoding
< wxFONTENCODING_UTF16BE
||
3399 ( m_encoding
>= wxFONTENCODING_MACMIN
&& m_encoding
<= wxFONTENCODING_MACMAX
) ) )
3402 wxMBConv_mac
*conv
= m_name
? new wxMBConv_mac(m_name
)
3403 : new wxMBConv_mac(m_encoding
);
3405 wxMBConv_mac
*conv
= new wxMBConv_mac(m_encoding
);
3415 #if defined(__WXCOCOA__)
3417 if ( m_name
|| ( m_encoding
<= wxFONTENCODING_UTF16
) )
3420 wxMBConv_cocoa
*conv
= m_name
? new wxMBConv_cocoa(m_name
)
3421 : new wxMBConv_cocoa(m_encoding
);
3423 wxMBConv_cocoa
*conv
= new wxMBConv_cocoa(m_encoding
);
3434 wxFontEncoding enc
= m_encoding
;
3436 if ( enc
== wxFONTENCODING_SYSTEM
&& m_name
)
3438 // use "false" to suppress interactive dialogs -- we can be called from
3439 // anywhere and popping up a dialog from here is the last thing we want to
3441 enc
= wxFontMapperBase::Get()->CharsetToEncoding(m_name
, false);
3443 #endif // wxUSE_FONTMAP
3447 case wxFONTENCODING_UTF7
:
3448 return new wxMBConvUTF7
;
3450 case wxFONTENCODING_UTF8
:
3451 return new wxMBConvUTF8
;
3453 case wxFONTENCODING_UTF16BE
:
3454 return new wxMBConvUTF16BE
;
3456 case wxFONTENCODING_UTF16LE
:
3457 return new wxMBConvUTF16LE
;
3459 case wxFONTENCODING_UTF32BE
:
3460 return new wxMBConvUTF32BE
;
3462 case wxFONTENCODING_UTF32LE
:
3463 return new wxMBConvUTF32LE
;
3466 // nothing to do but put here to suppress gcc warnings
3473 wxMBConv_wxwin
*conv
= m_name
? new wxMBConv_wxwin(m_name
)
3474 : new wxMBConv_wxwin(m_encoding
);
3480 #endif // wxUSE_FONTMAP
3482 // NB: This is a hack to prevent deadlock. What could otherwise happen
3483 // in Unicode build: wxConvLocal creation ends up being here
3484 // because of some failure and logs the error. But wxLog will try to
3485 // attach a timestamp, for which it will need wxConvLocal (to convert
3486 // time to char* and then wchar_t*), but that fails, tries to log the
3487 // error, but wxLog has an (already locked) critical section that
3488 // guards the static buffer.
3489 static bool alreadyLoggingError
= false;
3490 if (!alreadyLoggingError
)
3492 alreadyLoggingError
= true;
3493 wxLogError(_("Cannot convert from the charset '%s'!"),
3497 (const wxChar
*)wxFontMapperBase::GetEncodingDescription(m_encoding
).c_str()
3498 #else // !wxUSE_FONTMAP
3499 (const wxChar
*)wxString::Format(_("encoding %i"), m_encoding
).c_str()
3500 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
3503 alreadyLoggingError
= false;
3509 void wxCSConv::CreateConvIfNeeded() const
3513 wxCSConv
*self
= (wxCSConv
*)this; // const_cast
3515 // if we don't have neither the name nor the encoding, use the default
3516 // encoding for this system
3517 if ( !m_name
&& m_encoding
== wxFONTENCODING_SYSTEM
)
3520 self
->m_encoding
= wxLocale::GetSystemEncoding();
3522 // fallback to some reasonable default:
3523 self
->m_encoding
= wxFONTENCODING_ISO8859_1
;
3524 #endif // wxUSE_INTL
3527 self
->m_convReal
= DoCreate();
3528 self
->m_deferred
= false;
3532 bool wxCSConv::IsOk() const
3534 CreateConvIfNeeded();
3536 // special case: no convReal created for wxFONTENCODING_ISO8859_1
3537 if ( m_encoding
== wxFONTENCODING_ISO8859_1
)
3538 return true; // always ok as we do it ourselves
3540 // m_convReal->IsOk() is called at its own creation, so we know it must
3541 // be ok if m_convReal is non-NULL
3542 return m_convReal
!= NULL
;
3545 size_t wxCSConv::ToWChar(wchar_t *dst
, size_t dstLen
,
3546 const char *src
, size_t srcLen
) const
3548 CreateConvIfNeeded();
3551 return m_convReal
->ToWChar(dst
, dstLen
, src
, srcLen
);
3554 return wxMBConv::ToWChar(dst
, dstLen
, src
, srcLen
);
3557 size_t wxCSConv::FromWChar(char *dst
, size_t dstLen
,
3558 const wchar_t *src
, size_t srcLen
) const
3560 CreateConvIfNeeded();
3563 return m_convReal
->FromWChar(dst
, dstLen
, src
, srcLen
);
3566 return wxMBConv::FromWChar(dst
, dstLen
, src
, srcLen
);
3569 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
3571 CreateConvIfNeeded();
3574 return m_convReal
->MB2WC(buf
, psz
, n
);
3577 size_t len
= strlen(psz
);
3581 for (size_t c
= 0; c
<= len
; c
++)
3582 buf
[c
] = (unsigned char)(psz
[c
]);
3588 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
3590 CreateConvIfNeeded();
3593 return m_convReal
->WC2MB(buf
, psz
, n
);
3596 const size_t len
= wxWcslen(psz
);
3599 for (size_t c
= 0; c
<= len
; c
++)
3602 return wxCONV_FAILED
;
3604 buf
[c
] = (char)psz
[c
];
3609 for (size_t c
= 0; c
<= len
; c
++)
3612 return wxCONV_FAILED
;
3619 size_t wxCSConv::GetMBNulLen() const
3621 CreateConvIfNeeded();
3625 return m_convReal
->GetMBNulLen();
3628 // otherwise, we are ISO-8859-1
3632 #if wxUSE_UNICODE_UTF8
3633 bool wxCSConv::IsUTF8() const
3635 CreateConvIfNeeded();
3639 return m_convReal
->IsUTF8();
3642 // otherwise, we are ISO-8859-1
3650 wxWCharBuffer
wxSafeConvertMB2WX(const char *s
)
3653 return wxWCharBuffer();
3655 wxWCharBuffer
wbuf(wxConvLibc
.cMB2WX(s
));
3657 wbuf
= wxMBConvUTF8().cMB2WX(s
);
3659 wbuf
= wxConvISO8859_1
.cMB2WX(s
);
3664 wxCharBuffer
wxSafeConvertWX2MB(const wchar_t *ws
)
3667 return wxCharBuffer();
3669 wxCharBuffer
buf(wxConvLibc
.cWX2MB(ws
));
3671 buf
= wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_OCTAL
).cWX2MB(ws
);
3676 #endif // wxUSE_UNICODE
3678 // ----------------------------------------------------------------------------
3680 // ----------------------------------------------------------------------------
3682 // NB: The reason why we create converted objects in this convoluted way,
3683 // using a factory function instead of global variable, is that they
3684 // may be used at static initialization time (some of them are used by
3685 // wxString ctors and there may be a global wxString object). In other
3686 // words, possibly _before_ the converter global object would be
3693 #undef wxConvISO8859_1
3695 #define WX_DEFINE_GLOBAL_CONV2(klass, impl_klass, name, ctor_args) \
3696 WXDLLIMPEXP_DATA_BASE(klass*) name##Ptr = NULL; \
3697 WXDLLIMPEXP_BASE klass* wxGet_##name##Ptr() \
3699 static impl_klass name##Obj ctor_args; \
3700 return &name##Obj; \
3702 /* this ensures that all global converter objects are created */ \
3703 /* by the time static initialization is done, i.e. before any */ \
3704 /* thread is launched: */ \
3705 static klass* gs_##name##instance = wxGet_##name##Ptr()
3707 #define WX_DEFINE_GLOBAL_CONV(klass, name, ctor_args) \
3708 WX_DEFINE_GLOBAL_CONV2(klass, klass, name, ctor_args)
3711 WX_DEFINE_GLOBAL_CONV2(wxMBConv
, wxMBConv_win32
, wxConvLibc
, wxEMPTY_PARAMETER_VALUE
);
3712 #elif defined(__WXMAC__) && !defined(__MACH__)
3713 WX_DEFINE_GLOBAL_CONV2(wxMBConv
, wxMBConv_mac
, wxConvLibc
, wxEMPTY_PARAMETER_VALUE
);
3715 WX_DEFINE_GLOBAL_CONV2(wxMBConv
, wxMBConvLibc
, wxConvLibc
, wxEMPTY_PARAMETER_VALUE
);
3718 WX_DEFINE_GLOBAL_CONV(wxMBConvUTF8
, wxConvUTF8
, wxEMPTY_PARAMETER_VALUE
);
3719 WX_DEFINE_GLOBAL_CONV(wxMBConvUTF7
, wxConvUTF7
, wxEMPTY_PARAMETER_VALUE
);
3721 WX_DEFINE_GLOBAL_CONV(wxCSConv
, wxConvLocal
, (wxFONTENCODING_SYSTEM
));
3722 WX_DEFINE_GLOBAL_CONV(wxCSConv
, wxConvISO8859_1
, (wxFONTENCODING_ISO8859_1
));
3724 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvCurrent
= wxGet_wxConvLibcPtr();
3725 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvUI
= wxGet_wxConvLocalPtr();
3727 #if defined(__WXMAC__) && defined(TARGET_CARBON)
3728 static wxMBConv_macUTF8D wxConvMacUTF8DObj
;
3730 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvFileName
=
3732 #if defined(__WXMAC__) && defined(TARGET_CARBON)
3735 wxGet_wxConvUTF8Ptr();
3738 wxGet_wxConvLibcPtr();
3739 #endif // __WXOSX__/!__WXOSX__
3741 #else // !wxUSE_WCHAR_T
3743 // FIXME-UTF8: remove this, wxUSE_WCHAR_T is required now
3744 // stand-ins in absence of wchar_t
3745 WXDLLIMPEXP_DATA_BASE(wxMBConv
) wxConvLibc
,
3750 #endif // wxUSE_WCHAR_T/!wxUSE_WCHAR_T