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"
60 #include "wx/mac/corefoundation/private/strconv_cf.h"
61 #endif //def __DARWIN__
64 #define TRACE_STRCONV _T("strconv")
66 // WC_UTF16 is defined only if sizeof(wchar_t) == 2, otherwise it's supposed to
68 #if SIZEOF_WCHAR_T == 2
73 // ============================================================================
75 // ============================================================================
77 // helper function of cMB2WC(): check if n bytes at this location are all NUL
78 static bool NotAllNULs(const char *p
, size_t n
)
80 while ( n
&& *p
++ == '\0' )
86 // ----------------------------------------------------------------------------
87 // UTF-16 en/decoding to/from UCS-4 with surrogates handling
88 // ----------------------------------------------------------------------------
90 static size_t encode_utf16(wxUint32 input
, wxUint16
*output
)
95 *output
= (wxUint16
) input
;
99 else if (input
>= 0x110000)
101 return wxCONV_FAILED
;
107 *output
++ = (wxUint16
) ((input
>> 10) + 0xd7c0);
108 *output
= (wxUint16
) ((input
& 0x3ff) + 0xdc00);
115 static size_t decode_utf16(const wxUint16
* input
, wxUint32
& output
)
117 if ((*input
< 0xd800) || (*input
> 0xdfff))
122 else if ((input
[1] < 0xdc00) || (input
[1] > 0xdfff))
125 return wxCONV_FAILED
;
129 output
= ((input
[0] - 0xd7c0) << 10) + (input
[1] - 0xdc00);
135 typedef wchar_t wxDecodeSurrogate_t
;
137 typedef wxUint16 wxDecodeSurrogate_t
;
138 #endif // WC_UTF16/!WC_UTF16
140 // returns the next UTF-32 character from the wchar_t buffer and advances the
141 // pointer to the character after this one
143 // if an invalid character is found, *pSrc is set to NULL, the caller must
145 static wxUint32
wxDecodeSurrogate(const wxDecodeSurrogate_t
**pSrc
)
149 n
= decode_utf16(wx_reinterpret_cast(const wxUint16
*, *pSrc
), out
);
150 if ( n
== wxCONV_FAILED
)
158 // ----------------------------------------------------------------------------
160 // ----------------------------------------------------------------------------
163 wxMBConv::ToWChar(wchar_t *dst
, size_t dstLen
,
164 const char *src
, size_t srcLen
) const
166 // although new conversion classes are supposed to implement this function
167 // directly, the existins ones only implement the old MB2WC() and so, to
168 // avoid to have to rewrite all conversion classes at once, we provide a
169 // default (but not efficient) implementation of this one in terms of the
170 // old function by copying the input to ensure that it's NUL-terminated and
171 // then using MB2WC() to convert it
173 // the number of chars [which would be] written to dst [if it were not NULL]
174 size_t dstWritten
= 0;
176 // the number of NULs terminating this string
177 size_t nulLen
= 0; // not really needed, but just to avoid warnings
179 // if we were not given the input size we just have to assume that the
180 // string is properly terminated as we have no way of knowing how long it
181 // is anyhow, but if we do have the size check whether there are enough
185 if ( srcLen
!= wxNO_LEN
)
187 // we need to know how to find the end of this string
188 nulLen
= GetMBNulLen();
189 if ( nulLen
== wxCONV_FAILED
)
190 return wxCONV_FAILED
;
192 // if there are enough NULs we can avoid the copy
193 if ( srcLen
< nulLen
|| NotAllNULs(src
+ srcLen
- nulLen
, nulLen
) )
195 // make a copy in order to properly NUL-terminate the string
196 bufTmp
= wxCharBuffer(srcLen
+ nulLen
- 1 /* 1 will be added */);
197 char * const p
= bufTmp
.data();
198 memcpy(p
, src
, srcLen
);
199 for ( char *s
= p
+ srcLen
; s
< p
+ srcLen
+ nulLen
; s
++ )
205 srcEnd
= src
+ srcLen
;
207 else // quit after the first loop iteration
214 // try to convert the current chunk
215 size_t lenChunk
= MB2WC(NULL
, src
, 0);
216 if ( lenChunk
== wxCONV_FAILED
)
217 return wxCONV_FAILED
;
219 lenChunk
++; // for the L'\0' at the end of this chunk
221 dstWritten
+= lenChunk
;
225 // nothing left in the input string, conversion succeeded
231 if ( dstWritten
> dstLen
)
232 return wxCONV_FAILED
;
234 if ( MB2WC(dst
, src
, lenChunk
) == wxCONV_FAILED
)
235 return wxCONV_FAILED
;
242 // we convert just one chunk in this case as this is the entire
247 // advance the input pointer past the end of this chunk
248 while ( NotAllNULs(src
, nulLen
) )
250 // notice that we must skip over multiple bytes here as we suppose
251 // that if NUL takes 2 or 4 bytes, then all the other characters do
252 // too and so if advanced by a single byte we might erroneously
253 // detect sequences of NUL bytes in the middle of the input
257 src
+= nulLen
; // skipping over its terminator as well
259 // note that ">=" (and not just "==") is needed here as the terminator
260 // we skipped just above could be inside or just after the buffer
261 // delimited by inEnd
270 wxMBConv::FromWChar(char *dst
, size_t dstLen
,
271 const wchar_t *src
, size_t srcLen
) const
273 // the number of chars [which would be] written to dst [if it were not NULL]
274 size_t dstWritten
= 0;
276 // make a copy of the input string unless it is already properly
279 // if we don't know its length we have no choice but to assume that it is,
280 // indeed, properly terminated
281 wxWCharBuffer bufTmp
;
282 if ( srcLen
== wxNO_LEN
)
284 srcLen
= wxWcslen(src
) + 1;
286 else if ( srcLen
!= 0 && src
[srcLen
- 1] != L
'\0' )
288 // make a copy in order to properly NUL-terminate the string
289 bufTmp
= wxWCharBuffer(srcLen
);
290 memcpy(bufTmp
.data(), src
, srcLen
* sizeof(wchar_t));
294 const size_t lenNul
= GetMBNulLen();
295 for ( const wchar_t * const srcEnd
= src
+ srcLen
;
297 src
+= wxWcslen(src
) + 1 /* skip L'\0' too */ )
299 // try to convert the current chunk
300 size_t lenChunk
= WC2MB(NULL
, src
, 0);
302 if ( lenChunk
== wxCONV_FAILED
)
303 return wxCONV_FAILED
;
306 dstWritten
+= lenChunk
;
310 if ( dstWritten
> dstLen
)
311 return wxCONV_FAILED
;
313 if ( WC2MB(dst
, src
, lenChunk
) == wxCONV_FAILED
)
314 return wxCONV_FAILED
;
323 size_t wxMBConv::MB2WC(wchar_t *outBuff
, const char *inBuff
, size_t outLen
) const
325 size_t rc
= ToWChar(outBuff
, outLen
, inBuff
);
326 if ( rc
!= wxCONV_FAILED
)
328 // ToWChar() returns the buffer length, i.e. including the trailing
329 // NUL, while this method doesn't take it into account
336 size_t wxMBConv::WC2MB(char *outBuff
, const wchar_t *inBuff
, size_t outLen
) const
338 size_t rc
= FromWChar(outBuff
, outLen
, inBuff
);
339 if ( rc
!= wxCONV_FAILED
)
347 wxMBConv::~wxMBConv()
349 // nothing to do here (necessary for Darwin linking probably)
352 const wxWCharBuffer
wxMBConv::cMB2WC(const char *psz
) const
356 // calculate the length of the buffer needed first
357 const size_t nLen
= ToWChar(NULL
, 0, psz
);
358 if ( nLen
!= wxCONV_FAILED
)
360 // now do the actual conversion
361 wxWCharBuffer
buf(nLen
- 1 /* +1 added implicitly */);
363 // +1 for the trailing NULL
364 if ( ToWChar(buf
.data(), nLen
, psz
) != wxCONV_FAILED
)
369 return wxWCharBuffer();
372 const wxCharBuffer
wxMBConv::cWC2MB(const wchar_t *pwz
) const
376 const size_t nLen
= FromWChar(NULL
, 0, pwz
);
377 if ( nLen
!= wxCONV_FAILED
)
379 wxCharBuffer
buf(nLen
- 1);
380 if ( FromWChar(buf
.data(), nLen
, pwz
) != wxCONV_FAILED
)
385 return wxCharBuffer();
389 wxMBConv::cMB2WC(const char *inBuff
, size_t inLen
, size_t *outLen
) const
391 const size_t dstLen
= ToWChar(NULL
, 0, inBuff
, inLen
);
392 if ( dstLen
!= wxCONV_FAILED
)
394 // notice that we allocate space for dstLen+1 wide characters here
395 // because we want the buffer to always be NUL-terminated, even if the
396 // input isn't (as otherwise the caller has no way to know its length)
397 wxWCharBuffer
wbuf(dstLen
);
398 wbuf
.data()[dstLen
- 1] = L
'\0';
399 if ( ToWChar(wbuf
.data(), dstLen
, inBuff
, inLen
) != wxCONV_FAILED
)
404 if ( wbuf
[dstLen
- 1] == L
'\0' )
415 return wxWCharBuffer();
419 wxMBConv::cWC2MB(const wchar_t *inBuff
, size_t inLen
, size_t *outLen
) const
421 size_t dstLen
= FromWChar(NULL
, 0, inBuff
, inLen
);
422 if ( dstLen
!= wxCONV_FAILED
)
424 const size_t nulLen
= GetMBNulLen();
426 // as above, ensure that the buffer is always NUL-terminated, even if
428 wxCharBuffer
buf(dstLen
+ nulLen
- 1);
429 memset(buf
.data() + dstLen
, 0, nulLen
);
430 if ( FromWChar(buf
.data(), dstLen
, inBuff
, inLen
) != wxCONV_FAILED
)
436 if ( dstLen
>= nulLen
&&
437 !NotAllNULs(buf
.data() + dstLen
- nulLen
, nulLen
) )
439 // in this case the output is NUL-terminated and we're not
440 // supposed to count NUL
452 return wxCharBuffer();
455 // ----------------------------------------------------------------------------
457 // ----------------------------------------------------------------------------
459 size_t wxMBConvLibc::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
461 return wxMB2WC(buf
, psz
, n
);
464 size_t wxMBConvLibc::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
466 return wxWC2MB(buf
, psz
, n
);
469 // ----------------------------------------------------------------------------
470 // wxConvBrokenFileNames
471 // ----------------------------------------------------------------------------
475 wxConvBrokenFileNames::wxConvBrokenFileNames(const wxString
& charset
)
477 if ( wxStricmp(charset
, _T("UTF-8")) == 0 ||
478 wxStricmp(charset
, _T("UTF8")) == 0 )
479 m_conv
= new wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_PUA
);
481 m_conv
= new wxCSConv(charset
);
486 // ----------------------------------------------------------------------------
488 // ----------------------------------------------------------------------------
490 // Implementation (C) 2004 Fredrik Roubert
493 // BASE64 decoding table
495 static const unsigned char utf7unb64
[] =
497 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
498 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
499 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
500 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
501 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
502 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f,
503 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
504 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
505 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
506 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
507 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
508 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
509 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
510 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
511 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
512 0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
513 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
514 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
515 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
516 0xff, 0xff, 0xff, 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
531 size_t wxMBConvUTF7::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
535 while ( *psz
&& (!buf
|| (len
< n
)) )
537 unsigned char cc
= *psz
++;
545 else if (*psz
== '-')
553 else // start of BASE64 encoded string
557 for ( ok
= lsb
= false, d
= 0, l
= 0;
558 (cc
= utf7unb64
[(unsigned char)*psz
]) != 0xff;
563 for (l
+= 6; l
>= 8; lsb
= !lsb
)
565 unsigned char c
= (unsigned char)((d
>> (l
-= 8)) % 256);
575 *buf
= (wchar_t)(c
<< 8);
584 // in valid UTF7 we should have valid characters after '+'
585 return wxCONV_FAILED
;
593 if ( buf
&& (len
< n
) )
600 // BASE64 encoding table
602 static const unsigned char utf7enb64
[] =
604 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
605 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
606 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
607 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
608 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
609 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
610 'w', 'x', 'y', 'z', '0', '1', '2', '3',
611 '4', '5', '6', '7', '8', '9', '+', '/'
615 // UTF-7 encoding table
617 // 0 - Set D (directly encoded characters)
618 // 1 - Set O (optional direct characters)
619 // 2 - whitespace characters (optional)
620 // 3 - special characters
622 static const unsigned char utf7encode
[128] =
624 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
625 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
626 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 3,
627 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
628 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
629 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
630 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
631 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3
634 size_t wxMBConvUTF7::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
638 while (*psz
&& ((!buf
) || (len
< n
)))
641 if (cc
< 0x80 && utf7encode
[cc
] < 1)
650 else if (((wxUint32
)cc
) > 0xffff)
652 // no surrogate pair generation (yet?)
653 return wxCONV_FAILED
;
664 // BASE64 encode string
665 unsigned int lsb
, d
, l
;
666 for (d
= 0, l
= 0; /*nothing*/; psz
++)
668 for (lsb
= 0; lsb
< 2; lsb
++)
671 d
+= lsb
? cc
& 0xff : (cc
& 0xff00) >> 8;
673 for (l
+= 8; l
>= 6; )
677 *buf
++ = utf7enb64
[(d
>> l
) % 64];
683 if (!(cc
) || (cc
< 0x80 && utf7encode
[cc
] < 1))
690 *buf
++ = utf7enb64
[((d
% 16) << (6 - l
)) % 64];
702 if (buf
&& (len
< n
))
708 // ----------------------------------------------------------------------------
710 // ----------------------------------------------------------------------------
712 static const wxUint32 utf8_max
[]=
713 { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff, 0xffffffff };
715 // boundaries of the private use area we use to (temporarily) remap invalid
716 // characters invalid in a UTF-8 encoded string
717 const wxUint32 wxUnicodePUA
= 0x100000;
718 const wxUint32 wxUnicodePUAEnd
= wxUnicodePUA
+ 256;
720 // this table gives the length of the UTF-8 encoding from its first character:
721 const unsigned char tableUtf8Lengths
[256] = {
722 // single-byte sequences (ASCII):
723 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 00..0F
724 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 10..1F
725 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 20..2F
726 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 30..3F
727 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 40..4F
728 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 50..5F
729 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 60..6F
730 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 70..7F
732 // these are invalid:
733 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80..8F
734 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 90..9F
735 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A0..AF
736 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B0..BF
739 // two-byte sequences:
740 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C2..CF
741 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // D0..DF
743 // three-byte sequences:
744 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // E0..EF
746 // four-byte sequences:
747 4, 4, 4, 4, 4, // F0..F4
749 // these are invalid again (5- or 6-byte
750 // sequences and sequences for code points
751 // above U+10FFFF, as restricted by RFC 3629):
752 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F5..FF
756 wxMBConvStrictUTF8::ToWChar(wchar_t *dst
, size_t dstLen
,
757 const char *src
, size_t srcLen
) const
759 wchar_t *out
= dstLen
? dst
: NULL
;
762 if ( srcLen
== wxNO_LEN
)
763 srcLen
= strlen(src
) + 1;
765 for ( const char *p
= src
; ; p
++ )
767 if ( !(srcLen
== wxNO_LEN
? *p
: srcLen
) )
769 // all done successfully, just add the trailing NULL if we are not
770 // using explicit length
771 if ( srcLen
== wxNO_LEN
)
787 if ( out
&& !dstLen
-- )
791 unsigned char c
= *p
;
795 if ( srcLen
== 0 ) // the test works for wxNO_LEN too
798 if ( srcLen
!= wxNO_LEN
)
805 unsigned len
= tableUtf8Lengths
[c
];
809 if ( srcLen
< len
) // the test works for wxNO_LEN too
812 if ( srcLen
!= wxNO_LEN
)
815 // Char. number range | UTF-8 octet sequence
816 // (hexadecimal) | (binary)
817 // ----------------------+----------------------------------------
818 // 0000 0000 - 0000 007F | 0xxxxxxx
819 // 0000 0080 - 0000 07FF | 110xxxxx 10xxxxxx
820 // 0000 0800 - 0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
821 // 0001 0000 - 0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
823 // Code point value is stored in bits marked with 'x',
824 // lowest-order bit of the value on the right side in the diagram
825 // above. (from RFC 3629)
827 // mask to extract lead byte's value ('x' bits above), by sequence
829 static const unsigned char leadValueMask
[] = { 0x7F, 0x1F, 0x0F, 0x07 };
831 // mask and value of lead byte's most significant bits, by length:
832 static const unsigned char leadMarkerMask
[] = { 0x80, 0xE0, 0xF0, 0xF8 };
833 static const unsigned char leadMarkerVal
[] = { 0x00, 0xC0, 0xE0, 0xF0 };
835 len
--; // it's more convenient to work with 0-based length here
837 // extract the lead byte's value bits:
838 if ( (c
& leadMarkerMask
[len
]) != leadMarkerVal
[len
] )
841 code
= c
& leadValueMask
[len
];
843 // all remaining bytes, if any, are handled in the same way
844 // regardless of sequence's length:
848 if ( (c
& 0xC0) != 0x80 )
849 return wxCONV_FAILED
;
857 // cast is ok because wchar_t == wxUint16 if WC_UTF16
858 if ( encode_utf16(code
, (wxUint16
*)out
) == 2 )
867 #endif // WC_UTF16/!WC_UTF16
875 return wxCONV_FAILED
;
879 wxMBConvStrictUTF8::FromWChar(char *dst
, size_t dstLen
,
880 const wchar_t *src
, size_t srcLen
) const
882 char *out
= dstLen
? dst
: NULL
;
885 for ( const wchar_t *wp
= src
; ; wp
++ )
887 if ( !(srcLen
== wxNO_LEN
? *wp
: srcLen
--) )
889 // all done successfully, just add the trailing NULL if we are not
890 // using explicit length
891 if ( srcLen
== wxNO_LEN
)
910 // cast is ok for WC_UTF16
911 if ( decode_utf16((const wxUint16
*)wp
, code
) == 2 )
913 // skip the next char too as we decoded a surrogate
916 #else // wchar_t is UTF-32
917 code
= *wp
& 0x7fffffff;
932 else if ( code
<= 0x07FF )
940 // NB: this line takes 6 least significant bits, encodes them as
941 // 10xxxxxx and discards them so that the next byte can be encoded:
942 out
[1] = 0x80 | (code
& 0x3F); code
>>= 6;
943 out
[0] = 0xC0 | code
;
946 else if ( code
< 0xFFFF )
954 out
[2] = 0x80 | (code
& 0x3F); code
>>= 6;
955 out
[1] = 0x80 | (code
& 0x3F); code
>>= 6;
956 out
[0] = 0xE0 | code
;
959 else if ( code
<= 0x10FFFF )
967 out
[3] = 0x80 | (code
& 0x3F); code
>>= 6;
968 out
[2] = 0x80 | (code
& 0x3F); code
>>= 6;
969 out
[1] = 0x80 | (code
& 0x3F); code
>>= 6;
970 out
[0] = 0xF0 | code
;
975 wxFAIL_MSG( _T("trying to encode undefined Unicode character") );
988 // we only get here if an error occurs during decoding
989 return wxCONV_FAILED
;
992 size_t wxMBConvUTF8::ToWChar(wchar_t *buf
, size_t n
,
993 const char *psz
, size_t srcLen
) const
995 if ( m_options
== MAP_INVALID_UTF8_NOT
)
996 return wxMBConvStrictUTF8::ToWChar(buf
, n
, psz
, srcLen
);
1000 while ((srcLen
== wxNO_LEN
? *psz
: srcLen
--) && ((!buf
) || (len
< n
)))
1002 const char *opsz
= psz
;
1003 bool invalid
= false;
1004 unsigned char cc
= *psz
++, fc
= cc
;
1006 for (cnt
= 0; fc
& 0x80; cnt
++)
1016 // escape the escape character for octal escapes
1017 if ((m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
1018 && cc
== '\\' && (!buf
|| len
< n
))
1030 // invalid UTF-8 sequence
1035 unsigned ocnt
= cnt
- 1;
1036 wxUint32 res
= cc
& (0x3f >> cnt
);
1040 if ((cc
& 0xC0) != 0x80)
1042 // invalid UTF-8 sequence
1048 res
= (res
<< 6) | (cc
& 0x3f);
1051 if (invalid
|| res
<= utf8_max
[ocnt
])
1053 // illegal UTF-8 encoding
1056 else if ((m_options
& MAP_INVALID_UTF8_TO_PUA
) &&
1057 res
>= wxUnicodePUA
&& res
< wxUnicodePUAEnd
)
1059 // if one of our PUA characters turns up externally
1060 // it must also be treated as an illegal sequence
1061 // (a bit like you have to escape an escape character)
1067 // cast is ok because wchar_t == wxUint16 if WC_UTF16
1068 size_t pa
= encode_utf16(res
, (wxUint16
*)buf
);
1069 if (pa
== wxCONV_FAILED
)
1081 *buf
++ = (wchar_t)res
;
1083 #endif // WC_UTF16/!WC_UTF16
1089 if (m_options
& MAP_INVALID_UTF8_TO_PUA
)
1091 while (opsz
< psz
&& (!buf
|| len
< n
))
1094 // cast is ok because wchar_t == wxUuint16 if WC_UTF16
1095 size_t pa
= encode_utf16((unsigned char)*opsz
+ wxUnicodePUA
, (wxUint16
*)buf
);
1096 wxASSERT(pa
!= wxCONV_FAILED
);
1103 *buf
++ = (wchar_t)(wxUnicodePUA
+ (unsigned char)*opsz
);
1109 else if (m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
1111 while (opsz
< psz
&& (!buf
|| len
< n
))
1113 if ( buf
&& len
+ 3 < n
)
1115 unsigned char on
= *opsz
;
1117 *buf
++ = (wchar_t)( L
'0' + on
/ 0100 );
1118 *buf
++ = (wchar_t)( L
'0' + (on
% 0100) / 010 );
1119 *buf
++ = (wchar_t)( L
'0' + on
% 010 );
1126 else // MAP_INVALID_UTF8_NOT
1128 return wxCONV_FAILED
;
1134 if (srcLen
== wxNO_LEN
&& buf
&& (len
< n
))
1140 static inline bool isoctal(wchar_t wch
)
1142 return L
'0' <= wch
&& wch
<= L
'7';
1145 size_t wxMBConvUTF8::FromWChar(char *buf
, size_t n
,
1146 const wchar_t *psz
, size_t srcLen
) const
1148 if ( m_options
== MAP_INVALID_UTF8_NOT
)
1149 return wxMBConvStrictUTF8::FromWChar(buf
, n
, psz
, srcLen
);
1153 while ((srcLen
== wxNO_LEN
? *psz
: srcLen
--) && ((!buf
) || (len
< n
)))
1158 // cast is ok for WC_UTF16
1159 size_t pa
= decode_utf16((const wxUint16
*)psz
, cc
);
1160 psz
+= (pa
== wxCONV_FAILED
) ? 1 : pa
;
1162 cc
= (*psz
++) & 0x7fffffff;
1165 if ( (m_options
& MAP_INVALID_UTF8_TO_PUA
)
1166 && cc
>= wxUnicodePUA
&& cc
< wxUnicodePUAEnd
)
1169 *buf
++ = (char)(cc
- wxUnicodePUA
);
1172 else if ( (m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
1173 && cc
== L
'\\' && psz
[0] == L
'\\' )
1180 else if ( (m_options
& MAP_INVALID_UTF8_TO_OCTAL
) &&
1182 isoctal(psz
[0]) && isoctal(psz
[1]) && isoctal(psz
[2]) )
1186 *buf
++ = (char) ((psz
[0] - L
'0') * 0100 +
1187 (psz
[1] - L
'0') * 010 +
1197 for (cnt
= 0; cc
> utf8_max
[cnt
]; cnt
++)
1213 *buf
++ = (char) ((-128 >> cnt
) | ((cc
>> (cnt
* 6)) & (0x3f >> cnt
)));
1215 *buf
++ = (char) (0x80 | ((cc
>> (cnt
* 6)) & 0x3f));
1221 if (srcLen
== wxNO_LEN
&& buf
&& (len
< n
))
1227 // ============================================================================
1229 // ============================================================================
1231 #ifdef WORDS_BIGENDIAN
1232 #define wxMBConvUTF16straight wxMBConvUTF16BE
1233 #define wxMBConvUTF16swap wxMBConvUTF16LE
1235 #define wxMBConvUTF16swap wxMBConvUTF16BE
1236 #define wxMBConvUTF16straight wxMBConvUTF16LE
1240 size_t wxMBConvUTF16Base::GetLength(const char *src
, size_t srcLen
)
1242 if ( srcLen
== wxNO_LEN
)
1244 // count the number of bytes in input, including the trailing NULs
1245 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1246 for ( srcLen
= 1; *inBuff
++; srcLen
++ )
1249 srcLen
*= BYTES_PER_CHAR
;
1251 else // we already have the length
1253 // we can only convert an entire number of UTF-16 characters
1254 if ( srcLen
% BYTES_PER_CHAR
)
1255 return wxCONV_FAILED
;
1261 // case when in-memory representation is UTF-16 too
1264 // ----------------------------------------------------------------------------
1265 // conversions without endianness change
1266 // ----------------------------------------------------------------------------
1269 wxMBConvUTF16straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1270 const char *src
, size_t srcLen
) const
1272 // set up the scene for using memcpy() (which is presumably more efficient
1273 // than copying the bytes one by one)
1274 srcLen
= GetLength(src
, srcLen
);
1275 if ( srcLen
== wxNO_LEN
)
1276 return wxCONV_FAILED
;
1278 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1281 if ( dstLen
< inLen
)
1282 return wxCONV_FAILED
;
1284 memcpy(dst
, src
, srcLen
);
1291 wxMBConvUTF16straight::FromWChar(char *dst
, size_t dstLen
,
1292 const wchar_t *src
, size_t srcLen
) const
1294 if ( srcLen
== wxNO_LEN
)
1295 srcLen
= wxWcslen(src
) + 1;
1297 srcLen
*= BYTES_PER_CHAR
;
1301 if ( dstLen
< srcLen
)
1302 return wxCONV_FAILED
;
1304 memcpy(dst
, src
, srcLen
);
1310 // ----------------------------------------------------------------------------
1311 // endian-reversing conversions
1312 // ----------------------------------------------------------------------------
1315 wxMBConvUTF16swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1316 const char *src
, size_t srcLen
) const
1318 srcLen
= GetLength(src
, srcLen
);
1319 if ( srcLen
== wxNO_LEN
)
1320 return wxCONV_FAILED
;
1322 srcLen
/= BYTES_PER_CHAR
;
1326 if ( dstLen
< srcLen
)
1327 return wxCONV_FAILED
;
1329 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1330 for ( size_t n
= 0; n
< srcLen
; n
++, inBuff
++ )
1332 *dst
++ = wxUINT16_SWAP_ALWAYS(*inBuff
);
1340 wxMBConvUTF16swap::FromWChar(char *dst
, size_t dstLen
,
1341 const wchar_t *src
, size_t srcLen
) const
1343 if ( srcLen
== wxNO_LEN
)
1344 srcLen
= wxWcslen(src
) + 1;
1346 srcLen
*= BYTES_PER_CHAR
;
1350 if ( dstLen
< srcLen
)
1351 return wxCONV_FAILED
;
1353 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1354 for ( size_t n
= 0; n
< srcLen
; n
+= BYTES_PER_CHAR
, src
++ )
1356 *outBuff
++ = wxUINT16_SWAP_ALWAYS(*src
);
1363 #else // !WC_UTF16: wchar_t is UTF-32
1365 // ----------------------------------------------------------------------------
1366 // conversions without endianness change
1367 // ----------------------------------------------------------------------------
1370 wxMBConvUTF16straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1371 const char *src
, size_t srcLen
) const
1373 srcLen
= GetLength(src
, srcLen
);
1374 if ( srcLen
== wxNO_LEN
)
1375 return wxCONV_FAILED
;
1377 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1380 // optimization: return maximal space which could be needed for this
1381 // string even if the real size could be smaller if the buffer contains
1387 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1388 for ( const wxUint16
* const inEnd
= inBuff
+ inLen
; inBuff
< inEnd
; )
1390 const wxUint32 ch
= wxDecodeSurrogate(&inBuff
);
1392 return wxCONV_FAILED
;
1394 if ( ++outLen
> dstLen
)
1395 return wxCONV_FAILED
;
1405 wxMBConvUTF16straight::FromWChar(char *dst
, size_t dstLen
,
1406 const wchar_t *src
, size_t srcLen
) const
1408 if ( srcLen
== wxNO_LEN
)
1409 srcLen
= wxWcslen(src
) + 1;
1412 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1413 for ( size_t n
= 0; n
< srcLen
; n
++ )
1416 const size_t numChars
= encode_utf16(*src
++, cc
);
1417 if ( numChars
== wxCONV_FAILED
)
1418 return wxCONV_FAILED
;
1420 outLen
+= numChars
* BYTES_PER_CHAR
;
1423 if ( outLen
> dstLen
)
1424 return wxCONV_FAILED
;
1427 if ( numChars
== 2 )
1429 // second character of a surrogate
1438 // ----------------------------------------------------------------------------
1439 // endian-reversing conversions
1440 // ----------------------------------------------------------------------------
1443 wxMBConvUTF16swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1444 const char *src
, size_t srcLen
) const
1446 srcLen
= GetLength(src
, srcLen
);
1447 if ( srcLen
== wxNO_LEN
)
1448 return wxCONV_FAILED
;
1450 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1453 // optimization: return maximal space which could be needed for this
1454 // string even if the real size could be smaller if the buffer contains
1460 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1461 for ( const wxUint16
* const inEnd
= inBuff
+ inLen
; inBuff
< inEnd
; )
1466 tmp
[0] = wxUINT16_SWAP_ALWAYS(*inBuff
);
1468 tmp
[1] = wxUINT16_SWAP_ALWAYS(*inBuff
);
1470 const size_t numChars
= decode_utf16(tmp
, ch
);
1471 if ( numChars
== wxCONV_FAILED
)
1472 return wxCONV_FAILED
;
1474 if ( numChars
== 2 )
1477 if ( ++outLen
> dstLen
)
1478 return wxCONV_FAILED
;
1488 wxMBConvUTF16swap::FromWChar(char *dst
, size_t dstLen
,
1489 const wchar_t *src
, size_t srcLen
) const
1491 if ( srcLen
== wxNO_LEN
)
1492 srcLen
= wxWcslen(src
) + 1;
1495 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1496 for ( const wchar_t *srcEnd
= src
+ srcLen
; src
< srcEnd
; src
++ )
1499 const size_t numChars
= encode_utf16(*src
, cc
);
1500 if ( numChars
== wxCONV_FAILED
)
1501 return wxCONV_FAILED
;
1503 outLen
+= numChars
* BYTES_PER_CHAR
;
1506 if ( outLen
> dstLen
)
1507 return wxCONV_FAILED
;
1509 *outBuff
++ = wxUINT16_SWAP_ALWAYS(cc
[0]);
1510 if ( numChars
== 2 )
1512 // second character of a surrogate
1513 *outBuff
++ = wxUINT16_SWAP_ALWAYS(cc
[1]);
1521 #endif // WC_UTF16/!WC_UTF16
1524 // ============================================================================
1526 // ============================================================================
1528 #ifdef WORDS_BIGENDIAN
1529 #define wxMBConvUTF32straight wxMBConvUTF32BE
1530 #define wxMBConvUTF32swap wxMBConvUTF32LE
1532 #define wxMBConvUTF32swap wxMBConvUTF32BE
1533 #define wxMBConvUTF32straight wxMBConvUTF32LE
1537 WXDLLIMPEXP_DATA_BASE(wxMBConvUTF32LE
) wxConvUTF32LE
;
1538 WXDLLIMPEXP_DATA_BASE(wxMBConvUTF32BE
) wxConvUTF32BE
;
1541 size_t wxMBConvUTF32Base::GetLength(const char *src
, size_t srcLen
)
1543 if ( srcLen
== wxNO_LEN
)
1545 // count the number of bytes in input, including the trailing NULs
1546 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1547 for ( srcLen
= 1; *inBuff
++; srcLen
++ )
1550 srcLen
*= BYTES_PER_CHAR
;
1552 else // we already have the length
1554 // we can only convert an entire number of UTF-32 characters
1555 if ( srcLen
% BYTES_PER_CHAR
)
1556 return wxCONV_FAILED
;
1562 // case when in-memory representation is UTF-16
1565 // ----------------------------------------------------------------------------
1566 // conversions without endianness change
1567 // ----------------------------------------------------------------------------
1570 wxMBConvUTF32straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1571 const char *src
, size_t srcLen
) const
1573 srcLen
= GetLength(src
, srcLen
);
1574 if ( srcLen
== wxNO_LEN
)
1575 return wxCONV_FAILED
;
1577 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1578 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1580 for ( size_t n
= 0; n
< inLen
; n
++ )
1583 const size_t numChars
= encode_utf16(*inBuff
++, cc
);
1584 if ( numChars
== wxCONV_FAILED
)
1585 return wxCONV_FAILED
;
1590 if ( outLen
> dstLen
)
1591 return wxCONV_FAILED
;
1594 if ( numChars
== 2 )
1596 // second character of a surrogate
1606 wxMBConvUTF32straight::FromWChar(char *dst
, size_t dstLen
,
1607 const wchar_t *src
, size_t srcLen
) const
1609 if ( srcLen
== wxNO_LEN
)
1610 srcLen
= wxWcslen(src
) + 1;
1614 // optimization: return maximal space which could be needed for this
1615 // string instead of the exact amount which could be less if there are
1616 // any surrogates in the input
1618 // we consider that surrogates are rare enough to make it worthwhile to
1619 // avoid running the loop below at the cost of slightly extra memory
1621 return srcLen
* BYTES_PER_CHAR
;
1624 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1626 for ( const wchar_t * const srcEnd
= src
+ srcLen
; src
< srcEnd
; )
1628 const wxUint32 ch
= wxDecodeSurrogate(&src
);
1630 return wxCONV_FAILED
;
1632 outLen
+= BYTES_PER_CHAR
;
1634 if ( outLen
> dstLen
)
1635 return wxCONV_FAILED
;
1643 // ----------------------------------------------------------------------------
1644 // endian-reversing conversions
1645 // ----------------------------------------------------------------------------
1648 wxMBConvUTF32swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1649 const char *src
, size_t srcLen
) const
1651 srcLen
= GetLength(src
, srcLen
);
1652 if ( srcLen
== wxNO_LEN
)
1653 return wxCONV_FAILED
;
1655 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1656 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1658 for ( size_t n
= 0; n
< inLen
; n
++, inBuff
++ )
1661 const size_t numChars
= encode_utf16(wxUINT32_SWAP_ALWAYS(*inBuff
), cc
);
1662 if ( numChars
== wxCONV_FAILED
)
1663 return wxCONV_FAILED
;
1668 if ( outLen
> dstLen
)
1669 return wxCONV_FAILED
;
1672 if ( numChars
== 2 )
1674 // second character of a surrogate
1684 wxMBConvUTF32swap::FromWChar(char *dst
, size_t dstLen
,
1685 const wchar_t *src
, size_t srcLen
) const
1687 if ( srcLen
== wxNO_LEN
)
1688 srcLen
= wxWcslen(src
) + 1;
1692 // optimization: return maximal space which could be needed for this
1693 // string instead of the exact amount which could be less if there are
1694 // any surrogates in the input
1696 // we consider that surrogates are rare enough to make it worthwhile to
1697 // avoid running the loop below at the cost of slightly extra memory
1699 return srcLen
*BYTES_PER_CHAR
;
1702 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1704 for ( const wchar_t * const srcEnd
= src
+ srcLen
; src
< srcEnd
; )
1706 const wxUint32 ch
= wxDecodeSurrogate(&src
);
1708 return wxCONV_FAILED
;
1710 outLen
+= BYTES_PER_CHAR
;
1712 if ( outLen
> dstLen
)
1713 return wxCONV_FAILED
;
1715 *outBuff
++ = wxUINT32_SWAP_ALWAYS(ch
);
1721 #else // !WC_UTF16: wchar_t is UTF-32
1723 // ----------------------------------------------------------------------------
1724 // conversions without endianness change
1725 // ----------------------------------------------------------------------------
1728 wxMBConvUTF32straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1729 const char *src
, size_t srcLen
) const
1731 // use memcpy() as it should be much faster than hand-written loop
1732 srcLen
= GetLength(src
, srcLen
);
1733 if ( srcLen
== wxNO_LEN
)
1734 return wxCONV_FAILED
;
1736 const size_t inLen
= srcLen
/BYTES_PER_CHAR
;
1739 if ( dstLen
< inLen
)
1740 return wxCONV_FAILED
;
1742 memcpy(dst
, src
, srcLen
);
1749 wxMBConvUTF32straight::FromWChar(char *dst
, size_t dstLen
,
1750 const wchar_t *src
, size_t srcLen
) const
1752 if ( srcLen
== wxNO_LEN
)
1753 srcLen
= wxWcslen(src
) + 1;
1755 srcLen
*= BYTES_PER_CHAR
;
1759 if ( dstLen
< srcLen
)
1760 return wxCONV_FAILED
;
1762 memcpy(dst
, src
, srcLen
);
1768 // ----------------------------------------------------------------------------
1769 // endian-reversing conversions
1770 // ----------------------------------------------------------------------------
1773 wxMBConvUTF32swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1774 const char *src
, size_t srcLen
) const
1776 srcLen
= GetLength(src
, srcLen
);
1777 if ( srcLen
== wxNO_LEN
)
1778 return wxCONV_FAILED
;
1780 srcLen
/= BYTES_PER_CHAR
;
1784 if ( dstLen
< srcLen
)
1785 return wxCONV_FAILED
;
1787 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1788 for ( size_t n
= 0; n
< srcLen
; n
++, inBuff
++ )
1790 *dst
++ = wxUINT32_SWAP_ALWAYS(*inBuff
);
1798 wxMBConvUTF32swap::FromWChar(char *dst
, size_t dstLen
,
1799 const wchar_t *src
, size_t srcLen
) const
1801 if ( srcLen
== wxNO_LEN
)
1802 srcLen
= wxWcslen(src
) + 1;
1804 srcLen
*= BYTES_PER_CHAR
;
1808 if ( dstLen
< srcLen
)
1809 return wxCONV_FAILED
;
1811 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1812 for ( size_t n
= 0; n
< srcLen
; n
+= BYTES_PER_CHAR
, src
++ )
1814 *outBuff
++ = wxUINT32_SWAP_ALWAYS(*src
);
1821 #endif // WC_UTF16/!WC_UTF16
1824 // ============================================================================
1825 // The classes doing conversion using the iconv_xxx() functions
1826 // ============================================================================
1830 // VS: glibc 2.1.3 is broken in that iconv() conversion to/from UCS4 fails with
1831 // E2BIG if output buffer is _exactly_ as big as needed. Such case is
1832 // (unless there's yet another bug in glibc) the only case when iconv()
1833 // returns with (size_t)-1 (which means error) and says there are 0 bytes
1834 // left in the input buffer -- when _real_ error occurs,
1835 // bytes-left-in-input buffer is non-zero. Hence, this alternative test for
1837 // [This bug does not appear in glibc 2.2.]
1838 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ <= 1
1839 #define ICONV_FAILED(cres, bufLeft) ((cres == (size_t)-1) && \
1840 (errno != E2BIG || bufLeft != 0))
1842 #define ICONV_FAILED(cres, bufLeft) (cres == (size_t)-1)
1845 #define ICONV_CHAR_CAST(x) ((ICONV_CONST char **)(x))
1847 #define ICONV_T_INVALID ((iconv_t)-1)
1849 #if SIZEOF_WCHAR_T == 4
1850 #define WC_BSWAP wxUINT32_SWAP_ALWAYS
1851 #define WC_ENC wxFONTENCODING_UTF32
1852 #elif SIZEOF_WCHAR_T == 2
1853 #define WC_BSWAP wxUINT16_SWAP_ALWAYS
1854 #define WC_ENC wxFONTENCODING_UTF16
1855 #else // sizeof(wchar_t) != 2 nor 4
1856 // does this ever happen?
1857 #error "Unknown sizeof(wchar_t): please report this to wx-dev@lists.wxwindows.org"
1860 // ----------------------------------------------------------------------------
1861 // wxMBConv_iconv: encapsulates an iconv character set
1862 // ----------------------------------------------------------------------------
1864 class wxMBConv_iconv
: public wxMBConv
1867 wxMBConv_iconv(const char *name
);
1868 virtual ~wxMBConv_iconv();
1870 virtual size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const;
1871 virtual size_t WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const;
1873 // classify this encoding as explained in wxMBConv::GetMBNulLen() comment
1874 virtual size_t GetMBNulLen() const;
1876 #if wxUSE_UNICODE_UTF8
1877 virtual bool IsUTF8() const;
1880 virtual wxMBConv
*Clone() const
1882 wxMBConv_iconv
*p
= new wxMBConv_iconv(m_name
.ToAscii());
1883 p
->m_minMBCharWidth
= m_minMBCharWidth
;
1888 { return (m2w
!= ICONV_T_INVALID
) && (w2m
!= ICONV_T_INVALID
); }
1891 // the iconv handlers used to translate from multibyte
1892 // to wide char and in the other direction
1897 // guards access to m2w and w2m objects
1898 wxMutex m_iconvMutex
;
1902 // the name (for iconv_open()) of a wide char charset -- if none is
1903 // available on this machine, it will remain NULL
1904 static wxString ms_wcCharsetName
;
1906 // true if the wide char encoding we use (i.e. ms_wcCharsetName) has
1907 // different endian-ness than the native one
1908 static bool ms_wcNeedsSwap
;
1911 // name of the encoding handled by this conversion
1914 // cached result of GetMBNulLen(); set to 0 meaning "unknown"
1916 size_t m_minMBCharWidth
;
1919 // make the constructor available for unit testing
1920 WXDLLIMPEXP_BASE wxMBConv
* new_wxMBConv_iconv( const char* name
)
1922 wxMBConv_iconv
* result
= new wxMBConv_iconv( name
);
1923 if ( !result
->IsOk() )
1932 wxString
wxMBConv_iconv::ms_wcCharsetName
;
1933 bool wxMBConv_iconv::ms_wcNeedsSwap
= false;
1935 wxMBConv_iconv::wxMBConv_iconv(const char *name
)
1938 m_minMBCharWidth
= 0;
1940 // check for charset that represents wchar_t:
1941 if ( ms_wcCharsetName
.empty() )
1943 wxLogTrace(TRACE_STRCONV
, _T("Looking for wide char codeset:"));
1946 const wxChar
**names
= wxFontMapperBase::GetAllEncodingNames(WC_ENC
);
1947 #else // !wxUSE_FONTMAP
1948 static const wxChar
*names_static
[] =
1950 #if SIZEOF_WCHAR_T == 4
1952 #elif SIZEOF_WCHAR_T = 2
1957 const wxChar
**names
= names_static
;
1958 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1960 for ( ; *names
&& ms_wcCharsetName
.empty(); ++names
)
1962 const wxString
nameCS(*names
);
1964 // first try charset with explicit bytesex info (e.g. "UCS-4LE"):
1965 wxString
nameXE(nameCS
);
1967 #ifdef WORDS_BIGENDIAN
1969 #else // little endian
1973 wxLogTrace(TRACE_STRCONV
, _T(" trying charset \"%s\""),
1976 m2w
= iconv_open(nameXE
.ToAscii(), name
);
1977 if ( m2w
== ICONV_T_INVALID
)
1979 // try charset w/o bytesex info (e.g. "UCS4")
1980 wxLogTrace(TRACE_STRCONV
, _T(" trying charset \"%s\""),
1982 m2w
= iconv_open(nameCS
.ToAscii(), name
);
1984 // and check for bytesex ourselves:
1985 if ( m2w
!= ICONV_T_INVALID
)
1987 char buf
[2], *bufPtr
;
1988 wchar_t wbuf
[2], *wbufPtr
;
1996 outsz
= SIZEOF_WCHAR_T
* 2;
2001 m2w
, ICONV_CHAR_CAST(&bufPtr
), &insz
,
2002 (char**)&wbufPtr
, &outsz
);
2004 if (ICONV_FAILED(res
, insz
))
2006 wxLogLastError(wxT("iconv"));
2007 wxLogError(_("Conversion to charset '%s' doesn't work."),
2010 else // ok, can convert to this encoding, remember it
2012 ms_wcCharsetName
= nameCS
;
2013 ms_wcNeedsSwap
= wbuf
[0] != (wchar_t)buf
[0];
2017 else // use charset not requiring byte swapping
2019 ms_wcCharsetName
= nameXE
;
2023 wxLogTrace(TRACE_STRCONV
,
2024 wxT("iconv wchar_t charset is \"%s\"%s"),
2025 ms_wcCharsetName
.empty() ? wxString("<none>")
2027 ms_wcNeedsSwap
? _T(" (needs swap)")
2030 else // we already have ms_wcCharsetName
2032 m2w
= iconv_open(ms_wcCharsetName
.ToAscii(), name
);
2035 if ( ms_wcCharsetName
.empty() )
2037 w2m
= ICONV_T_INVALID
;
2041 w2m
= iconv_open(name
, ms_wcCharsetName
.ToAscii());
2042 if ( w2m
== ICONV_T_INVALID
)
2044 wxLogTrace(TRACE_STRCONV
,
2045 wxT("\"%s\" -> \"%s\" works but not the converse!?"),
2046 ms_wcCharsetName
.c_str(), name
);
2051 wxMBConv_iconv::~wxMBConv_iconv()
2053 if ( m2w
!= ICONV_T_INVALID
)
2055 if ( w2m
!= ICONV_T_INVALID
)
2059 size_t wxMBConv_iconv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2061 // find the string length: notice that must be done differently for
2062 // NUL-terminated strings and UTF-16/32 which are terminated with 2/4 NULs
2064 const size_t nulLen
= GetMBNulLen();
2068 return wxCONV_FAILED
;
2071 inbuf
= strlen(psz
); // arguably more optimized than our version
2076 // for UTF-16/32 not only we need to have 2/4 consecutive NULs but
2077 // they also have to start at character boundary and not span two
2078 // adjacent characters
2080 for ( p
= psz
; NotAllNULs(p
, nulLen
); p
+= nulLen
)
2087 // NB: iconv() is MT-safe, but each thread must use its own iconv_t handle.
2088 // Unfortunately there are a couple of global wxCSConv objects such as
2089 // wxConvLocal that are used all over wx code, so we have to make sure
2090 // the handle is used by at most one thread at the time. Otherwise
2091 // only a few wx classes would be safe to use from non-main threads
2092 // as MB<->WC conversion would fail "randomly".
2093 wxMutexLocker
lock(wxConstCast(this, wxMBConv_iconv
)->m_iconvMutex
);
2094 #endif // wxUSE_THREADS
2096 size_t outbuf
= n
* SIZEOF_WCHAR_T
;
2098 // VS: Use these instead of psz, buf because iconv() modifies its arguments:
2099 wchar_t *bufPtr
= buf
;
2100 const char *pszPtr
= psz
;
2104 // have destination buffer, convert there
2106 ICONV_CHAR_CAST(&pszPtr
), &inbuf
,
2107 (char**)&bufPtr
, &outbuf
);
2108 res
= n
- (outbuf
/ SIZEOF_WCHAR_T
);
2112 // convert to native endianness
2113 for ( unsigned i
= 0; i
< res
; i
++ )
2114 buf
[n
] = WC_BSWAP(buf
[i
]);
2117 // NUL-terminate the string if there is any space left
2123 // no destination buffer... convert using temp buffer
2124 // to calculate destination buffer requirement
2131 outbuf
= 8 * SIZEOF_WCHAR_T
;
2134 ICONV_CHAR_CAST(&pszPtr
), &inbuf
,
2135 (char**)&bufPtr
, &outbuf
);
2137 res
+= 8 - (outbuf
/ SIZEOF_WCHAR_T
);
2139 while ((cres
== (size_t)-1) && (errno
== E2BIG
));
2142 if (ICONV_FAILED(cres
, inbuf
))
2144 //VS: it is ok if iconv fails, hence trace only
2145 wxLogTrace(TRACE_STRCONV
, wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
2146 return wxCONV_FAILED
;
2152 size_t wxMBConv_iconv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2155 // NB: explained in MB2WC
2156 wxMutexLocker
lock(wxConstCast(this, wxMBConv_iconv
)->m_iconvMutex
);
2159 size_t inlen
= wxWcslen(psz
);
2160 size_t inbuf
= inlen
* SIZEOF_WCHAR_T
;
2164 wchar_t *tmpbuf
= 0;
2168 // need to copy to temp buffer to switch endianness
2169 // (doing WC_BSWAP twice on the original buffer won't help, as it
2170 // could be in read-only memory, or be accessed in some other thread)
2171 tmpbuf
= (wchar_t *)malloc(inbuf
+ SIZEOF_WCHAR_T
);
2172 for ( size_t i
= 0; i
< inlen
; i
++ )
2173 tmpbuf
[n
] = WC_BSWAP(psz
[i
]);
2175 tmpbuf
[inlen
] = L
'\0';
2181 // have destination buffer, convert there
2182 cres
= iconv( w2m
, ICONV_CHAR_CAST(&psz
), &inbuf
, &buf
, &outbuf
);
2186 // NB: iconv was given only wcslen(psz) characters on input, and so
2187 // it couldn't convert the trailing zero. Let's do it ourselves
2188 // if there's some room left for it in the output buffer.
2194 // no destination buffer: convert using temp buffer
2195 // to calculate destination buffer requirement
2203 cres
= iconv( w2m
, ICONV_CHAR_CAST(&psz
), &inbuf
, &buf
, &outbuf
);
2207 while ((cres
== (size_t)-1) && (errno
== E2BIG
));
2215 if (ICONV_FAILED(cres
, inbuf
))
2217 wxLogTrace(TRACE_STRCONV
, wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
2218 return wxCONV_FAILED
;
2224 size_t wxMBConv_iconv::GetMBNulLen() const
2226 if ( m_minMBCharWidth
== 0 )
2228 wxMBConv_iconv
* const self
= wxConstCast(this, wxMBConv_iconv
);
2231 // NB: explained in MB2WC
2232 wxMutexLocker
lock(self
->m_iconvMutex
);
2235 const wchar_t *wnul
= L
"";
2236 char buf
[8]; // should be enough for NUL in any encoding
2237 size_t inLen
= sizeof(wchar_t),
2238 outLen
= WXSIZEOF(buf
);
2239 char *inBuff
= (char *)wnul
;
2240 char *outBuff
= buf
;
2241 if ( iconv(w2m
, ICONV_CHAR_CAST(&inBuff
), &inLen
, &outBuff
, &outLen
) == (size_t)-1 )
2243 self
->m_minMBCharWidth
= (size_t)-1;
2247 self
->m_minMBCharWidth
= outBuff
- buf
;
2251 return m_minMBCharWidth
;
2254 #if wxUSE_UNICODE_UTF8
2255 bool wxMBConv_iconv::IsUTF8() const
2257 return wxStricmp(m_name
, "UTF-8") == 0 ||
2258 wxStricmp(m_name
, "UTF8") == 0;
2262 #endif // HAVE_ICONV
2265 // ============================================================================
2266 // Win32 conversion classes
2267 // ============================================================================
2269 #ifdef wxHAVE_WIN32_MB2WC
2273 extern WXDLLIMPEXP_BASE
long wxCharsetToCodepage(const char *charset
);
2274 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
);
2277 class wxMBConv_win32
: public wxMBConv
2282 m_CodePage
= CP_ACP
;
2283 m_minMBCharWidth
= 0;
2286 wxMBConv_win32(const wxMBConv_win32
& conv
)
2289 m_CodePage
= conv
.m_CodePage
;
2290 m_minMBCharWidth
= conv
.m_minMBCharWidth
;
2294 wxMBConv_win32(const char* name
)
2296 m_CodePage
= wxCharsetToCodepage(name
);
2297 m_minMBCharWidth
= 0;
2300 wxMBConv_win32(wxFontEncoding encoding
)
2302 m_CodePage
= wxEncodingToCodepage(encoding
);
2303 m_minMBCharWidth
= 0;
2305 #endif // wxUSE_FONTMAP
2307 virtual size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2309 // note that we have to use MB_ERR_INVALID_CHARS flag as it without it
2310 // the behaviour is not compatible with the Unix version (using iconv)
2311 // and break the library itself, e.g. wxTextInputStream::NextChar()
2312 // wouldn't work if reading an incomplete MB char didn't result in an
2315 // Moreover, MB_ERR_INVALID_CHARS is only supported on Win 2K SP4 or
2316 // Win XP or newer and it is not supported for UTF-[78] so we always
2317 // use our own conversions in this case. See
2318 // http://blogs.msdn.com/michkap/archive/2005/04/19/409566.aspx
2319 // http://msdn.microsoft.com/library/en-us/intl/unicode_17si.asp
2320 if ( m_CodePage
== CP_UTF8
)
2322 return wxMBConvUTF8().MB2WC(buf
, psz
, n
);
2325 if ( m_CodePage
== CP_UTF7
)
2327 return wxMBConvUTF7().MB2WC(buf
, psz
, n
);
2331 if ( (m_CodePage
< 50000 && m_CodePage
!= CP_SYMBOL
) &&
2332 IsAtLeastWin2kSP4() )
2334 flags
= MB_ERR_INVALID_CHARS
;
2337 const size_t len
= ::MultiByteToWideChar
2339 m_CodePage
, // code page
2340 flags
, // flags: fall on error
2341 psz
, // input string
2342 -1, // its length (NUL-terminated)
2343 buf
, // output string
2344 buf
? n
: 0 // size of output buffer
2348 // function totally failed
2349 return wxCONV_FAILED
;
2352 // if we were really converting and didn't use MB_ERR_INVALID_CHARS,
2353 // check if we succeeded, by doing a double trip:
2354 if ( !flags
&& buf
)
2356 const size_t mbLen
= strlen(psz
);
2357 wxCharBuffer
mbBuf(mbLen
);
2358 if ( ::WideCharToMultiByte
2365 mbLen
+ 1, // size in bytes, not length
2369 strcmp(mbBuf
, psz
) != 0 )
2371 // we didn't obtain the same thing we started from, hence
2372 // the conversion was lossy and we consider that it failed
2373 return wxCONV_FAILED
;
2377 // note that it returns count of written chars for buf != NULL and size
2378 // of the needed buffer for buf == NULL so in either case the length of
2379 // the string (which never includes the terminating NUL) is one less
2383 virtual size_t WC2MB(char *buf
, const wchar_t *pwz
, size_t n
) const
2386 we have a problem here: by default, WideCharToMultiByte() may
2387 replace characters unrepresentable in the target code page with bad
2388 quality approximations such as turning "1/2" symbol (U+00BD) into
2389 "1" for the code pages which don't have it and we, obviously, want
2390 to avoid this at any price
2392 the trouble is that this function does it _silently_, i.e. it won't
2393 even tell us whether it did or not... Win98/2000 and higher provide
2394 WC_NO_BEST_FIT_CHARS but it doesn't work for the older systems and
2395 we have to resort to a round trip, i.e. check that converting back
2396 results in the same string -- this is, of course, expensive but
2397 otherwise we simply can't be sure to not garble the data.
2400 // determine if we can rely on WC_NO_BEST_FIT_CHARS: according to MSDN
2401 // it doesn't work with CJK encodings (which we test for rather roughly
2402 // here...) nor with UTF-7/8 nor, of course, with Windows versions not
2404 BOOL usedDef
wxDUMMY_INITIALIZE(false);
2407 if ( CanUseNoBestFit() && m_CodePage
< 50000 )
2409 // it's our lucky day
2410 flags
= WC_NO_BEST_FIT_CHARS
;
2411 pUsedDef
= &usedDef
;
2413 else // old system or unsupported encoding
2419 const size_t len
= ::WideCharToMultiByte
2421 m_CodePage
, // code page
2422 flags
, // either none or no best fit
2423 pwz
, // input string
2424 -1, // it is (wide) NUL-terminated
2425 buf
, // output buffer
2426 buf
? n
: 0, // and its size
2427 NULL
, // default "replacement" char
2428 pUsedDef
// [out] was it used?
2433 // function totally failed
2434 return wxCONV_FAILED
;
2437 // we did something, check if we really succeeded
2440 // check if the conversion failed, i.e. if any replacements
2443 return wxCONV_FAILED
;
2445 else // we must resort to double tripping...
2447 // first we need to ensure that we really have the MB data: this is
2448 // not the case if we're called with NULL buffer, in which case we
2449 // need to do the conversion yet again
2450 wxCharBuffer bufDef
;
2453 bufDef
= wxCharBuffer(len
);
2454 buf
= bufDef
.data();
2455 if ( !::WideCharToMultiByte(m_CodePage
, flags
, pwz
, -1,
2456 buf
, len
, NULL
, NULL
) )
2457 return wxCONV_FAILED
;
2462 wxWCharBuffer
wcBuf(n
);
2463 if ( MB2WC(wcBuf
.data(), buf
, n
+ 1) == wxCONV_FAILED
||
2464 wcscmp(wcBuf
, pwz
) != 0 )
2466 // we didn't obtain the same thing we started from, hence
2467 // the conversion was lossy and we consider that it failed
2468 return wxCONV_FAILED
;
2472 // see the comment above for the reason of "len - 1"
2476 virtual size_t GetMBNulLen() const
2478 if ( m_minMBCharWidth
== 0 )
2480 int len
= ::WideCharToMultiByte
2482 m_CodePage
, // code page
2484 L
"", // input string
2485 1, // translate just the NUL
2486 NULL
, // output buffer
2488 NULL
, // no replacement char
2489 NULL
// [out] don't care if it was used
2492 wxMBConv_win32
* const self
= wxConstCast(this, wxMBConv_win32
);
2496 wxLogDebug(_T("Unexpected NUL length %d"), len
);
2497 self
->m_minMBCharWidth
= (size_t)-1;
2501 self
->m_minMBCharWidth
= (size_t)-1;
2507 self
->m_minMBCharWidth
= len
;
2512 return m_minMBCharWidth
;
2515 virtual wxMBConv
*Clone() const { return new wxMBConv_win32(*this); }
2517 bool IsOk() const { return m_CodePage
!= -1; }
2520 static bool CanUseNoBestFit()
2522 static int s_isWin98Or2k
= -1;
2524 if ( s_isWin98Or2k
== -1 )
2527 switch ( wxGetOsVersion(&verMaj
, &verMin
) )
2529 case wxOS_WINDOWS_9X
:
2530 s_isWin98Or2k
= verMaj
>= 4 && verMin
>= 10;
2533 case wxOS_WINDOWS_NT
:
2534 s_isWin98Or2k
= verMaj
>= 5;
2538 // unknown: be conservative by default
2543 wxASSERT_MSG( s_isWin98Or2k
!= -1, _T("should be set above") );
2546 return s_isWin98Or2k
== 1;
2549 static bool IsAtLeastWin2kSP4()
2554 static int s_isAtLeastWin2kSP4
= -1;
2556 if ( s_isAtLeastWin2kSP4
== -1 )
2558 OSVERSIONINFOEX ver
;
2560 memset(&ver
, 0, sizeof(ver
));
2561 ver
.dwOSVersionInfoSize
= sizeof(ver
);
2562 GetVersionEx((OSVERSIONINFO
*)&ver
);
2564 s_isAtLeastWin2kSP4
=
2565 ((ver
.dwMajorVersion
> 5) || // Vista+
2566 (ver
.dwMajorVersion
== 5 && ver
.dwMinorVersion
> 0) || // XP/2003
2567 (ver
.dwMajorVersion
== 5 && ver
.dwMinorVersion
== 0 &&
2568 ver
.wServicePackMajor
>= 4)) // 2000 SP4+
2572 return s_isAtLeastWin2kSP4
== 1;
2577 // the code page we're working with
2580 // cached result of GetMBNulLen(), set to 0 initially meaning
2582 size_t m_minMBCharWidth
;
2585 #endif // wxHAVE_WIN32_MB2WC
2588 // ============================================================================
2589 // wxEncodingConverter based conversion classes
2590 // ============================================================================
2594 class wxMBConv_wxwin
: public wxMBConv
2599 // Refuse to use broken wxEncodingConverter code for Mac-specific encodings.
2600 // The wxMBConv_cf class does a better job.
2601 m_ok
= (m_enc
< wxFONTENCODING_MACMIN
|| m_enc
> wxFONTENCODING_MACMAX
) &&
2602 m2w
.Init(m_enc
, wxFONTENCODING_UNICODE
) &&
2603 w2m
.Init(wxFONTENCODING_UNICODE
, m_enc
);
2607 // temporarily just use wxEncodingConverter stuff,
2608 // so that it works while a better implementation is built
2609 wxMBConv_wxwin(const char* name
)
2612 m_enc
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
2614 m_enc
= wxFONTENCODING_SYSTEM
;
2619 wxMBConv_wxwin(wxFontEncoding enc
)
2626 size_t MB2WC(wchar_t *buf
, const char *psz
, size_t WXUNUSED(n
)) const
2628 size_t inbuf
= strlen(psz
);
2631 if (!m2w
.Convert(psz
, buf
))
2632 return wxCONV_FAILED
;
2637 size_t WC2MB(char *buf
, const wchar_t *psz
, size_t WXUNUSED(n
)) const
2639 const size_t inbuf
= wxWcslen(psz
);
2642 if (!w2m
.Convert(psz
, buf
))
2643 return wxCONV_FAILED
;
2649 virtual size_t GetMBNulLen() const
2653 case wxFONTENCODING_UTF16BE
:
2654 case wxFONTENCODING_UTF16LE
:
2657 case wxFONTENCODING_UTF32BE
:
2658 case wxFONTENCODING_UTF32LE
:
2666 virtual wxMBConv
*Clone() const { return new wxMBConv_wxwin(m_enc
); }
2668 bool IsOk() const { return m_ok
; }
2671 wxFontEncoding m_enc
;
2672 wxEncodingConverter m2w
, w2m
;
2675 // were we initialized successfully?
2678 DECLARE_NO_COPY_CLASS(wxMBConv_wxwin
)
2681 // make the constructors available for unit testing
2682 WXDLLIMPEXP_BASE wxMBConv
* new_wxMBConv_wxwin( const char* name
)
2684 wxMBConv_wxwin
* result
= new wxMBConv_wxwin( name
);
2685 if ( !result
->IsOk() )
2694 #endif // wxUSE_FONTMAP
2696 // ============================================================================
2697 // wxCSConv implementation
2698 // ============================================================================
2700 void wxCSConv::Init()
2707 wxCSConv::wxCSConv(const wxString
& charset
)
2711 if ( !charset
.empty() )
2713 SetName(charset
.ToAscii());
2717 m_encoding
= wxFontMapperBase::GetEncodingFromName(charset
);
2719 m_encoding
= wxFONTENCODING_SYSTEM
;
2723 wxCSConv::wxCSConv(wxFontEncoding encoding
)
2725 if ( encoding
== wxFONTENCODING_MAX
|| encoding
== wxFONTENCODING_DEFAULT
)
2727 wxFAIL_MSG( _T("invalid encoding value in wxCSConv ctor") );
2729 encoding
= wxFONTENCODING_SYSTEM
;
2734 m_encoding
= encoding
;
2737 wxCSConv::~wxCSConv()
2742 wxCSConv::wxCSConv(const wxCSConv
& conv
)
2747 SetName(conv
.m_name
);
2748 m_encoding
= conv
.m_encoding
;
2751 wxCSConv
& wxCSConv::operator=(const wxCSConv
& conv
)
2755 SetName(conv
.m_name
);
2756 m_encoding
= conv
.m_encoding
;
2761 void wxCSConv::Clear()
2770 void wxCSConv::SetName(const char *charset
)
2774 m_name
= wxStrdup(charset
);
2781 WX_DECLARE_HASH_MAP( wxFontEncoding
, wxString
, wxIntegerHash
, wxIntegerEqual
,
2782 wxEncodingNameCache
);
2784 static wxEncodingNameCache gs_nameCache
;
2787 wxMBConv
*wxCSConv::DoCreate() const
2790 wxLogTrace(TRACE_STRCONV
,
2791 wxT("creating conversion for %s"),
2793 : (const char*)wxFontMapperBase::GetEncodingName(m_encoding
).mb_str()));
2794 #endif // wxUSE_FONTMAP
2796 // check for the special case of ASCII or ISO8859-1 charset: as we have
2797 // special knowledge of it anyhow, we don't need to create a special
2798 // conversion object
2799 if ( m_encoding
== wxFONTENCODING_ISO8859_1
||
2800 m_encoding
== wxFONTENCODING_DEFAULT
)
2802 // don't convert at all
2806 // we trust OS to do conversion better than we can so try external
2807 // conversion methods first
2809 // the full order is:
2810 // 1. OS conversion (iconv() under Unix or Win32 API)
2811 // 2. hard coded conversions for UTF
2812 // 3. wxEncodingConverter as fall back
2818 #endif // !wxUSE_FONTMAP
2821 wxFontEncoding
encoding(m_encoding
);
2826 wxMBConv_iconv
*conv
= new wxMBConv_iconv(m_name
);
2834 wxFontMapperBase::Get()->CharsetToEncoding(m_name
, false);
2835 #endif // wxUSE_FONTMAP
2839 const wxEncodingNameCache::iterator it
= gs_nameCache
.find(encoding
);
2840 if ( it
!= gs_nameCache
.end() )
2842 if ( it
->second
.empty() )
2845 wxMBConv_iconv
*conv
= new wxMBConv_iconv(it
->second
.ToAscii());
2852 const wxChar
** names
= wxFontMapperBase::GetAllEncodingNames(encoding
);
2853 // CS : in case this does not return valid names (eg for MacRoman)
2854 // encoding got a 'failure' entry in the cache all the same,
2855 // although it just has to be created using a different method, so
2856 // only store failed iconv creation attempts (or perhaps we
2857 // shoulnd't do this at all ?)
2858 if ( names
[0] != NULL
)
2860 for ( ; *names
; ++names
)
2862 // FIXME-UTF8: wxFontMapperBase::GetAllEncodingNames()
2863 // will need changes that will obsolete this
2864 wxString
name(*names
);
2865 wxMBConv_iconv
*conv
= new wxMBConv_iconv(name
.ToAscii());
2868 gs_nameCache
[encoding
] = *names
;
2875 gs_nameCache
[encoding
] = _T(""); // cache the failure
2878 #endif // wxUSE_FONTMAP
2880 #endif // HAVE_ICONV
2882 #ifdef wxHAVE_WIN32_MB2WC
2885 wxMBConv_win32
*conv
= m_name
? new wxMBConv_win32(m_name
)
2886 : new wxMBConv_win32(m_encoding
);
2895 #endif // wxHAVE_WIN32_MB2WC
2899 // leave UTF16 and UTF32 to the built-ins of wx
2900 if ( m_name
|| ( m_encoding
< wxFONTENCODING_UTF16BE
||
2901 ( m_encoding
>= wxFONTENCODING_MACMIN
&& m_encoding
<= wxFONTENCODING_MACMAX
) ) )
2904 wxMBConv_cf
*conv
= m_name
? new wxMBConv_cf(m_name
)
2905 : new wxMBConv_cf(m_encoding
);
2907 wxMBConv_cf
*conv
= new wxMBConv_cf(m_encoding
);
2916 #endif // __DARWIN__
2919 wxFontEncoding enc
= m_encoding
;
2921 if ( enc
== wxFONTENCODING_SYSTEM
&& m_name
)
2923 // use "false" to suppress interactive dialogs -- we can be called from
2924 // anywhere and popping up a dialog from here is the last thing we want to
2926 enc
= wxFontMapperBase::Get()->CharsetToEncoding(m_name
, false);
2928 #endif // wxUSE_FONTMAP
2932 case wxFONTENCODING_UTF7
:
2933 return new wxMBConvUTF7
;
2935 case wxFONTENCODING_UTF8
:
2936 return new wxMBConvUTF8
;
2938 case wxFONTENCODING_UTF16BE
:
2939 return new wxMBConvUTF16BE
;
2941 case wxFONTENCODING_UTF16LE
:
2942 return new wxMBConvUTF16LE
;
2944 case wxFONTENCODING_UTF32BE
:
2945 return new wxMBConvUTF32BE
;
2947 case wxFONTENCODING_UTF32LE
:
2948 return new wxMBConvUTF32LE
;
2951 // nothing to do but put here to suppress gcc warnings
2958 wxMBConv_wxwin
*conv
= m_name
? new wxMBConv_wxwin(m_name
)
2959 : new wxMBConv_wxwin(m_encoding
);
2965 #endif // wxUSE_FONTMAP
2967 // NB: This is a hack to prevent deadlock. What could otherwise happen
2968 // in Unicode build: wxConvLocal creation ends up being here
2969 // because of some failure and logs the error. But wxLog will try to
2970 // attach a timestamp, for which it will need wxConvLocal (to convert
2971 // time to char* and then wchar_t*), but that fails, tries to log the
2972 // error, but wxLog has an (already locked) critical section that
2973 // guards the static buffer.
2974 static bool alreadyLoggingError
= false;
2975 if (!alreadyLoggingError
)
2977 alreadyLoggingError
= true;
2978 wxLogError(_("Cannot convert from the charset '%s'!"),
2982 (const char*)wxFontMapperBase::GetEncodingDescription(m_encoding
).ToAscii()
2983 #else // !wxUSE_FONTMAP
2984 (const char*)wxString::Format(_("encoding %i"), m_encoding
).ToAscii()
2985 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
2988 alreadyLoggingError
= false;
2994 void wxCSConv::CreateConvIfNeeded() const
2998 wxCSConv
*self
= (wxCSConv
*)this; // const_cast
3000 // if we don't have neither the name nor the encoding, use the default
3001 // encoding for this system
3002 if ( !m_name
&& m_encoding
== wxFONTENCODING_SYSTEM
)
3005 self
->m_encoding
= wxLocale::GetSystemEncoding();
3007 // fallback to some reasonable default:
3008 self
->m_encoding
= wxFONTENCODING_ISO8859_1
;
3009 #endif // wxUSE_INTL
3012 self
->m_convReal
= DoCreate();
3013 self
->m_deferred
= false;
3017 bool wxCSConv::IsOk() const
3019 CreateConvIfNeeded();
3021 // special case: no convReal created for wxFONTENCODING_ISO8859_1
3022 if ( m_encoding
== wxFONTENCODING_ISO8859_1
)
3023 return true; // always ok as we do it ourselves
3025 // m_convReal->IsOk() is called at its own creation, so we know it must
3026 // be ok if m_convReal is non-NULL
3027 return m_convReal
!= NULL
;
3030 size_t wxCSConv::ToWChar(wchar_t *dst
, size_t dstLen
,
3031 const char *src
, size_t srcLen
) const
3033 CreateConvIfNeeded();
3036 return m_convReal
->ToWChar(dst
, dstLen
, src
, srcLen
);
3039 return wxMBConv::ToWChar(dst
, dstLen
, src
, srcLen
);
3042 size_t wxCSConv::FromWChar(char *dst
, size_t dstLen
,
3043 const wchar_t *src
, size_t srcLen
) const
3045 CreateConvIfNeeded();
3048 return m_convReal
->FromWChar(dst
, dstLen
, src
, srcLen
);
3051 return wxMBConv::FromWChar(dst
, dstLen
, src
, srcLen
);
3054 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
3056 CreateConvIfNeeded();
3059 return m_convReal
->MB2WC(buf
, psz
, n
);
3062 size_t len
= strlen(psz
);
3066 for (size_t c
= 0; c
<= len
; c
++)
3067 buf
[c
] = (unsigned char)(psz
[c
]);
3073 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
3075 CreateConvIfNeeded();
3078 return m_convReal
->WC2MB(buf
, psz
, n
);
3081 const size_t len
= wxWcslen(psz
);
3084 for (size_t c
= 0; c
<= len
; c
++)
3087 return wxCONV_FAILED
;
3089 buf
[c
] = (char)psz
[c
];
3094 for (size_t c
= 0; c
<= len
; c
++)
3097 return wxCONV_FAILED
;
3104 size_t wxCSConv::GetMBNulLen() const
3106 CreateConvIfNeeded();
3110 return m_convReal
->GetMBNulLen();
3113 // otherwise, we are ISO-8859-1
3117 #if wxUSE_UNICODE_UTF8
3118 bool wxCSConv::IsUTF8() const
3120 CreateConvIfNeeded();
3124 return m_convReal
->IsUTF8();
3127 // otherwise, we are ISO-8859-1
3135 wxWCharBuffer
wxSafeConvertMB2WX(const char *s
)
3138 return wxWCharBuffer();
3140 wxWCharBuffer
wbuf(wxConvLibc
.cMB2WX(s
));
3142 wbuf
= wxMBConvUTF8().cMB2WX(s
);
3144 wbuf
= wxConvISO8859_1
.cMB2WX(s
);
3149 wxCharBuffer
wxSafeConvertWX2MB(const wchar_t *ws
)
3152 return wxCharBuffer();
3154 wxCharBuffer
buf(wxConvLibc
.cWX2MB(ws
));
3156 buf
= wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_OCTAL
).cWX2MB(ws
);
3161 #endif // wxUSE_UNICODE
3163 // ----------------------------------------------------------------------------
3165 // ----------------------------------------------------------------------------
3167 // NB: The reason why we create converted objects in this convoluted way,
3168 // using a factory function instead of global variable, is that they
3169 // may be used at static initialization time (some of them are used by
3170 // wxString ctors and there may be a global wxString object). In other
3171 // words, possibly _before_ the converter global object would be
3178 #undef wxConvISO8859_1
3180 #define WX_DEFINE_GLOBAL_CONV2(klass, impl_klass, name, ctor_args) \
3181 WXDLLIMPEXP_DATA_BASE(klass*) name##Ptr = NULL; \
3182 WXDLLIMPEXP_BASE klass* wxGet_##name##Ptr() \
3184 static impl_klass name##Obj ctor_args; \
3185 return &name##Obj; \
3187 /* this ensures that all global converter objects are created */ \
3188 /* by the time static initialization is done, i.e. before any */ \
3189 /* thread is launched: */ \
3190 static klass* gs_##name##instance = wxGet_##name##Ptr()
3192 #define WX_DEFINE_GLOBAL_CONV(klass, name, ctor_args) \
3193 WX_DEFINE_GLOBAL_CONV2(klass, klass, name, ctor_args)
3196 WX_DEFINE_GLOBAL_CONV2(wxMBConv
, wxMBConv_win32
, wxConvLibc
, wxEMPTY_PARAMETER_VALUE
);
3198 WX_DEFINE_GLOBAL_CONV2(wxMBConv
, wxMBConvLibc
, wxConvLibc
, wxEMPTY_PARAMETER_VALUE
);
3201 // NB: we can't use wxEMPTY_PARAMETER_VALUE as final argument here because it's
3202 // passed to WX_DEFINE_GLOBAL_CONV2 after a macro expansion and so still
3203 // provokes an error message about "not enough macro parameters"; and we
3204 // can't use "()" here as the name##Obj declaration would be parsed as a
3205 // function declaration then, so use a semicolon and live with an extra
3206 // empty statement (and hope that no compilers warns about this)
3207 WX_DEFINE_GLOBAL_CONV(wxMBConvStrictUTF8
, wxConvUTF8
, ;);
3208 WX_DEFINE_GLOBAL_CONV(wxMBConvUTF7
, wxConvUTF7
, ;);
3210 WX_DEFINE_GLOBAL_CONV(wxCSConv
, wxConvLocal
, (wxFONTENCODING_SYSTEM
));
3211 WX_DEFINE_GLOBAL_CONV(wxCSConv
, wxConvISO8859_1
, (wxFONTENCODING_ISO8859_1
));
3213 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvCurrent
= wxGet_wxConvLibcPtr();
3214 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvUI
= wxGet_wxConvLocalPtr();
3217 // The xnu kernel always communicates file paths in decomposed UTF-8.
3218 // WARNING: Are we sure that CFString's conversion will cause decomposition?
3219 static wxMBConv_cf
wxConvMacUTF8DObj(wxFONTENCODING_UTF8
);
3222 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvFileName
=
3225 #else // !__DARWIN__
3226 wxGet_wxConvLibcPtr();
3227 #endif // __DARWIN__/!__DARWIN__
3229 #else // !wxUSE_WCHAR_T
3231 // FIXME-UTF8: remove this, wxUSE_WCHAR_T is required now
3232 // stand-ins in absence of wchar_t
3233 WXDLLIMPEXP_DATA_BASE(wxMBConv
) wxConvLibc
,
3238 #endif // wxUSE_WCHAR_T/!wxUSE_WCHAR_T