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 wxWCharBuffer
wbuf(dstLen
- 1);
395 if ( ToWChar(wbuf
.data(), dstLen
, inBuff
, inLen
) != wxCONV_FAILED
)
400 if ( wbuf
[dstLen
- 1] == L
'\0' )
411 return wxWCharBuffer();
415 wxMBConv::cWC2MB(const wchar_t *inBuff
, size_t inLen
, size_t *outLen
) const
417 size_t dstLen
= FromWChar(NULL
, 0, inBuff
, inLen
);
418 if ( dstLen
!= wxCONV_FAILED
)
420 // special case of empty input: can't allocate 0 size buffer below as
421 // wxCharBuffer insists on NUL-terminating it
422 wxCharBuffer
buf(dstLen
? dstLen
- 1 : 1);
423 if ( FromWChar(buf
.data(), dstLen
, inBuff
, inLen
) != wxCONV_FAILED
)
429 const size_t nulLen
= GetMBNulLen();
430 if ( dstLen
>= nulLen
&&
431 !NotAllNULs(buf
.data() + dstLen
- nulLen
, nulLen
) )
433 // in this case the output is NUL-terminated and we're not
434 // supposed to count NUL
446 return wxCharBuffer();
449 // ----------------------------------------------------------------------------
451 // ----------------------------------------------------------------------------
453 size_t wxMBConvLibc::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
455 return wxMB2WC(buf
, psz
, n
);
458 size_t wxMBConvLibc::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
460 return wxWC2MB(buf
, psz
, n
);
463 // ----------------------------------------------------------------------------
464 // wxConvBrokenFileNames
465 // ----------------------------------------------------------------------------
469 wxConvBrokenFileNames::wxConvBrokenFileNames(const wxString
& charset
)
471 if ( wxStricmp(charset
, _T("UTF-8")) == 0 ||
472 wxStricmp(charset
, _T("UTF8")) == 0 )
473 m_conv
= new wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_PUA
);
475 m_conv
= new wxCSConv(charset
);
480 // ----------------------------------------------------------------------------
482 // ----------------------------------------------------------------------------
484 // Implementation (C) 2004 Fredrik Roubert
487 // BASE64 decoding table
489 static const unsigned char utf7unb64
[] =
491 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
492 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
493 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
494 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
495 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
496 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f,
497 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b,
498 0x3c, 0x3d, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
499 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
500 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
501 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16,
502 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
503 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
504 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
505 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
506 0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff,
507 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
508 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
509 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
510 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
511 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
512 0xff, 0xff, 0xff, 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
525 size_t wxMBConvUTF7::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
529 while ( *psz
&& (!buf
|| (len
< n
)) )
531 unsigned char cc
= *psz
++;
539 else if (*psz
== '-')
547 else // start of BASE64 encoded string
551 for ( ok
= lsb
= false, d
= 0, l
= 0;
552 (cc
= utf7unb64
[(unsigned char)*psz
]) != 0xff;
557 for (l
+= 6; l
>= 8; lsb
= !lsb
)
559 unsigned char c
= (unsigned char)((d
>> (l
-= 8)) % 256);
569 *buf
= (wchar_t)(c
<< 8);
578 // in valid UTF7 we should have valid characters after '+'
579 return wxCONV_FAILED
;
587 if ( buf
&& (len
< n
) )
594 // BASE64 encoding table
596 static const unsigned char utf7enb64
[] =
598 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
599 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
600 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
601 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
602 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
603 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
604 'w', 'x', 'y', 'z', '0', '1', '2', '3',
605 '4', '5', '6', '7', '8', '9', '+', '/'
609 // UTF-7 encoding table
611 // 0 - Set D (directly encoded characters)
612 // 1 - Set O (optional direct characters)
613 // 2 - whitespace characters (optional)
614 // 3 - special characters
616 static const unsigned char utf7encode
[128] =
618 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 3, 3, 2, 3, 3,
619 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
620 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 0, 0, 0, 3,
621 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0,
622 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
623 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 1, 1, 1,
624 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
625 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3
628 size_t wxMBConvUTF7::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
632 while (*psz
&& ((!buf
) || (len
< n
)))
635 if (cc
< 0x80 && utf7encode
[cc
] < 1)
644 else if (((wxUint32
)cc
) > 0xffff)
646 // no surrogate pair generation (yet?)
647 return wxCONV_FAILED
;
658 // BASE64 encode string
659 unsigned int lsb
, d
, l
;
660 for (d
= 0, l
= 0; /*nothing*/; psz
++)
662 for (lsb
= 0; lsb
< 2; lsb
++)
665 d
+= lsb
? cc
& 0xff : (cc
& 0xff00) >> 8;
667 for (l
+= 8; l
>= 6; )
671 *buf
++ = utf7enb64
[(d
>> l
) % 64];
677 if (!(cc
) || (cc
< 0x80 && utf7encode
[cc
] < 1))
684 *buf
++ = utf7enb64
[((d
% 16) << (6 - l
)) % 64];
696 if (buf
&& (len
< n
))
702 // ----------------------------------------------------------------------------
704 // ----------------------------------------------------------------------------
706 static const wxUint32 utf8_max
[]=
707 { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff, 0xffffffff };
709 // boundaries of the private use area we use to (temporarily) remap invalid
710 // characters invalid in a UTF-8 encoded string
711 const wxUint32 wxUnicodePUA
= 0x100000;
712 const wxUint32 wxUnicodePUAEnd
= wxUnicodePUA
+ 256;
714 // this table gives the length of the UTF-8 encoding from its first character:
715 const unsigned char tableUtf8Lengths
[256] = {
716 // single-byte sequences (ASCII):
717 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 00..0F
718 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 10..1F
719 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 20..2F
720 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 30..3F
721 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 40..4F
722 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 50..5F
723 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 60..6F
724 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 70..7F
726 // these are invalid:
727 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 80..8F
728 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 90..9F
729 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A0..AF
730 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B0..BF
733 // two-byte sequences:
734 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C2..CF
735 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // D0..DF
737 // three-byte sequences:
738 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, // E0..EF
740 // four-byte sequences:
741 4, 4, 4, 4, 4, // F0..F4
743 // these are invalid again (5- or 6-byte
744 // sequences and sequences for code points
745 // above U+10FFFF, as restricted by RFC 3629):
746 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F5..FF
750 wxMBConvStrictUTF8::ToWChar(wchar_t *dst
, size_t dstLen
,
751 const char *src
, size_t srcLen
) const
753 wchar_t *out
= dstLen
? dst
: NULL
;
756 if ( srcLen
== wxNO_LEN
)
757 srcLen
= strlen(src
) + 1;
759 for ( const char *p
= src
; ; p
++ )
761 if ( !(srcLen
== wxNO_LEN
? *p
: srcLen
) )
763 // all done successfully, just add the trailing NULL if we are not
764 // using explicit length
765 if ( srcLen
== wxNO_LEN
)
781 if ( out
&& !dstLen
-- )
785 unsigned char c
= *p
;
789 if ( srcLen
== 0 ) // the test works for wxNO_LEN too
792 if ( srcLen
!= wxNO_LEN
)
799 unsigned len
= tableUtf8Lengths
[c
];
803 if ( srcLen
< len
) // the test works for wxNO_LEN too
806 if ( srcLen
!= wxNO_LEN
)
809 // Char. number range | UTF-8 octet sequence
810 // (hexadecimal) | (binary)
811 // ----------------------+----------------------------------------
812 // 0000 0000 - 0000 007F | 0xxxxxxx
813 // 0000 0080 - 0000 07FF | 110xxxxx 10xxxxxx
814 // 0000 0800 - 0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
815 // 0001 0000 - 0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
817 // Code point value is stored in bits marked with 'x',
818 // lowest-order bit of the value on the right side in the diagram
819 // above. (from RFC 3629)
821 // mask to extract lead byte's value ('x' bits above), by sequence
823 static const unsigned char leadValueMask
[] = { 0x7F, 0x1F, 0x0F, 0x07 };
825 // mask and value of lead byte's most significant bits, by length:
826 static const unsigned char leadMarkerMask
[] = { 0x80, 0xE0, 0xF0, 0xF8 };
827 static const unsigned char leadMarkerVal
[] = { 0x00, 0xC0, 0xE0, 0xF0 };
829 len
--; // it's more convenient to work with 0-based length here
831 // extract the lead byte's value bits:
832 if ( (c
& leadMarkerMask
[len
]) != leadMarkerVal
[len
] )
835 code
= c
& leadValueMask
[len
];
837 // all remaining bytes, if any, are handled in the same way
838 // regardless of sequence's length:
842 if ( (c
& 0xC0) != 0x80 )
843 return wxCONV_FAILED
;
851 // cast is ok because wchar_t == wxUint16 if WC_UTF16
852 if ( encode_utf16(code
, (wxUint16
*)out
) == 2 )
861 #endif // WC_UTF16/!WC_UTF16
869 return wxCONV_FAILED
;
873 wxMBConvStrictUTF8::FromWChar(char *dst
, size_t dstLen
,
874 const wchar_t *src
, size_t srcLen
) const
876 char *out
= dstLen
? dst
: NULL
;
879 for ( const wchar_t *wp
= src
; ; wp
++ )
881 if ( !(srcLen
== wxNO_LEN
? *wp
: srcLen
--) )
883 // all done successfully, just add the trailing NULL if we are not
884 // using explicit length
885 if ( srcLen
== wxNO_LEN
)
904 // cast is ok for WC_UTF16
905 if ( decode_utf16((const wxUint16
*)wp
, code
) == 2 )
907 // skip the next char too as we decoded a surrogate
910 #else // wchar_t is UTF-32
911 code
= *wp
& 0x7fffffff;
926 else if ( code
<= 0x07FF )
934 // NB: this line takes 6 least significant bits, encodes them as
935 // 10xxxxxx and discards them so that the next byte can be encoded:
936 out
[1] = 0x80 | (code
& 0x3F); code
>>= 6;
937 out
[0] = 0xC0 | code
;
940 else if ( code
< 0xFFFF )
948 out
[2] = 0x80 | (code
& 0x3F); code
>>= 6;
949 out
[1] = 0x80 | (code
& 0x3F); code
>>= 6;
950 out
[0] = 0xE0 | code
;
953 else if ( code
<= 0x10FFFF )
961 out
[3] = 0x80 | (code
& 0x3F); code
>>= 6;
962 out
[2] = 0x80 | (code
& 0x3F); code
>>= 6;
963 out
[1] = 0x80 | (code
& 0x3F); code
>>= 6;
964 out
[0] = 0xF0 | code
;
969 wxFAIL_MSG( _T("trying to encode undefined Unicode character") );
982 // we only get here if an error occurs during decoding
983 return wxCONV_FAILED
;
986 size_t wxMBConvUTF8::ToWChar(wchar_t *buf
, size_t n
,
987 const char *psz
, size_t srcLen
) const
989 if ( m_options
== MAP_INVALID_UTF8_NOT
)
990 return wxMBConvStrictUTF8::ToWChar(buf
, n
, psz
, srcLen
);
994 while ((srcLen
== wxNO_LEN
? *psz
: srcLen
--) && ((!buf
) || (len
< n
)))
996 const char *opsz
= psz
;
997 bool invalid
= false;
998 unsigned char cc
= *psz
++, fc
= cc
;
1000 for (cnt
= 0; fc
& 0x80; cnt
++)
1010 // escape the escape character for octal escapes
1011 if ((m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
1012 && cc
== '\\' && (!buf
|| len
< n
))
1024 // invalid UTF-8 sequence
1029 unsigned ocnt
= cnt
- 1;
1030 wxUint32 res
= cc
& (0x3f >> cnt
);
1034 if ((cc
& 0xC0) != 0x80)
1036 // invalid UTF-8 sequence
1042 res
= (res
<< 6) | (cc
& 0x3f);
1045 if (invalid
|| res
<= utf8_max
[ocnt
])
1047 // illegal UTF-8 encoding
1050 else if ((m_options
& MAP_INVALID_UTF8_TO_PUA
) &&
1051 res
>= wxUnicodePUA
&& res
< wxUnicodePUAEnd
)
1053 // if one of our PUA characters turns up externally
1054 // it must also be treated as an illegal sequence
1055 // (a bit like you have to escape an escape character)
1061 // cast is ok because wchar_t == wxUint16 if WC_UTF16
1062 size_t pa
= encode_utf16(res
, (wxUint16
*)buf
);
1063 if (pa
== wxCONV_FAILED
)
1075 *buf
++ = (wchar_t)res
;
1077 #endif // WC_UTF16/!WC_UTF16
1083 if (m_options
& MAP_INVALID_UTF8_TO_PUA
)
1085 while (opsz
< psz
&& (!buf
|| len
< n
))
1088 // cast is ok because wchar_t == wxUuint16 if WC_UTF16
1089 size_t pa
= encode_utf16((unsigned char)*opsz
+ wxUnicodePUA
, (wxUint16
*)buf
);
1090 wxASSERT(pa
!= wxCONV_FAILED
);
1097 *buf
++ = (wchar_t)(wxUnicodePUA
+ (unsigned char)*opsz
);
1103 else if (m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
1105 while (opsz
< psz
&& (!buf
|| len
< n
))
1107 if ( buf
&& len
+ 3 < n
)
1109 unsigned char on
= *opsz
;
1111 *buf
++ = (wchar_t)( L
'0' + on
/ 0100 );
1112 *buf
++ = (wchar_t)( L
'0' + (on
% 0100) / 010 );
1113 *buf
++ = (wchar_t)( L
'0' + on
% 010 );
1120 else // MAP_INVALID_UTF8_NOT
1122 return wxCONV_FAILED
;
1128 if (srcLen
== wxNO_LEN
&& buf
&& (len
< n
))
1134 static inline bool isoctal(wchar_t wch
)
1136 return L
'0' <= wch
&& wch
<= L
'7';
1139 size_t wxMBConvUTF8::FromWChar(char *buf
, size_t n
,
1140 const wchar_t *psz
, size_t srcLen
) const
1142 if ( m_options
== MAP_INVALID_UTF8_NOT
)
1143 return wxMBConvStrictUTF8::FromWChar(buf
, n
, psz
, srcLen
);
1147 while ((srcLen
== wxNO_LEN
? *psz
: srcLen
--) && ((!buf
) || (len
< n
)))
1152 // cast is ok for WC_UTF16
1153 size_t pa
= decode_utf16((const wxUint16
*)psz
, cc
);
1154 psz
+= (pa
== wxCONV_FAILED
) ? 1 : pa
;
1156 cc
= (*psz
++) & 0x7fffffff;
1159 if ( (m_options
& MAP_INVALID_UTF8_TO_PUA
)
1160 && cc
>= wxUnicodePUA
&& cc
< wxUnicodePUAEnd
)
1163 *buf
++ = (char)(cc
- wxUnicodePUA
);
1166 else if ( (m_options
& MAP_INVALID_UTF8_TO_OCTAL
)
1167 && cc
== L
'\\' && psz
[0] == L
'\\' )
1174 else if ( (m_options
& MAP_INVALID_UTF8_TO_OCTAL
) &&
1176 isoctal(psz
[0]) && isoctal(psz
[1]) && isoctal(psz
[2]) )
1180 *buf
++ = (char) ((psz
[0] - L
'0') * 0100 +
1181 (psz
[1] - L
'0') * 010 +
1191 for (cnt
= 0; cc
> utf8_max
[cnt
]; cnt
++)
1207 *buf
++ = (char) ((-128 >> cnt
) | ((cc
>> (cnt
* 6)) & (0x3f >> cnt
)));
1209 *buf
++ = (char) (0x80 | ((cc
>> (cnt
* 6)) & 0x3f));
1215 if (srcLen
== wxNO_LEN
&& buf
&& (len
< n
))
1221 // ============================================================================
1223 // ============================================================================
1225 #ifdef WORDS_BIGENDIAN
1226 #define wxMBConvUTF16straight wxMBConvUTF16BE
1227 #define wxMBConvUTF16swap wxMBConvUTF16LE
1229 #define wxMBConvUTF16swap wxMBConvUTF16BE
1230 #define wxMBConvUTF16straight wxMBConvUTF16LE
1234 size_t wxMBConvUTF16Base::GetLength(const char *src
, size_t srcLen
)
1236 if ( srcLen
== wxNO_LEN
)
1238 // count the number of bytes in input, including the trailing NULs
1239 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1240 for ( srcLen
= 1; *inBuff
++; srcLen
++ )
1243 srcLen
*= BYTES_PER_CHAR
;
1245 else // we already have the length
1247 // we can only convert an entire number of UTF-16 characters
1248 if ( srcLen
% BYTES_PER_CHAR
)
1249 return wxCONV_FAILED
;
1255 // case when in-memory representation is UTF-16 too
1258 // ----------------------------------------------------------------------------
1259 // conversions without endianness change
1260 // ----------------------------------------------------------------------------
1263 wxMBConvUTF16straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1264 const char *src
, size_t srcLen
) const
1266 // set up the scene for using memcpy() (which is presumably more efficient
1267 // than copying the bytes one by one)
1268 srcLen
= GetLength(src
, srcLen
);
1269 if ( srcLen
== wxNO_LEN
)
1270 return wxCONV_FAILED
;
1272 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1275 if ( dstLen
< inLen
)
1276 return wxCONV_FAILED
;
1278 memcpy(dst
, src
, srcLen
);
1285 wxMBConvUTF16straight::FromWChar(char *dst
, size_t dstLen
,
1286 const wchar_t *src
, size_t srcLen
) const
1288 if ( srcLen
== wxNO_LEN
)
1289 srcLen
= wxWcslen(src
) + 1;
1291 srcLen
*= BYTES_PER_CHAR
;
1295 if ( dstLen
< srcLen
)
1296 return wxCONV_FAILED
;
1298 memcpy(dst
, src
, srcLen
);
1304 // ----------------------------------------------------------------------------
1305 // endian-reversing conversions
1306 // ----------------------------------------------------------------------------
1309 wxMBConvUTF16swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1310 const char *src
, size_t srcLen
) const
1312 srcLen
= GetLength(src
, srcLen
);
1313 if ( srcLen
== wxNO_LEN
)
1314 return wxCONV_FAILED
;
1316 srcLen
/= BYTES_PER_CHAR
;
1320 if ( dstLen
< srcLen
)
1321 return wxCONV_FAILED
;
1323 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1324 for ( size_t n
= 0; n
< srcLen
; n
++, inBuff
++ )
1326 *dst
++ = wxUINT16_SWAP_ALWAYS(*inBuff
);
1334 wxMBConvUTF16swap::FromWChar(char *dst
, size_t dstLen
,
1335 const wchar_t *src
, size_t srcLen
) const
1337 if ( srcLen
== wxNO_LEN
)
1338 srcLen
= wxWcslen(src
) + 1;
1340 srcLen
*= BYTES_PER_CHAR
;
1344 if ( dstLen
< srcLen
)
1345 return wxCONV_FAILED
;
1347 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1348 for ( size_t n
= 0; n
< srcLen
; n
+= BYTES_PER_CHAR
, src
++ )
1350 *outBuff
++ = wxUINT16_SWAP_ALWAYS(*src
);
1357 #else // !WC_UTF16: wchar_t is UTF-32
1359 // ----------------------------------------------------------------------------
1360 // conversions without endianness change
1361 // ----------------------------------------------------------------------------
1364 wxMBConvUTF16straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1365 const char *src
, size_t srcLen
) const
1367 srcLen
= GetLength(src
, srcLen
);
1368 if ( srcLen
== wxNO_LEN
)
1369 return wxCONV_FAILED
;
1371 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1374 // optimization: return maximal space which could be needed for this
1375 // string even if the real size could be smaller if the buffer contains
1381 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1382 for ( const wxUint16
* const inEnd
= inBuff
+ inLen
; inBuff
< inEnd
; )
1384 const wxUint32 ch
= wxDecodeSurrogate(&inBuff
);
1386 return wxCONV_FAILED
;
1388 if ( ++outLen
> dstLen
)
1389 return wxCONV_FAILED
;
1399 wxMBConvUTF16straight::FromWChar(char *dst
, size_t dstLen
,
1400 const wchar_t *src
, size_t srcLen
) const
1402 if ( srcLen
== wxNO_LEN
)
1403 srcLen
= wxWcslen(src
) + 1;
1406 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1407 for ( size_t n
= 0; n
< srcLen
; n
++ )
1410 const size_t numChars
= encode_utf16(*src
++, cc
);
1411 if ( numChars
== wxCONV_FAILED
)
1412 return wxCONV_FAILED
;
1414 outLen
+= numChars
* BYTES_PER_CHAR
;
1417 if ( outLen
> dstLen
)
1418 return wxCONV_FAILED
;
1421 if ( numChars
== 2 )
1423 // second character of a surrogate
1432 // ----------------------------------------------------------------------------
1433 // endian-reversing conversions
1434 // ----------------------------------------------------------------------------
1437 wxMBConvUTF16swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1438 const char *src
, size_t srcLen
) const
1440 srcLen
= GetLength(src
, srcLen
);
1441 if ( srcLen
== wxNO_LEN
)
1442 return wxCONV_FAILED
;
1444 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1447 // optimization: return maximal space which could be needed for this
1448 // string even if the real size could be smaller if the buffer contains
1454 const wxUint16
*inBuff
= wx_reinterpret_cast(const wxUint16
*, src
);
1455 for ( const wxUint16
* const inEnd
= inBuff
+ inLen
; inBuff
< inEnd
; )
1460 tmp
[0] = wxUINT16_SWAP_ALWAYS(*inBuff
);
1462 tmp
[1] = wxUINT16_SWAP_ALWAYS(*inBuff
);
1464 const size_t numChars
= decode_utf16(tmp
, ch
);
1465 if ( numChars
== wxCONV_FAILED
)
1466 return wxCONV_FAILED
;
1468 if ( numChars
== 2 )
1471 if ( ++outLen
> dstLen
)
1472 return wxCONV_FAILED
;
1482 wxMBConvUTF16swap::FromWChar(char *dst
, size_t dstLen
,
1483 const wchar_t *src
, size_t srcLen
) const
1485 if ( srcLen
== wxNO_LEN
)
1486 srcLen
= wxWcslen(src
) + 1;
1489 wxUint16
*outBuff
= wx_reinterpret_cast(wxUint16
*, dst
);
1490 for ( const wchar_t *srcEnd
= src
+ srcLen
; src
< srcEnd
; src
++ )
1493 const size_t numChars
= encode_utf16(*src
, cc
);
1494 if ( numChars
== wxCONV_FAILED
)
1495 return wxCONV_FAILED
;
1497 outLen
+= numChars
* BYTES_PER_CHAR
;
1500 if ( outLen
> dstLen
)
1501 return wxCONV_FAILED
;
1503 *outBuff
++ = wxUINT16_SWAP_ALWAYS(cc
[0]);
1504 if ( numChars
== 2 )
1506 // second character of a surrogate
1507 *outBuff
++ = wxUINT16_SWAP_ALWAYS(cc
[1]);
1515 #endif // WC_UTF16/!WC_UTF16
1518 // ============================================================================
1520 // ============================================================================
1522 #ifdef WORDS_BIGENDIAN
1523 #define wxMBConvUTF32straight wxMBConvUTF32BE
1524 #define wxMBConvUTF32swap wxMBConvUTF32LE
1526 #define wxMBConvUTF32swap wxMBConvUTF32BE
1527 #define wxMBConvUTF32straight wxMBConvUTF32LE
1531 WXDLLIMPEXP_DATA_BASE(wxMBConvUTF32LE
) wxConvUTF32LE
;
1532 WXDLLIMPEXP_DATA_BASE(wxMBConvUTF32BE
) wxConvUTF32BE
;
1535 size_t wxMBConvUTF32Base::GetLength(const char *src
, size_t srcLen
)
1537 if ( srcLen
== wxNO_LEN
)
1539 // count the number of bytes in input, including the trailing NULs
1540 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1541 for ( srcLen
= 1; *inBuff
++; srcLen
++ )
1544 srcLen
*= BYTES_PER_CHAR
;
1546 else // we already have the length
1548 // we can only convert an entire number of UTF-32 characters
1549 if ( srcLen
% BYTES_PER_CHAR
)
1550 return wxCONV_FAILED
;
1556 // case when in-memory representation is UTF-16
1559 // ----------------------------------------------------------------------------
1560 // conversions without endianness change
1561 // ----------------------------------------------------------------------------
1564 wxMBConvUTF32straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1565 const char *src
, size_t srcLen
) const
1567 srcLen
= GetLength(src
, srcLen
);
1568 if ( srcLen
== wxNO_LEN
)
1569 return wxCONV_FAILED
;
1571 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1572 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1574 for ( size_t n
= 0; n
< inLen
; n
++ )
1577 const size_t numChars
= encode_utf16(*inBuff
++, cc
);
1578 if ( numChars
== wxCONV_FAILED
)
1579 return wxCONV_FAILED
;
1584 if ( outLen
> dstLen
)
1585 return wxCONV_FAILED
;
1588 if ( numChars
== 2 )
1590 // second character of a surrogate
1600 wxMBConvUTF32straight::FromWChar(char *dst
, size_t dstLen
,
1601 const wchar_t *src
, size_t srcLen
) const
1603 if ( srcLen
== wxNO_LEN
)
1604 srcLen
= wxWcslen(src
) + 1;
1608 // optimization: return maximal space which could be needed for this
1609 // string instead of the exact amount which could be less if there are
1610 // any surrogates in the input
1612 // we consider that surrogates are rare enough to make it worthwhile to
1613 // avoid running the loop below at the cost of slightly extra memory
1615 return srcLen
* BYTES_PER_CHAR
;
1618 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1620 for ( const wchar_t * const srcEnd
= src
+ srcLen
; src
< srcEnd
; )
1622 const wxUint32 ch
= wxDecodeSurrogate(&src
);
1624 return wxCONV_FAILED
;
1626 outLen
+= BYTES_PER_CHAR
;
1628 if ( outLen
> dstLen
)
1629 return wxCONV_FAILED
;
1637 // ----------------------------------------------------------------------------
1638 // endian-reversing conversions
1639 // ----------------------------------------------------------------------------
1642 wxMBConvUTF32swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1643 const char *src
, size_t srcLen
) const
1645 srcLen
= GetLength(src
, srcLen
);
1646 if ( srcLen
== wxNO_LEN
)
1647 return wxCONV_FAILED
;
1649 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1650 const size_t inLen
= srcLen
/ BYTES_PER_CHAR
;
1652 for ( size_t n
= 0; n
< inLen
; n
++, inBuff
++ )
1655 const size_t numChars
= encode_utf16(wxUINT32_SWAP_ALWAYS(*inBuff
), cc
);
1656 if ( numChars
== wxCONV_FAILED
)
1657 return wxCONV_FAILED
;
1662 if ( outLen
> dstLen
)
1663 return wxCONV_FAILED
;
1666 if ( numChars
== 2 )
1668 // second character of a surrogate
1678 wxMBConvUTF32swap::FromWChar(char *dst
, size_t dstLen
,
1679 const wchar_t *src
, size_t srcLen
) const
1681 if ( srcLen
== wxNO_LEN
)
1682 srcLen
= wxWcslen(src
) + 1;
1686 // optimization: return maximal space which could be needed for this
1687 // string instead of the exact amount which could be less if there are
1688 // any surrogates in the input
1690 // we consider that surrogates are rare enough to make it worthwhile to
1691 // avoid running the loop below at the cost of slightly extra memory
1693 return srcLen
*BYTES_PER_CHAR
;
1696 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1698 for ( const wchar_t * const srcEnd
= src
+ srcLen
; src
< srcEnd
; )
1700 const wxUint32 ch
= wxDecodeSurrogate(&src
);
1702 return wxCONV_FAILED
;
1704 outLen
+= BYTES_PER_CHAR
;
1706 if ( outLen
> dstLen
)
1707 return wxCONV_FAILED
;
1709 *outBuff
++ = wxUINT32_SWAP_ALWAYS(ch
);
1715 #else // !WC_UTF16: wchar_t is UTF-32
1717 // ----------------------------------------------------------------------------
1718 // conversions without endianness change
1719 // ----------------------------------------------------------------------------
1722 wxMBConvUTF32straight::ToWChar(wchar_t *dst
, size_t dstLen
,
1723 const char *src
, size_t srcLen
) const
1725 // use memcpy() as it should be much faster than hand-written loop
1726 srcLen
= GetLength(src
, srcLen
);
1727 if ( srcLen
== wxNO_LEN
)
1728 return wxCONV_FAILED
;
1730 const size_t inLen
= srcLen
/BYTES_PER_CHAR
;
1733 if ( dstLen
< inLen
)
1734 return wxCONV_FAILED
;
1736 memcpy(dst
, src
, srcLen
);
1743 wxMBConvUTF32straight::FromWChar(char *dst
, size_t dstLen
,
1744 const wchar_t *src
, size_t srcLen
) const
1746 if ( srcLen
== wxNO_LEN
)
1747 srcLen
= wxWcslen(src
) + 1;
1749 srcLen
*= BYTES_PER_CHAR
;
1753 if ( dstLen
< srcLen
)
1754 return wxCONV_FAILED
;
1756 memcpy(dst
, src
, srcLen
);
1762 // ----------------------------------------------------------------------------
1763 // endian-reversing conversions
1764 // ----------------------------------------------------------------------------
1767 wxMBConvUTF32swap::ToWChar(wchar_t *dst
, size_t dstLen
,
1768 const char *src
, size_t srcLen
) const
1770 srcLen
= GetLength(src
, srcLen
);
1771 if ( srcLen
== wxNO_LEN
)
1772 return wxCONV_FAILED
;
1774 srcLen
/= BYTES_PER_CHAR
;
1778 if ( dstLen
< srcLen
)
1779 return wxCONV_FAILED
;
1781 const wxUint32
*inBuff
= wx_reinterpret_cast(const wxUint32
*, src
);
1782 for ( size_t n
= 0; n
< srcLen
; n
++, inBuff
++ )
1784 *dst
++ = wxUINT32_SWAP_ALWAYS(*inBuff
);
1792 wxMBConvUTF32swap::FromWChar(char *dst
, size_t dstLen
,
1793 const wchar_t *src
, size_t srcLen
) const
1795 if ( srcLen
== wxNO_LEN
)
1796 srcLen
= wxWcslen(src
) + 1;
1798 srcLen
*= BYTES_PER_CHAR
;
1802 if ( dstLen
< srcLen
)
1803 return wxCONV_FAILED
;
1805 wxUint32
*outBuff
= wx_reinterpret_cast(wxUint32
*, dst
);
1806 for ( size_t n
= 0; n
< srcLen
; n
+= BYTES_PER_CHAR
, src
++ )
1808 *outBuff
++ = wxUINT32_SWAP_ALWAYS(*src
);
1815 #endif // WC_UTF16/!WC_UTF16
1818 // ============================================================================
1819 // The classes doing conversion using the iconv_xxx() functions
1820 // ============================================================================
1824 // VS: glibc 2.1.3 is broken in that iconv() conversion to/from UCS4 fails with
1825 // E2BIG if output buffer is _exactly_ as big as needed. Such case is
1826 // (unless there's yet another bug in glibc) the only case when iconv()
1827 // returns with (size_t)-1 (which means error) and says there are 0 bytes
1828 // left in the input buffer -- when _real_ error occurs,
1829 // bytes-left-in-input buffer is non-zero. Hence, this alternative test for
1831 // [This bug does not appear in glibc 2.2.]
1832 #if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ <= 1
1833 #define ICONV_FAILED(cres, bufLeft) ((cres == (size_t)-1) && \
1834 (errno != E2BIG || bufLeft != 0))
1836 #define ICONV_FAILED(cres, bufLeft) (cres == (size_t)-1)
1839 #define ICONV_CHAR_CAST(x) ((ICONV_CONST char **)(x))
1841 #define ICONV_T_INVALID ((iconv_t)-1)
1843 #if SIZEOF_WCHAR_T == 4
1844 #define WC_BSWAP wxUINT32_SWAP_ALWAYS
1845 #define WC_ENC wxFONTENCODING_UTF32
1846 #elif SIZEOF_WCHAR_T == 2
1847 #define WC_BSWAP wxUINT16_SWAP_ALWAYS
1848 #define WC_ENC wxFONTENCODING_UTF16
1849 #else // sizeof(wchar_t) != 2 nor 4
1850 // does this ever happen?
1851 #error "Unknown sizeof(wchar_t): please report this to wx-dev@lists.wxwindows.org"
1854 // ----------------------------------------------------------------------------
1855 // wxMBConv_iconv: encapsulates an iconv character set
1856 // ----------------------------------------------------------------------------
1858 class wxMBConv_iconv
: public wxMBConv
1861 wxMBConv_iconv(const char *name
);
1862 virtual ~wxMBConv_iconv();
1864 virtual size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const;
1865 virtual size_t WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const;
1867 // classify this encoding as explained in wxMBConv::GetMBNulLen() comment
1868 virtual size_t GetMBNulLen() const;
1870 #if wxUSE_UNICODE_UTF8
1871 virtual bool IsUTF8() const;
1874 virtual wxMBConv
*Clone() const
1876 wxMBConv_iconv
*p
= new wxMBConv_iconv(m_name
.ToAscii());
1877 p
->m_minMBCharWidth
= m_minMBCharWidth
;
1882 { return (m2w
!= ICONV_T_INVALID
) && (w2m
!= ICONV_T_INVALID
); }
1885 // the iconv handlers used to translate from multibyte
1886 // to wide char and in the other direction
1891 // guards access to m2w and w2m objects
1892 wxMutex m_iconvMutex
;
1896 // the name (for iconv_open()) of a wide char charset -- if none is
1897 // available on this machine, it will remain NULL
1898 static wxString ms_wcCharsetName
;
1900 // true if the wide char encoding we use (i.e. ms_wcCharsetName) has
1901 // different endian-ness than the native one
1902 static bool ms_wcNeedsSwap
;
1905 // name of the encoding handled by this conversion
1908 // cached result of GetMBNulLen(); set to 0 meaning "unknown"
1910 size_t m_minMBCharWidth
;
1913 // make the constructor available for unit testing
1914 WXDLLIMPEXP_BASE wxMBConv
* new_wxMBConv_iconv( const char* name
)
1916 wxMBConv_iconv
* result
= new wxMBConv_iconv( name
);
1917 if ( !result
->IsOk() )
1926 wxString
wxMBConv_iconv::ms_wcCharsetName
;
1927 bool wxMBConv_iconv::ms_wcNeedsSwap
= false;
1929 wxMBConv_iconv::wxMBConv_iconv(const char *name
)
1932 m_minMBCharWidth
= 0;
1934 // check for charset that represents wchar_t:
1935 if ( ms_wcCharsetName
.empty() )
1937 wxLogTrace(TRACE_STRCONV
, _T("Looking for wide char codeset:"));
1940 const wxChar
**names
= wxFontMapperBase::GetAllEncodingNames(WC_ENC
);
1941 #else // !wxUSE_FONTMAP
1942 static const wxChar
*names_static
[] =
1944 #if SIZEOF_WCHAR_T == 4
1946 #elif SIZEOF_WCHAR_T = 2
1951 const wxChar
**names
= names_static
;
1952 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
1954 for ( ; *names
&& ms_wcCharsetName
.empty(); ++names
)
1956 const wxString
nameCS(*names
);
1958 // first try charset with explicit bytesex info (e.g. "UCS-4LE"):
1959 wxString
nameXE(nameCS
);
1961 #ifdef WORDS_BIGENDIAN
1963 #else // little endian
1967 wxLogTrace(TRACE_STRCONV
, _T(" trying charset \"%s\""),
1970 m2w
= iconv_open(nameXE
.ToAscii(), name
);
1971 if ( m2w
== ICONV_T_INVALID
)
1973 // try charset w/o bytesex info (e.g. "UCS4")
1974 wxLogTrace(TRACE_STRCONV
, _T(" trying charset \"%s\""),
1976 m2w
= iconv_open(nameCS
.ToAscii(), name
);
1978 // and check for bytesex ourselves:
1979 if ( m2w
!= ICONV_T_INVALID
)
1981 char buf
[2], *bufPtr
;
1982 wchar_t wbuf
[2], *wbufPtr
;
1990 outsz
= SIZEOF_WCHAR_T
* 2;
1995 m2w
, ICONV_CHAR_CAST(&bufPtr
), &insz
,
1996 (char**)&wbufPtr
, &outsz
);
1998 if (ICONV_FAILED(res
, insz
))
2000 wxLogLastError(wxT("iconv"));
2001 wxLogError(_("Conversion to charset '%s' doesn't work."),
2004 else // ok, can convert to this encoding, remember it
2006 ms_wcCharsetName
= nameCS
;
2007 ms_wcNeedsSwap
= wbuf
[0] != (wchar_t)buf
[0];
2011 else // use charset not requiring byte swapping
2013 ms_wcCharsetName
= nameXE
;
2017 wxLogTrace(TRACE_STRCONV
,
2018 wxT("iconv wchar_t charset is \"%s\"%s"),
2019 ms_wcCharsetName
.empty() ? wxString("<none>")
2021 ms_wcNeedsSwap
? _T(" (needs swap)")
2024 else // we already have ms_wcCharsetName
2026 m2w
= iconv_open(ms_wcCharsetName
.ToAscii(), name
);
2029 if ( ms_wcCharsetName
.empty() )
2031 w2m
= ICONV_T_INVALID
;
2035 w2m
= iconv_open(name
, ms_wcCharsetName
.ToAscii());
2036 if ( w2m
== ICONV_T_INVALID
)
2038 wxLogTrace(TRACE_STRCONV
,
2039 wxT("\"%s\" -> \"%s\" works but not the converse!?"),
2040 ms_wcCharsetName
.c_str(), name
);
2045 wxMBConv_iconv::~wxMBConv_iconv()
2047 if ( m2w
!= ICONV_T_INVALID
)
2049 if ( w2m
!= ICONV_T_INVALID
)
2053 size_t wxMBConv_iconv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2055 // find the string length: notice that must be done differently for
2056 // NUL-terminated strings and UTF-16/32 which are terminated with 2/4 NULs
2058 const size_t nulLen
= GetMBNulLen();
2062 return wxCONV_FAILED
;
2065 inbuf
= strlen(psz
); // arguably more optimized than our version
2070 // for UTF-16/32 not only we need to have 2/4 consecutive NULs but
2071 // they also have to start at character boundary and not span two
2072 // adjacent characters
2074 for ( p
= psz
; NotAllNULs(p
, nulLen
); p
+= nulLen
)
2081 // NB: iconv() is MT-safe, but each thread must use its own iconv_t handle.
2082 // Unfortunately there are a couple of global wxCSConv objects such as
2083 // wxConvLocal that are used all over wx code, so we have to make sure
2084 // the handle is used by at most one thread at the time. Otherwise
2085 // only a few wx classes would be safe to use from non-main threads
2086 // as MB<->WC conversion would fail "randomly".
2087 wxMutexLocker
lock(wxConstCast(this, wxMBConv_iconv
)->m_iconvMutex
);
2088 #endif // wxUSE_THREADS
2090 size_t outbuf
= n
* SIZEOF_WCHAR_T
;
2092 // VS: Use these instead of psz, buf because iconv() modifies its arguments:
2093 wchar_t *bufPtr
= buf
;
2094 const char *pszPtr
= psz
;
2098 // have destination buffer, convert there
2100 ICONV_CHAR_CAST(&pszPtr
), &inbuf
,
2101 (char**)&bufPtr
, &outbuf
);
2102 res
= n
- (outbuf
/ SIZEOF_WCHAR_T
);
2106 // convert to native endianness
2107 for ( unsigned i
= 0; i
< res
; i
++ )
2108 buf
[n
] = WC_BSWAP(buf
[i
]);
2111 // NUL-terminate the string if there is any space left
2117 // no destination buffer... convert using temp buffer
2118 // to calculate destination buffer requirement
2125 outbuf
= 8 * SIZEOF_WCHAR_T
;
2128 ICONV_CHAR_CAST(&pszPtr
), &inbuf
,
2129 (char**)&bufPtr
, &outbuf
);
2131 res
+= 8 - (outbuf
/ SIZEOF_WCHAR_T
);
2133 while ((cres
== (size_t)-1) && (errno
== E2BIG
));
2136 if (ICONV_FAILED(cres
, inbuf
))
2138 //VS: it is ok if iconv fails, hence trace only
2139 wxLogTrace(TRACE_STRCONV
, wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
2140 return wxCONV_FAILED
;
2146 size_t wxMBConv_iconv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
2149 // NB: explained in MB2WC
2150 wxMutexLocker
lock(wxConstCast(this, wxMBConv_iconv
)->m_iconvMutex
);
2153 size_t inlen
= wxWcslen(psz
);
2154 size_t inbuf
= inlen
* SIZEOF_WCHAR_T
;
2158 wchar_t *tmpbuf
= 0;
2162 // need to copy to temp buffer to switch endianness
2163 // (doing WC_BSWAP twice on the original buffer won't help, as it
2164 // could be in read-only memory, or be accessed in some other thread)
2165 tmpbuf
= (wchar_t *)malloc(inbuf
+ SIZEOF_WCHAR_T
);
2166 for ( size_t i
= 0; i
< inlen
; i
++ )
2167 tmpbuf
[n
] = WC_BSWAP(psz
[i
]);
2169 tmpbuf
[inlen
] = L
'\0';
2175 // have destination buffer, convert there
2176 cres
= iconv( w2m
, ICONV_CHAR_CAST(&psz
), &inbuf
, &buf
, &outbuf
);
2180 // NB: iconv was given only wcslen(psz) characters on input, and so
2181 // it couldn't convert the trailing zero. Let's do it ourselves
2182 // if there's some room left for it in the output buffer.
2188 // no destination buffer: convert using temp buffer
2189 // to calculate destination buffer requirement
2197 cres
= iconv( w2m
, ICONV_CHAR_CAST(&psz
), &inbuf
, &buf
, &outbuf
);
2201 while ((cres
== (size_t)-1) && (errno
== E2BIG
));
2209 if (ICONV_FAILED(cres
, inbuf
))
2211 wxLogTrace(TRACE_STRCONV
, wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
2212 return wxCONV_FAILED
;
2218 size_t wxMBConv_iconv::GetMBNulLen() const
2220 if ( m_minMBCharWidth
== 0 )
2222 wxMBConv_iconv
* const self
= wxConstCast(this, wxMBConv_iconv
);
2225 // NB: explained in MB2WC
2226 wxMutexLocker
lock(self
->m_iconvMutex
);
2229 const wchar_t *wnul
= L
"";
2230 char buf
[8]; // should be enough for NUL in any encoding
2231 size_t inLen
= sizeof(wchar_t),
2232 outLen
= WXSIZEOF(buf
);
2233 char *inBuff
= (char *)wnul
;
2234 char *outBuff
= buf
;
2235 if ( iconv(w2m
, ICONV_CHAR_CAST(&inBuff
), &inLen
, &outBuff
, &outLen
) == (size_t)-1 )
2237 self
->m_minMBCharWidth
= (size_t)-1;
2241 self
->m_minMBCharWidth
= outBuff
- buf
;
2245 return m_minMBCharWidth
;
2248 #if wxUSE_UNICODE_UTF8
2249 bool wxMBConv_iconv::IsUTF8() const
2251 return wxStricmp(m_name
, "UTF-8") == 0 ||
2252 wxStricmp(m_name
, "UTF8") == 0;
2256 #endif // HAVE_ICONV
2259 // ============================================================================
2260 // Win32 conversion classes
2261 // ============================================================================
2263 #ifdef wxHAVE_WIN32_MB2WC
2267 extern WXDLLIMPEXP_BASE
long wxCharsetToCodepage(const char *charset
);
2268 extern WXDLLIMPEXP_BASE
long wxEncodingToCodepage(wxFontEncoding encoding
);
2271 class wxMBConv_win32
: public wxMBConv
2276 m_CodePage
= CP_ACP
;
2277 m_minMBCharWidth
= 0;
2280 wxMBConv_win32(const wxMBConv_win32
& conv
)
2283 m_CodePage
= conv
.m_CodePage
;
2284 m_minMBCharWidth
= conv
.m_minMBCharWidth
;
2288 wxMBConv_win32(const char* name
)
2290 m_CodePage
= wxCharsetToCodepage(name
);
2291 m_minMBCharWidth
= 0;
2294 wxMBConv_win32(wxFontEncoding encoding
)
2296 m_CodePage
= wxEncodingToCodepage(encoding
);
2297 m_minMBCharWidth
= 0;
2299 #endif // wxUSE_FONTMAP
2301 virtual size_t MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
2303 // note that we have to use MB_ERR_INVALID_CHARS flag as it without it
2304 // the behaviour is not compatible with the Unix version (using iconv)
2305 // and break the library itself, e.g. wxTextInputStream::NextChar()
2306 // wouldn't work if reading an incomplete MB char didn't result in an
2309 // Moreover, MB_ERR_INVALID_CHARS is only supported on Win 2K SP4 or
2310 // Win XP or newer and it is not supported for UTF-[78] so we always
2311 // use our own conversions in this case. See
2312 // http://blogs.msdn.com/michkap/archive/2005/04/19/409566.aspx
2313 // http://msdn.microsoft.com/library/en-us/intl/unicode_17si.asp
2314 if ( m_CodePage
== CP_UTF8
)
2316 return wxMBConvUTF8().MB2WC(buf
, psz
, n
);
2319 if ( m_CodePage
== CP_UTF7
)
2321 return wxMBConvUTF7().MB2WC(buf
, psz
, n
);
2325 if ( (m_CodePage
< 50000 && m_CodePage
!= CP_SYMBOL
) &&
2326 IsAtLeastWin2kSP4() )
2328 flags
= MB_ERR_INVALID_CHARS
;
2331 const size_t len
= ::MultiByteToWideChar
2333 m_CodePage
, // code page
2334 flags
, // flags: fall on error
2335 psz
, // input string
2336 -1, // its length (NUL-terminated)
2337 buf
, // output string
2338 buf
? n
: 0 // size of output buffer
2342 // function totally failed
2343 return wxCONV_FAILED
;
2346 // if we were really converting and didn't use MB_ERR_INVALID_CHARS,
2347 // check if we succeeded, by doing a double trip:
2348 if ( !flags
&& buf
)
2350 const size_t mbLen
= strlen(psz
);
2351 wxCharBuffer
mbBuf(mbLen
);
2352 if ( ::WideCharToMultiByte
2359 mbLen
+ 1, // size in bytes, not length
2363 strcmp(mbBuf
, psz
) != 0 )
2365 // we didn't obtain the same thing we started from, hence
2366 // the conversion was lossy and we consider that it failed
2367 return wxCONV_FAILED
;
2371 // note that it returns count of written chars for buf != NULL and size
2372 // of the needed buffer for buf == NULL so in either case the length of
2373 // the string (which never includes the terminating NUL) is one less
2377 virtual size_t WC2MB(char *buf
, const wchar_t *pwz
, size_t n
) const
2380 we have a problem here: by default, WideCharToMultiByte() may
2381 replace characters unrepresentable in the target code page with bad
2382 quality approximations such as turning "1/2" symbol (U+00BD) into
2383 "1" for the code pages which don't have it and we, obviously, want
2384 to avoid this at any price
2386 the trouble is that this function does it _silently_, i.e. it won't
2387 even tell us whether it did or not... Win98/2000 and higher provide
2388 WC_NO_BEST_FIT_CHARS but it doesn't work for the older systems and
2389 we have to resort to a round trip, i.e. check that converting back
2390 results in the same string -- this is, of course, expensive but
2391 otherwise we simply can't be sure to not garble the data.
2394 // determine if we can rely on WC_NO_BEST_FIT_CHARS: according to MSDN
2395 // it doesn't work with CJK encodings (which we test for rather roughly
2396 // here...) nor with UTF-7/8 nor, of course, with Windows versions not
2398 BOOL usedDef
wxDUMMY_INITIALIZE(false);
2401 if ( CanUseNoBestFit() && m_CodePage
< 50000 )
2403 // it's our lucky day
2404 flags
= WC_NO_BEST_FIT_CHARS
;
2405 pUsedDef
= &usedDef
;
2407 else // old system or unsupported encoding
2413 const size_t len
= ::WideCharToMultiByte
2415 m_CodePage
, // code page
2416 flags
, // either none or no best fit
2417 pwz
, // input string
2418 -1, // it is (wide) NUL-terminated
2419 buf
, // output buffer
2420 buf
? n
: 0, // and its size
2421 NULL
, // default "replacement" char
2422 pUsedDef
// [out] was it used?
2427 // function totally failed
2428 return wxCONV_FAILED
;
2431 // we did something, check if we really succeeded
2434 // check if the conversion failed, i.e. if any replacements
2437 return wxCONV_FAILED
;
2439 else // we must resort to double tripping...
2441 // first we need to ensure that we really have the MB data: this is
2442 // not the case if we're called with NULL buffer, in which case we
2443 // need to do the conversion yet again
2444 wxCharBuffer bufDef
;
2447 bufDef
= wxCharBuffer(len
);
2448 buf
= bufDef
.data();
2449 if ( !::WideCharToMultiByte(m_CodePage
, flags
, pwz
, -1,
2450 buf
, len
, NULL
, NULL
) )
2451 return wxCONV_FAILED
;
2454 wxWCharBuffer
wcBuf(n
);
2455 if ( MB2WC(wcBuf
.data(), buf
, n
) == wxCONV_FAILED
||
2456 wcscmp(wcBuf
, pwz
) != 0 )
2458 // we didn't obtain the same thing we started from, hence
2459 // the conversion was lossy and we consider that it failed
2460 return wxCONV_FAILED
;
2464 // see the comment above for the reason of "len - 1"
2468 virtual size_t GetMBNulLen() const
2470 if ( m_minMBCharWidth
== 0 )
2472 int len
= ::WideCharToMultiByte
2474 m_CodePage
, // code page
2476 L
"", // input string
2477 1, // translate just the NUL
2478 NULL
, // output buffer
2480 NULL
, // no replacement char
2481 NULL
// [out] don't care if it was used
2484 wxMBConv_win32
* const self
= wxConstCast(this, wxMBConv_win32
);
2488 wxLogDebug(_T("Unexpected NUL length %d"), len
);
2489 self
->m_minMBCharWidth
= (size_t)-1;
2493 self
->m_minMBCharWidth
= (size_t)-1;
2499 self
->m_minMBCharWidth
= len
;
2504 return m_minMBCharWidth
;
2507 virtual wxMBConv
*Clone() const { return new wxMBConv_win32(*this); }
2509 bool IsOk() const { return m_CodePage
!= -1; }
2512 static bool CanUseNoBestFit()
2514 static int s_isWin98Or2k
= -1;
2516 if ( s_isWin98Or2k
== -1 )
2519 switch ( wxGetOsVersion(&verMaj
, &verMin
) )
2521 case wxOS_WINDOWS_9X
:
2522 s_isWin98Or2k
= verMaj
>= 4 && verMin
>= 10;
2525 case wxOS_WINDOWS_NT
:
2526 s_isWin98Or2k
= verMaj
>= 5;
2530 // unknown: be conservative by default
2535 wxASSERT_MSG( s_isWin98Or2k
!= -1, _T("should be set above") );
2538 return s_isWin98Or2k
== 1;
2541 static bool IsAtLeastWin2kSP4()
2546 static int s_isAtLeastWin2kSP4
= -1;
2548 if ( s_isAtLeastWin2kSP4
== -1 )
2550 OSVERSIONINFOEX ver
;
2552 memset(&ver
, 0, sizeof(ver
));
2553 ver
.dwOSVersionInfoSize
= sizeof(ver
);
2554 GetVersionEx((OSVERSIONINFO
*)&ver
);
2556 s_isAtLeastWin2kSP4
=
2557 ((ver
.dwMajorVersion
> 5) || // Vista+
2558 (ver
.dwMajorVersion
== 5 && ver
.dwMinorVersion
> 0) || // XP/2003
2559 (ver
.dwMajorVersion
== 5 && ver
.dwMinorVersion
== 0 &&
2560 ver
.wServicePackMajor
>= 4)) // 2000 SP4+
2564 return s_isAtLeastWin2kSP4
== 1;
2569 // the code page we're working with
2572 // cached result of GetMBNulLen(), set to 0 initially meaning
2574 size_t m_minMBCharWidth
;
2577 #endif // wxHAVE_WIN32_MB2WC
2580 // ============================================================================
2581 // wxEncodingConverter based conversion classes
2582 // ============================================================================
2586 class wxMBConv_wxwin
: public wxMBConv
2591 // Refuse to use broken wxEncodingConverter code for Mac-specific encodings.
2592 // The wxMBConv_cf class does a better job.
2593 m_ok
= (m_enc
< wxFONTENCODING_MACMIN
|| m_enc
> wxFONTENCODING_MACMAX
) &&
2594 m2w
.Init(m_enc
, wxFONTENCODING_UNICODE
) &&
2595 w2m
.Init(wxFONTENCODING_UNICODE
, m_enc
);
2599 // temporarily just use wxEncodingConverter stuff,
2600 // so that it works while a better implementation is built
2601 wxMBConv_wxwin(const char* name
)
2604 m_enc
= wxFontMapperBase::Get()->CharsetToEncoding(name
, false);
2606 m_enc
= wxFONTENCODING_SYSTEM
;
2611 wxMBConv_wxwin(wxFontEncoding enc
)
2618 size_t MB2WC(wchar_t *buf
, const char *psz
, size_t WXUNUSED(n
)) const
2620 size_t inbuf
= strlen(psz
);
2623 if (!m2w
.Convert(psz
, buf
))
2624 return wxCONV_FAILED
;
2629 size_t WC2MB(char *buf
, const wchar_t *psz
, size_t WXUNUSED(n
)) const
2631 const size_t inbuf
= wxWcslen(psz
);
2634 if (!w2m
.Convert(psz
, buf
))
2635 return wxCONV_FAILED
;
2641 virtual size_t GetMBNulLen() const
2645 case wxFONTENCODING_UTF16BE
:
2646 case wxFONTENCODING_UTF16LE
:
2649 case wxFONTENCODING_UTF32BE
:
2650 case wxFONTENCODING_UTF32LE
:
2658 virtual wxMBConv
*Clone() const { return new wxMBConv_wxwin(m_enc
); }
2660 bool IsOk() const { return m_ok
; }
2663 wxFontEncoding m_enc
;
2664 wxEncodingConverter m2w
, w2m
;
2667 // were we initialized successfully?
2670 DECLARE_NO_COPY_CLASS(wxMBConv_wxwin
)
2673 // make the constructors available for unit testing
2674 WXDLLIMPEXP_BASE wxMBConv
* new_wxMBConv_wxwin( const char* name
)
2676 wxMBConv_wxwin
* result
= new wxMBConv_wxwin( name
);
2677 if ( !result
->IsOk() )
2686 #endif // wxUSE_FONTMAP
2688 // ============================================================================
2689 // wxCSConv implementation
2690 // ============================================================================
2692 void wxCSConv::Init()
2699 wxCSConv::wxCSConv(const wxString
& charset
)
2703 if ( !charset
.empty() )
2705 SetName(charset
.ToAscii());
2709 m_encoding
= wxFontMapperBase::GetEncodingFromName(charset
);
2711 m_encoding
= wxFONTENCODING_SYSTEM
;
2715 wxCSConv::wxCSConv(wxFontEncoding encoding
)
2717 if ( encoding
== wxFONTENCODING_MAX
|| encoding
== wxFONTENCODING_DEFAULT
)
2719 wxFAIL_MSG( _T("invalid encoding value in wxCSConv ctor") );
2721 encoding
= wxFONTENCODING_SYSTEM
;
2726 m_encoding
= encoding
;
2729 wxCSConv::~wxCSConv()
2734 wxCSConv::wxCSConv(const wxCSConv
& conv
)
2739 SetName(conv
.m_name
);
2740 m_encoding
= conv
.m_encoding
;
2743 wxCSConv
& wxCSConv::operator=(const wxCSConv
& conv
)
2747 SetName(conv
.m_name
);
2748 m_encoding
= conv
.m_encoding
;
2753 void wxCSConv::Clear()
2762 void wxCSConv::SetName(const char *charset
)
2766 m_name
= wxStrdup(charset
);
2773 WX_DECLARE_HASH_MAP( wxFontEncoding
, wxString
, wxIntegerHash
, wxIntegerEqual
,
2774 wxEncodingNameCache
);
2776 static wxEncodingNameCache gs_nameCache
;
2779 wxMBConv
*wxCSConv::DoCreate() const
2782 wxLogTrace(TRACE_STRCONV
,
2783 wxT("creating conversion for %s"),
2785 : (const char*)wxFontMapperBase::GetEncodingName(m_encoding
).mb_str()));
2786 #endif // wxUSE_FONTMAP
2788 // check for the special case of ASCII or ISO8859-1 charset: as we have
2789 // special knowledge of it anyhow, we don't need to create a special
2790 // conversion object
2791 if ( m_encoding
== wxFONTENCODING_ISO8859_1
||
2792 m_encoding
== wxFONTENCODING_DEFAULT
)
2794 // don't convert at all
2798 // we trust OS to do conversion better than we can so try external
2799 // conversion methods first
2801 // the full order is:
2802 // 1. OS conversion (iconv() under Unix or Win32 API)
2803 // 2. hard coded conversions for UTF
2804 // 3. wxEncodingConverter as fall back
2810 #endif // !wxUSE_FONTMAP
2813 wxFontEncoding
encoding(m_encoding
);
2818 wxMBConv_iconv
*conv
= new wxMBConv_iconv(m_name
);
2826 wxFontMapperBase::Get()->CharsetToEncoding(m_name
, false);
2827 #endif // wxUSE_FONTMAP
2831 const wxEncodingNameCache::iterator it
= gs_nameCache
.find(encoding
);
2832 if ( it
!= gs_nameCache
.end() )
2834 if ( it
->second
.empty() )
2837 wxMBConv_iconv
*conv
= new wxMBConv_iconv(it
->second
.ToAscii());
2844 const wxChar
** names
= wxFontMapperBase::GetAllEncodingNames(encoding
);
2845 // CS : in case this does not return valid names (eg for MacRoman)
2846 // encoding got a 'failure' entry in the cache all the same,
2847 // although it just has to be created using a different method, so
2848 // only store failed iconv creation attempts (or perhaps we
2849 // shoulnd't do this at all ?)
2850 if ( names
[0] != NULL
)
2852 for ( ; *names
; ++names
)
2854 // FIXME-UTF8: wxFontMapperBase::GetAllEncodingNames()
2855 // will need changes that will obsolete this
2856 wxString
name(*names
);
2857 wxMBConv_iconv
*conv
= new wxMBConv_iconv(name
.ToAscii());
2860 gs_nameCache
[encoding
] = *names
;
2867 gs_nameCache
[encoding
] = _T(""); // cache the failure
2870 #endif // wxUSE_FONTMAP
2872 #endif // HAVE_ICONV
2874 #ifdef wxHAVE_WIN32_MB2WC
2877 wxMBConv_win32
*conv
= m_name
? new wxMBConv_win32(m_name
)
2878 : new wxMBConv_win32(m_encoding
);
2887 #endif // wxHAVE_WIN32_MB2WC
2891 // leave UTF16 and UTF32 to the built-ins of wx
2892 if ( m_name
|| ( m_encoding
< wxFONTENCODING_UTF16BE
||
2893 ( m_encoding
>= wxFONTENCODING_MACMIN
&& m_encoding
<= wxFONTENCODING_MACMAX
) ) )
2896 wxMBConv_cf
*conv
= m_name
? new wxMBConv_cf(m_name
)
2897 : new wxMBConv_cf(m_encoding
);
2899 wxMBConv_cf
*conv
= new wxMBConv_cf(m_encoding
);
2908 #endif // __DARWIN__
2911 wxFontEncoding enc
= m_encoding
;
2913 if ( enc
== wxFONTENCODING_SYSTEM
&& m_name
)
2915 // use "false" to suppress interactive dialogs -- we can be called from
2916 // anywhere and popping up a dialog from here is the last thing we want to
2918 enc
= wxFontMapperBase::Get()->CharsetToEncoding(m_name
, false);
2920 #endif // wxUSE_FONTMAP
2924 case wxFONTENCODING_UTF7
:
2925 return new wxMBConvUTF7
;
2927 case wxFONTENCODING_UTF8
:
2928 return new wxMBConvUTF8
;
2930 case wxFONTENCODING_UTF16BE
:
2931 return new wxMBConvUTF16BE
;
2933 case wxFONTENCODING_UTF16LE
:
2934 return new wxMBConvUTF16LE
;
2936 case wxFONTENCODING_UTF32BE
:
2937 return new wxMBConvUTF32BE
;
2939 case wxFONTENCODING_UTF32LE
:
2940 return new wxMBConvUTF32LE
;
2943 // nothing to do but put here to suppress gcc warnings
2950 wxMBConv_wxwin
*conv
= m_name
? new wxMBConv_wxwin(m_name
)
2951 : new wxMBConv_wxwin(m_encoding
);
2957 #endif // wxUSE_FONTMAP
2959 // NB: This is a hack to prevent deadlock. What could otherwise happen
2960 // in Unicode build: wxConvLocal creation ends up being here
2961 // because of some failure and logs the error. But wxLog will try to
2962 // attach a timestamp, for which it will need wxConvLocal (to convert
2963 // time to char* and then wchar_t*), but that fails, tries to log the
2964 // error, but wxLog has an (already locked) critical section that
2965 // guards the static buffer.
2966 static bool alreadyLoggingError
= false;
2967 if (!alreadyLoggingError
)
2969 alreadyLoggingError
= true;
2970 wxLogError(_("Cannot convert from the charset '%s'!"),
2974 (const char*)wxFontMapperBase::GetEncodingDescription(m_encoding
).ToAscii()
2975 #else // !wxUSE_FONTMAP
2976 (const char*)wxString::Format(_("encoding %i"), m_encoding
).ToAscii()
2977 #endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
2980 alreadyLoggingError
= false;
2986 void wxCSConv::CreateConvIfNeeded() const
2990 wxCSConv
*self
= (wxCSConv
*)this; // const_cast
2992 // if we don't have neither the name nor the encoding, use the default
2993 // encoding for this system
2994 if ( !m_name
&& m_encoding
== wxFONTENCODING_SYSTEM
)
2997 self
->m_encoding
= wxLocale::GetSystemEncoding();
2999 // fallback to some reasonable default:
3000 self
->m_encoding
= wxFONTENCODING_ISO8859_1
;
3001 #endif // wxUSE_INTL
3004 self
->m_convReal
= DoCreate();
3005 self
->m_deferred
= false;
3009 bool wxCSConv::IsOk() const
3011 CreateConvIfNeeded();
3013 // special case: no convReal created for wxFONTENCODING_ISO8859_1
3014 if ( m_encoding
== wxFONTENCODING_ISO8859_1
)
3015 return true; // always ok as we do it ourselves
3017 // m_convReal->IsOk() is called at its own creation, so we know it must
3018 // be ok if m_convReal is non-NULL
3019 return m_convReal
!= NULL
;
3022 size_t wxCSConv::ToWChar(wchar_t *dst
, size_t dstLen
,
3023 const char *src
, size_t srcLen
) const
3025 CreateConvIfNeeded();
3028 return m_convReal
->ToWChar(dst
, dstLen
, src
, srcLen
);
3031 return wxMBConv::ToWChar(dst
, dstLen
, src
, srcLen
);
3034 size_t wxCSConv::FromWChar(char *dst
, size_t dstLen
,
3035 const wchar_t *src
, size_t srcLen
) const
3037 CreateConvIfNeeded();
3040 return m_convReal
->FromWChar(dst
, dstLen
, src
, srcLen
);
3043 return wxMBConv::FromWChar(dst
, dstLen
, src
, srcLen
);
3046 size_t wxCSConv::MB2WC(wchar_t *buf
, const char *psz
, size_t n
) const
3048 CreateConvIfNeeded();
3051 return m_convReal
->MB2WC(buf
, psz
, n
);
3054 size_t len
= strlen(psz
);
3058 for (size_t c
= 0; c
<= len
; c
++)
3059 buf
[c
] = (unsigned char)(psz
[c
]);
3065 size_t wxCSConv::WC2MB(char *buf
, const wchar_t *psz
, size_t n
) const
3067 CreateConvIfNeeded();
3070 return m_convReal
->WC2MB(buf
, psz
, n
);
3073 const size_t len
= wxWcslen(psz
);
3076 for (size_t c
= 0; c
<= len
; c
++)
3079 return wxCONV_FAILED
;
3081 buf
[c
] = (char)psz
[c
];
3086 for (size_t c
= 0; c
<= len
; c
++)
3089 return wxCONV_FAILED
;
3096 size_t wxCSConv::GetMBNulLen() const
3098 CreateConvIfNeeded();
3102 return m_convReal
->GetMBNulLen();
3105 // otherwise, we are ISO-8859-1
3109 #if wxUSE_UNICODE_UTF8
3110 bool wxCSConv::IsUTF8() const
3112 CreateConvIfNeeded();
3116 return m_convReal
->IsUTF8();
3119 // otherwise, we are ISO-8859-1
3127 wxWCharBuffer
wxSafeConvertMB2WX(const char *s
)
3130 return wxWCharBuffer();
3132 wxWCharBuffer
wbuf(wxConvLibc
.cMB2WX(s
));
3134 wbuf
= wxMBConvUTF8().cMB2WX(s
);
3136 wbuf
= wxConvISO8859_1
.cMB2WX(s
);
3141 wxCharBuffer
wxSafeConvertWX2MB(const wchar_t *ws
)
3144 return wxCharBuffer();
3146 wxCharBuffer
buf(wxConvLibc
.cWX2MB(ws
));
3148 buf
= wxMBConvUTF8(wxMBConvUTF8::MAP_INVALID_UTF8_TO_OCTAL
).cWX2MB(ws
);
3153 #endif // wxUSE_UNICODE
3155 // ----------------------------------------------------------------------------
3157 // ----------------------------------------------------------------------------
3159 // NB: The reason why we create converted objects in this convoluted way,
3160 // using a factory function instead of global variable, is that they
3161 // may be used at static initialization time (some of them are used by
3162 // wxString ctors and there may be a global wxString object). In other
3163 // words, possibly _before_ the converter global object would be
3170 #undef wxConvISO8859_1
3172 #define WX_DEFINE_GLOBAL_CONV2(klass, impl_klass, name, ctor_args) \
3173 WXDLLIMPEXP_DATA_BASE(klass*) name##Ptr = NULL; \
3174 WXDLLIMPEXP_BASE klass* wxGet_##name##Ptr() \
3176 static impl_klass name##Obj ctor_args; \
3177 return &name##Obj; \
3179 /* this ensures that all global converter objects are created */ \
3180 /* by the time static initialization is done, i.e. before any */ \
3181 /* thread is launched: */ \
3182 static klass* gs_##name##instance = wxGet_##name##Ptr()
3184 #define WX_DEFINE_GLOBAL_CONV(klass, name, ctor_args) \
3185 WX_DEFINE_GLOBAL_CONV2(klass, klass, name, ctor_args)
3188 WX_DEFINE_GLOBAL_CONV2(wxMBConv
, wxMBConv_win32
, wxConvLibc
, wxEMPTY_PARAMETER_VALUE
);
3190 WX_DEFINE_GLOBAL_CONV2(wxMBConv
, wxMBConvLibc
, wxConvLibc
, wxEMPTY_PARAMETER_VALUE
);
3193 // NB: we can't use wxEMPTY_PARAMETER_VALUE as final argument here because it's
3194 // passed to WX_DEFINE_GLOBAL_CONV2 after a macro expansion and so still
3195 // provokes an error message about "not enough macro parameters"; and we
3196 // can't use "()" here as the name##Obj declaration would be parsed as a
3197 // function declaration then, so use a semicolon and live with an extra
3198 // empty statement (and hope that no compilers warns about this)
3199 WX_DEFINE_GLOBAL_CONV(wxMBConvStrictUTF8
, wxConvUTF8
, ;);
3200 WX_DEFINE_GLOBAL_CONV(wxMBConvUTF7
, wxConvUTF7
, ;);
3202 WX_DEFINE_GLOBAL_CONV(wxCSConv
, wxConvLocal
, (wxFONTENCODING_SYSTEM
));
3203 WX_DEFINE_GLOBAL_CONV(wxCSConv
, wxConvISO8859_1
, (wxFONTENCODING_ISO8859_1
));
3205 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvCurrent
= wxGet_wxConvLibcPtr();
3206 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvUI
= wxGet_wxConvLocalPtr();
3209 // The xnu kernel always communicates file paths in decomposed UTF-8.
3210 // WARNING: Are we sure that CFString's conversion will cause decomposition?
3211 static wxMBConv_cf
wxConvMacUTF8DObj(wxFONTENCODING_UTF8
);
3214 WXDLLIMPEXP_DATA_BASE(wxMBConv
*) wxConvFileName
=
3217 #else // !__DARWIN__
3218 wxGet_wxConvLibcPtr();
3219 #endif // __DARWIN__/!__DARWIN__
3221 #else // !wxUSE_WCHAR_T
3223 // FIXME-UTF8: remove this, wxUSE_WCHAR_T is required now
3224 // stand-ins in absence of wchar_t
3225 WXDLLIMPEXP_DATA_BASE(wxMBConv
) wxConvLibc
,
3230 #endif // wxUSE_WCHAR_T/!wxUSE_WCHAR_T