]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/common/strconv.cpp
better attempts to try .utf-8 suffix
[wxWidgets.git] / src / common / strconv.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: strconv.cpp
3// Purpose: Unicode conversion classes
4// Author: Ove Kaaven, Robert Roebling, Vadim Zeitlin, Vaclav Slavik
5// Modified by:
6// Created: 29/01/98
7// RCS-ID: $Id$
8// Copyright: (c) 1999 Ove Kaaven, Robert Roebling, Vadim Zeitlin, Vaclav Slavik
9// Licence: wxWindows licence
10/////////////////////////////////////////////////////////////////////////////
11
12// ============================================================================
13// declarations
14// ============================================================================
15
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
19
20#ifdef __GNUG__
21 #pragma implementation "strconv.h"
22#endif
23
24// For compilers that support precompilation, includes "wx.h".
25#include "wx/wxprec.h"
26
27#ifdef __BORLANDC__
28 #pragma hdrstop
29#endif
30
31#ifndef WX_PRECOMP
32 #include "wx/intl.h"
33 #include "wx/log.h"
34#endif // WX_PRECOMP
35
36#ifdef __WXMSW__
37 #include "wx/msw/private.h"
38#endif
39
40#ifndef __WXWINCE__
41#include <errno.h>
42#endif
43
44#include <ctype.h>
45#include <string.h>
46#include <stdlib.h>
47
48#include "wx/module.h"
49#include "wx/strconv.h"
50
51// ----------------------------------------------------------------------------
52// globals
53// ----------------------------------------------------------------------------
54
55#if wxUSE_WCHAR_T
56 WXDLLIMPEXP_DATA_BASE(wxMBConv) wxConvLibc;
57 WXDLLIMPEXP_DATA_BASE(wxCSConv) wxConvLocal((const wxChar *)NULL);
58 WXDLLIMPEXP_DATA_BASE(wxCSConv) wxConvISO8859_1(_T("iso-8859-1"));
59#else
60 // stand-ins in absence of wchar_t
61 WXDLLIMPEXP_DATA_BASE(wxMBConv) wxConvLibc,
62 wxConvFile,
63 wxConvISO8859_1,
64 wxConvLocal,
65 wxConvUTF8;
66#endif // wxUSE_WCHAR_T
67
68WXDLLIMPEXP_DATA_BASE(wxMBConv *) wxConvCurrent = &wxConvLibc;
69
70class wxStrConvModule: public wxModule
71{
72public:
73 wxStrConvModule() : wxModule() { }
74 virtual bool OnInit() { return TRUE; }
75 virtual void OnExit()
76 {
77#if wxUSE_WCHAR_T
78 wxConvLocal.Clear();
79 wxConvISO8859_1.Clear();
80#endif
81 }
82
83 DECLARE_DYNAMIC_CLASS(wxStrConvModule)
84};
85
86IMPLEMENT_DYNAMIC_CLASS(wxStrConvModule, wxModule)
87
88
89// ----------------------------------------------------------------------------
90// headers
91// ----------------------------------------------------------------------------
92
93#if wxUSE_WCHAR_T
94
95#ifdef __SALFORDC__
96 #include <clib.h>
97#endif
98
99#ifdef HAVE_ICONV
100 #include <iconv.h>
101#endif
102
103#include "wx/encconv.h"
104#include "wx/fontmap.h"
105
106// ----------------------------------------------------------------------------
107// macros
108// ----------------------------------------------------------------------------
109
110#define BSWAP_UCS4(str, len) { unsigned _c; for (_c=0; _c<len; _c++) str[_c]=wxUINT32_SWAP_ALWAYS(str[_c]); }
111#define BSWAP_UTF16(str, len) { unsigned _c; for (_c=0; _c<len; _c++) str[_c]=wxUINT16_SWAP_ALWAYS(str[_c]); }
112
113// under Unix SIZEOF_WCHAR_T is defined by configure, but under other platforms
114// it might be not defined - assume the most common value
115#ifndef SIZEOF_WCHAR_T
116 #define SIZEOF_WCHAR_T 2
117#endif // !defined(SIZEOF_WCHAR_T)
118
119#if SIZEOF_WCHAR_T == 4
120 #define WC_NAME "UCS4"
121 #define WC_BSWAP BSWAP_UCS4
122 #ifdef WORDS_BIGENDIAN
123 #define WC_NAME_BEST "UCS-4BE"
124 #else
125 #define WC_NAME_BEST "UCS-4LE"
126 #endif
127#elif SIZEOF_WCHAR_T == 2
128 #define WC_NAME "UTF16"
129 #define WC_BSWAP BSWAP_UTF16
130 #define WC_UTF16
131 #ifdef WORDS_BIGENDIAN
132 #define WC_NAME_BEST "UTF-16BE"
133 #else
134 #define WC_NAME_BEST "UTF-16LE"
135 #endif
136#else // sizeof(wchar_t) != 2 nor 4
137 // I don't know what to do about this
138 #error "Weird sizeof(wchar_t): please report your platform details to wx-users mailing list"
139#endif
140
141// ============================================================================
142// implementation
143// ============================================================================
144
145// ----------------------------------------------------------------------------
146// UTF-16 en/decoding
147// ----------------------------------------------------------------------------
148
149#ifdef WC_UTF16
150
151static size_t encode_utf16(wxUint32 input, wchar_t *output)
152{
153 if (input<=0xffff)
154 {
155 if (output) *output++ = (wchar_t) input;
156 return 1;
157 }
158 else if (input>=0x110000)
159 {
160 return (size_t)-1;
161 }
162 else
163 {
164 if (output)
165 {
166 *output++ = (wchar_t) ((input >> 10)+0xd7c0);
167 *output++ = (wchar_t) ((input&0x3ff)+0xdc00);
168 }
169 return 2;
170 }
171}
172
173static size_t decode_utf16(const wchar_t* input, wxUint32& output)
174{
175 if ((*input<0xd800) || (*input>0xdfff))
176 {
177 output = *input;
178 return 1;
179 }
180 else if ((input[1]<0xdc00) || (input[1]>=0xdfff))
181 {
182 output = *input;
183 return (size_t)-1;
184 }
185 else
186 {
187 output = ((input[0] - 0xd7c0) << 10) + (input[1] - 0xdc00);
188 return 2;
189 }
190}
191
192#endif // WC_UTF16
193
194// ----------------------------------------------------------------------------
195// wxMBConv
196// ----------------------------------------------------------------------------
197
198#define IGNORE_LIBC 0
199
200wxMBConv::~wxMBConv()
201{
202 // nothing to do here
203}
204
205size_t wxMBConv::MB2WC(wchar_t *buf, const char *psz, size_t n) const
206{
207#if IGNORE_LIBC
208 if (buf)
209 {
210 for (size_t i = 0; i < strlen( psz )+1; i++)
211 buf[i] = (wchar_t) psz[i];
212 return strlen( psz );
213 }
214 else
215 {
216 return strlen( psz );
217 }
218#else
219 return wxMB2WC(buf, psz, n);
220#endif
221}
222
223size_t wxMBConv::WC2MB(char *buf, const wchar_t *psz, size_t n) const
224{
225#if IGNORE_LIBC
226 if (buf)
227 {
228 for (size_t i = 0; i < wxStrlen( psz )+1; i++)
229 buf[i] = (char) psz[i];
230 return wxStrlen( psz );
231 }
232 else
233 {
234 return wxStrlen( psz );
235 }
236#else
237 return wxWC2MB(buf, psz, n);
238#endif
239}
240
241const wxWCharBuffer wxMBConv::cMB2WC(const char *psz) const
242{
243 if ( psz )
244 {
245 // calculate the length of the buffer needed first
246 size_t nLen = MB2WC(NULL, psz, 0);
247 if ( nLen != (size_t)-1 )
248 {
249 // now do the actual conversion
250 wxWCharBuffer buf(nLen);
251 MB2WC(buf.data(), psz, nLen + 1); // with the trailing NUL
252
253 return buf;
254 }
255 }
256
257 wxWCharBuffer buf((wchar_t *)NULL);
258
259 return buf;
260}
261
262const wxCharBuffer wxMBConv::cWC2MB(const wchar_t *pwz) const
263{
264 if ( pwz )
265 {
266 size_t nLen = WC2MB(NULL, pwz, 0);
267 if ( nLen != (size_t)-1 )
268 {
269 wxCharBuffer buf(nLen);
270 WC2MB(buf.data(), pwz, nLen + 1);
271
272 return buf;
273 }
274 }
275
276 wxCharBuffer buf((char *)NULL);
277
278 return buf;
279}
280
281// ----------------------------------------------------------------------------
282// UTF-7
283// ----------------------------------------------------------------------------
284
285WXDLLIMPEXP_DATA_BASE(wxMBConvUTF7) wxConvUTF7;
286
287#if 0
288static char utf7_setD[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
289 "abcdefghijklmnopqrstuvwxyz"
290 "0123456789'(),-./:?";
291static char utf7_setO[]="!\"#$%&*;<=>@[]^_`{|}";
292static char utf7_setB[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
293 "abcdefghijklmnopqrstuvwxyz"
294 "0123456789+/";
295#endif
296
297// TODO: write actual implementations of UTF-7 here
298size_t wxMBConvUTF7::MB2WC(wchar_t * WXUNUSED(buf),
299 const char * WXUNUSED(psz),
300 size_t WXUNUSED(n)) const
301{
302 return 0;
303}
304
305size_t wxMBConvUTF7::WC2MB(char * WXUNUSED(buf),
306 const wchar_t * WXUNUSED(psz),
307 size_t WXUNUSED(n)) const
308{
309 return 0;
310}
311
312// ----------------------------------------------------------------------------
313// UTF-8
314// ----------------------------------------------------------------------------
315
316WXDLLIMPEXP_DATA_BASE(wxMBConvUTF8) wxConvUTF8;
317
318static wxUint32 utf8_max[]=
319 { 0x7f, 0x7ff, 0xffff, 0x1fffff, 0x3ffffff, 0x7fffffff, 0xffffffff };
320
321size_t wxMBConvUTF8::MB2WC(wchar_t *buf, const char *psz, size_t n) const
322{
323 size_t len = 0;
324
325 while (*psz && ((!buf) || (len < n)))
326 {
327 unsigned char cc = *psz++, fc = cc;
328 unsigned cnt;
329 for (cnt = 0; fc & 0x80; cnt++)
330 fc <<= 1;
331 if (!cnt)
332 {
333 // plain ASCII char
334 if (buf)
335 *buf++ = cc;
336 len++;
337 }
338 else
339 {
340 cnt--;
341 if (!cnt)
342 {
343 // invalid UTF-8 sequence
344 return (size_t)-1;
345 }
346 else
347 {
348 unsigned ocnt = cnt - 1;
349 wxUint32 res = cc & (0x3f >> cnt);
350 while (cnt--)
351 {
352 cc = *psz++;
353 if ((cc & 0xC0) != 0x80)
354 {
355 // invalid UTF-8 sequence
356 return (size_t)-1;
357 }
358 res = (res << 6) | (cc & 0x3f);
359 }
360 if (res <= utf8_max[ocnt])
361 {
362 // illegal UTF-8 encoding
363 return (size_t)-1;
364 }
365#ifdef WC_UTF16
366 size_t pa = encode_utf16(res, buf);
367 if (pa == (size_t)-1)
368 return (size_t)-1;
369 if (buf)
370 buf += pa;
371 len += pa;
372#else // !WC_UTF16
373 if (buf)
374 *buf++ = res;
375 len++;
376#endif // WC_UTF16/!WC_UTF16
377 }
378 }
379 }
380 if (buf && (len < n))
381 *buf = 0;
382 return len;
383}
384
385size_t wxMBConvUTF8::WC2MB(char *buf, const wchar_t *psz, size_t n) const
386{
387 size_t len = 0;
388
389 while (*psz && ((!buf) || (len < n)))
390 {
391 wxUint32 cc;
392#ifdef WC_UTF16
393 size_t pa = decode_utf16(psz, cc);
394 psz += (pa == (size_t)-1) ? 1 : pa;
395#else
396 cc=(*psz++) & 0x7fffffff;
397#endif
398 unsigned cnt;
399 for (cnt = 0; cc > utf8_max[cnt]; cnt++) {}
400 if (!cnt)
401 {
402 // plain ASCII char
403 if (buf)
404 *buf++ = (char) cc;
405 len++;
406 }
407
408 else
409 {
410 len += cnt + 1;
411 if (buf)
412 {
413 *buf++ = (char) ((-128 >> cnt) | ((cc >> (cnt * 6)) & (0x3f >> cnt)));
414 while (cnt--)
415 *buf++ = (char) (0x80 | ((cc >> (cnt * 6)) & 0x3f));
416 }
417 }
418 }
419
420 if (buf && (len<n)) *buf = 0;
421
422 return len;
423}
424
425// ============================================================================
426// wxCharacterSet and derived classes
427// ============================================================================
428
429// ----------------------------------------------------------------------------
430// wxCharacterSet is the ABC for the classes below
431// ----------------------------------------------------------------------------
432
433class wxCharacterSet
434{
435public:
436 wxCharacterSet(const wxChar*name) : cname(name) {}
437 virtual ~wxCharacterSet() {}
438 virtual size_t MB2WC(wchar_t *buf, const char *psz, size_t n) = 0;
439 virtual size_t WC2MB(char *buf, const wchar_t *psz, size_t n) = 0;
440 virtual bool usable() const = 0;
441public:
442 const wxChar*cname;
443};
444
445// ----------------------------------------------------------------------------
446// ID_CharSet: implementation of wxCharacterSet using an existing wxMBConv
447// ----------------------------------------------------------------------------
448
449class ID_CharSet : public wxCharacterSet
450{
451public:
452 ID_CharSet(const wxChar *name, wxMBConv *cnv)
453 : wxCharacterSet(name), work(cnv) {}
454
455 size_t MB2WC(wchar_t *buf, const char *psz, size_t n)
456 { return work ? work->MB2WC(buf,psz,n) : (size_t)-1; }
457
458 size_t WC2MB(char *buf, const wchar_t *psz, size_t n)
459 { return work ? work->WC2MB(buf,psz,n) : (size_t)-1; }
460
461 bool usable() const
462 { return work!=NULL; }
463public:
464 wxMBConv*work;
465};
466
467
468// ============================================================================
469// The classes doing conversion using the iconv_xxx() functions
470// ============================================================================
471
472#ifdef HAVE_ICONV
473
474// VS: glibc 2.1.3 is broken in that iconv() conversion to/from UCS4 fails with E2BIG
475// if output buffer is _exactly_ as big as needed. Such case is (unless there's
476// yet another bug in glibc) the only case when iconv() returns with (size_t)-1
477// (which means error) and says there are 0 bytes left in the input buffer --
478// when _real_ error occurs, bytes-left-in-input buffer is non-zero. Hence,
479// this alternative test for iconv() failure.
480// [This bug does not appear in glibc 2.2.]
481#if defined(__GLIBC__) && __GLIBC__ == 2 && __GLIBC_MINOR__ <= 1
482#define ICONV_FAILED(cres, bufLeft) ((cres == (size_t)-1) && \
483 (errno != E2BIG || bufLeft != 0))
484#else
485#define ICONV_FAILED(cres, bufLeft) (cres == (size_t)-1)
486#endif
487
488#define ICONV_CHAR_CAST(x) ((ICONV_CONST char **)(x))
489
490// ----------------------------------------------------------------------------
491// IC_CharSet: encapsulates an iconv character set
492// ----------------------------------------------------------------------------
493
494class IC_CharSet : public wxCharacterSet
495{
496public:
497 IC_CharSet(const wxChar *name);
498 virtual ~IC_CharSet();
499
500 virtual size_t MB2WC(wchar_t *buf, const char *psz, size_t n);
501 virtual size_t WC2MB(char *buf, const wchar_t *psz, size_t n);
502
503 bool usable() const
504 { return (m2w != (iconv_t)-1) && (w2m != (iconv_t)-1); }
505
506protected:
507 // the iconv handlers used to translate from multibyte to wide char and in
508 // the other direction
509 iconv_t m2w,
510 w2m;
511
512private:
513 // the name (for iconv_open()) of a wide char charset - if none is
514 // available on this machine, it will remain NULL
515 static const char *ms_wcCharsetName;
516
517 // true if the wide char encoding we use (i.e. ms_wcCharsetName) has
518 // different endian-ness than the native one
519 static bool ms_wcNeedsSwap;
520};
521
522const char *IC_CharSet::ms_wcCharsetName = NULL;
523bool IC_CharSet::ms_wcNeedsSwap = FALSE;
524
525IC_CharSet::IC_CharSet(const wxChar *name)
526 : wxCharacterSet(name)
527{
528 // Do it the hard way
529 char cname[100];
530 for (size_t i = 0; i < wxStrlen(name)+1; i++)
531 cname[i] = (char) name[i];
532
533 // check for charset that represents wchar_t:
534 if (ms_wcCharsetName == NULL)
535 {
536 ms_wcNeedsSwap = FALSE;
537
538 // try charset with explicit bytesex info (e.g. "UCS-4LE"):
539 ms_wcCharsetName = WC_NAME_BEST;
540 m2w = iconv_open(ms_wcCharsetName, cname);
541
542 if (m2w == (iconv_t)-1)
543 {
544 // try charset w/o bytesex info (e.g. "UCS4")
545 // and check for bytesex ourselves:
546 ms_wcCharsetName = WC_NAME;
547 m2w = iconv_open(ms_wcCharsetName, cname);
548
549 // last bet, try if it knows WCHAR_T pseudo-charset
550 if (m2w == (iconv_t)-1)
551 {
552 ms_wcCharsetName = "WCHAR_T";
553 m2w = iconv_open(ms_wcCharsetName, cname);
554 }
555
556 if (m2w != (iconv_t)-1)
557 {
558 char buf[2], *bufPtr;
559 wchar_t wbuf[2], *wbufPtr;
560 size_t insz, outsz;
561 size_t res;
562
563 buf[0] = 'A';
564 buf[1] = 0;
565 wbuf[0] = 0;
566 insz = 2;
567 outsz = SIZEOF_WCHAR_T * 2;
568 wbufPtr = wbuf;
569 bufPtr = buf;
570
571 res = iconv(m2w, ICONV_CHAR_CAST(&bufPtr), &insz,
572 (char**)&wbufPtr, &outsz);
573
574 if (ICONV_FAILED(res, insz))
575 {
576 ms_wcCharsetName = NULL;
577 wxLogLastError(wxT("iconv"));
578 wxLogError(_("Conversion to charset '%s' doesn't work."), name);
579 }
580 else
581 {
582 ms_wcNeedsSwap = wbuf[0] != (wchar_t)buf[0];
583 }
584 }
585 else
586 {
587 ms_wcCharsetName = NULL;
588
589 // VS: we must not output an error here, since wxWindows will safely
590 // fall back to using wxEncodingConverter.
591 wxLogTrace(wxT("strconv"), wxT("Impossible to convert to/from charset '%s' with iconv, falling back to wxEncodingConverter."), name);
592 //wxLogError(
593 }
594 }
595 wxLogTrace(wxT("strconv"), wxT("wchar_t charset is '%s', needs swap: %i"), ms_wcCharsetName, ms_wcNeedsSwap);
596 }
597 else // we already have ms_wcCharsetName
598 {
599 m2w = iconv_open(ms_wcCharsetName, cname);
600 }
601
602 // NB: don't ever pass NULL to iconv_open(), it may crash!
603 if ( ms_wcCharsetName )
604 {
605 w2m = iconv_open( cname, ms_wcCharsetName);
606 }
607 else
608 {
609 w2m = (iconv_t)-1;
610 }
611}
612
613IC_CharSet::~IC_CharSet()
614{
615 if ( m2w != (iconv_t)-1 )
616 iconv_close(m2w);
617 if ( w2m != (iconv_t)-1 )
618 iconv_close(w2m);
619}
620
621size_t IC_CharSet::MB2WC(wchar_t *buf, const char *psz, size_t n)
622{
623 size_t inbuf = strlen(psz);
624 size_t outbuf = n * SIZEOF_WCHAR_T;
625 size_t res, cres;
626 // VS: Use these instead of psz, buf because iconv() modifies its arguments:
627 wchar_t *bufPtr = buf;
628 const char *pszPtr = psz;
629
630 if (buf)
631 {
632 // have destination buffer, convert there
633 cres = iconv(m2w,
634 ICONV_CHAR_CAST(&pszPtr), &inbuf,
635 (char**)&bufPtr, &outbuf);
636 res = n - (outbuf / SIZEOF_WCHAR_T);
637
638 if (ms_wcNeedsSwap)
639 {
640 // convert to native endianness
641 WC_BSWAP(buf /* _not_ bufPtr */, res)
642 }
643
644 // NB: iconv was given only strlen(psz) characters on input, and so
645 // it couldn't convert the trailing zero. Let's do it ourselves
646 // if there's some room left for it in the output buffer.
647 if (res < n)
648 buf[res] = 0;
649 }
650 else
651 {
652 // no destination buffer... convert using temp buffer
653 // to calculate destination buffer requirement
654 wchar_t tbuf[8];
655 res = 0;
656 do {
657 bufPtr = tbuf;
658 outbuf = 8*SIZEOF_WCHAR_T;
659
660 cres = iconv(m2w,
661 ICONV_CHAR_CAST(&pszPtr), &inbuf,
662 (char**)&bufPtr, &outbuf );
663
664 res += 8-(outbuf/SIZEOF_WCHAR_T);
665 } while ((cres==(size_t)-1) && (errno==E2BIG));
666 }
667
668 if (ICONV_FAILED(cres, inbuf))
669 {
670 //VS: it is ok if iconv fails, hence trace only
671 wxLogTrace(wxT("strconv"), wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
672 return (size_t)-1;
673 }
674
675 return res;
676}
677
678size_t IC_CharSet::WC2MB(char *buf, const wchar_t *psz, size_t n)
679{
680 size_t inbuf = wxWcslen(psz) * SIZEOF_WCHAR_T;
681 size_t outbuf = n;
682 size_t res, cres;
683
684 wchar_t *tmpbuf = 0;
685
686 if (ms_wcNeedsSwap)
687 {
688 // need to copy to temp buffer to switch endianness
689 // this absolutely doesn't rock!
690 // (no, doing WC_BSWAP twice on the original buffer won't help, as it
691 // could be in read-only memory, or be accessed in some other thread)
692 tmpbuf=(wchar_t*)malloc((inbuf+1)*SIZEOF_WCHAR_T);
693 memcpy(tmpbuf,psz,(inbuf+1)*SIZEOF_WCHAR_T);
694 WC_BSWAP(tmpbuf, inbuf)
695 psz=tmpbuf;
696 }
697
698 if (buf)
699 {
700 // have destination buffer, convert there
701 cres = iconv( w2m, ICONV_CHAR_CAST(&psz), &inbuf, &buf, &outbuf );
702
703 res = n-outbuf;
704
705 // NB: iconv was given only wcslen(psz) characters on input, and so
706 // it couldn't convert the trailing zero. Let's do it ourselves
707 // if there's some room left for it in the output buffer.
708 if (res < n)
709 buf[0] = 0;
710 }
711 else
712 {
713 // no destination buffer... convert using temp buffer
714 // to calculate destination buffer requirement
715 char tbuf[16];
716 res = 0;
717 do {
718 buf = tbuf; outbuf = 16;
719
720 cres = iconv( w2m, ICONV_CHAR_CAST(&psz), &inbuf, &buf, &outbuf );
721
722 res += 16 - outbuf;
723 } while ((cres==(size_t)-1) && (errno==E2BIG));
724 }
725
726 if (ms_wcNeedsSwap)
727 {
728 free(tmpbuf);
729 }
730
731 if (ICONV_FAILED(cres, inbuf))
732 {
733 //VS: it is ok if iconv fails, hence trace only
734 wxLogTrace(wxT("strconv"), wxT("iconv failed: %s"), wxSysErrorMsg(wxSysErrorCode()));
735 return (size_t)-1;
736 }
737
738 return res;
739}
740
741#endif // HAVE_ICONV
742
743// ============================================================================
744// Win32 conversion classes
745// ============================================================================
746
747#if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXUNIVERSAL__)
748
749extern long wxCharsetToCodepage(const wxChar *charset); // from utils.cpp
750
751class CP_CharSet : public wxCharacterSet
752{
753public:
754 CP_CharSet(const wxChar* name)
755 : wxCharacterSet(name)
756 {
757 m_CodePage = wxCharsetToCodepage(name);
758 }
759
760 size_t MB2WC(wchar_t *buf, const char *psz, size_t n)
761 {
762 const size_t len = ::MultiByteToWideChar
763 (
764 m_CodePage, // code page
765 0, // flags (none)
766 psz, // input string
767 -1, // its length (NUL-terminated)
768 buf, // output string
769 buf ? n : 0 // size of output buffer
770 );
771
772 // note that it returns # of written chars for buf != NULL and *size*
773 // of the needed buffer for buf == NULL
774 return len ? (buf ? len : len - 1) : (size_t)-1;
775 }
776
777 size_t WC2MB(char *buf, const wchar_t *psz, size_t n)
778 {
779 const size_t len = ::WideCharToMultiByte
780 (
781 m_CodePage, // code page
782 0, // flags (none)
783 psz, // input string
784 -1, // it is (wide) NUL-terminated
785 buf, // output buffer
786 buf ? n : 0, // and its size
787 NULL, // default "replacement" char
788 NULL // [out] was it used?
789 );
790
791 // see the comment above!
792 return len ? (buf ? len : len - 1) : (size_t)-1;
793 }
794
795 bool usable() const
796 { return m_CodePage != -1; }
797
798public:
799 long m_CodePage;
800};
801#endif // defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXUNIVERSAL__)
802
803// ============================================================================
804// wxEncodingConverter based conversion classes
805// ============================================================================
806
807#if wxUSE_FONTMAP
808
809class EC_CharSet : public wxCharacterSet
810{
811public:
812 // temporarily just use wxEncodingConverter stuff,
813 // so that it works while a better implementation is built
814 EC_CharSet(const wxChar* name) : wxCharacterSet(name),
815 enc(wxFONTENCODING_SYSTEM)
816 {
817 if (name)
818 enc = wxFontMapper::Get()->CharsetToEncoding(name, FALSE);
819
820 m_ok = m2w.Init(enc, wxFONTENCODING_UNICODE) &&
821 w2m.Init(wxFONTENCODING_UNICODE, enc);
822 }
823
824 size_t MB2WC(wchar_t *buf, const char *psz, size_t WXUNUSED(n))
825 {
826 size_t inbuf = strlen(psz);
827 if (buf)
828 m2w.Convert(psz,buf);
829 return inbuf;
830 }
831
832 size_t WC2MB(char *buf, const wchar_t *psz, size_t WXUNUSED(n))
833 {
834 const size_t inbuf = wxWcslen(psz);
835 if (buf)
836 w2m.Convert(psz,buf);
837
838 return inbuf;
839 }
840
841 bool usable() const { return m_ok; }
842
843public:
844 wxFontEncoding enc;
845 wxEncodingConverter m2w, w2m;
846
847 // were we initialized successfully?
848 bool m_ok;
849
850 DECLARE_NO_COPY_CLASS(EC_CharSet)
851};
852
853#endif // wxUSE_FONTMAP
854
855// ----------------------------------------------------------------------------
856// the function creating the wxCharacterSet for the specified charset on the
857// current system, trying all possibilities
858// ----------------------------------------------------------------------------
859
860static wxCharacterSet *wxGetCharacterSet(const wxChar *name)
861{
862 // check for the special case of ASCII charset
863#if wxUSE_FONTMAP
864 if ( wxFontMapper::Get()->CharsetToEncoding(name) == wxFONTENCODING_DEFAULT )
865#else // wxUSE_FONTMAP
866 if ( !name )
867#endif // wxUSE_FONTMAP/!wxUSE_FONTMAP
868 {
869 // don't convert at all
870 return NULL;
871 }
872
873 // the test above must have taken care of this case
874 wxCHECK_MSG( name, NULL, _T("NULL name must be wxFONTENCODING_DEFAULT") );
875
876 wxCharacterSet *cset;
877
878 if ( wxStricmp(name, wxT("UTF8")) == 0 || wxStricmp(name, wxT("UTF-8")) == 0)
879 {
880 cset = new ID_CharSet(name, &wxConvUTF8);
881 }
882 else
883 {
884#ifdef HAVE_ICONV
885 cset = new IC_CharSet(name);
886#else // !HAVE_ICONV
887 cset = NULL;
888#endif // HAVE_ICONV/!HAVE_ICONV
889 }
890
891 // it can only be NULL in this case
892#ifndef HAVE_ICONV
893 if ( cset )
894#endif // !HAVE_ICONV
895 {
896 if ( cset->usable() )
897 return cset;
898
899 delete cset;
900 cset = NULL;
901 }
902
903#if defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXUNIVERSAL__)
904 cset = new CP_CharSet(name);
905 if ( cset->usable() )
906 return cset;
907
908 delete cset;
909 cset = NULL;
910#endif // defined(__WIN32__) && !defined(__WXMICROWIN__) && !defined(__WXUNIVERSAL__)
911
912#if wxUSE_FONTMAP
913 cset = new EC_CharSet(name);
914 if ( cset->usable() )
915 return cset;
916
917 delete cset;
918 cset = NULL;
919#endif // wxUSE_FONTMAP
920
921 wxLogError(_("Cannot convert from encoding '%s'!"), name);
922
923 return NULL;
924}
925
926// ============================================================================
927// wxCSConv implementation
928// ============================================================================
929
930wxCSConv::wxCSConv(const wxChar *charset)
931{
932 m_name = (wxChar *)NULL;
933 m_cset = (wxCharacterSet *) NULL;
934 m_deferred = TRUE;
935
936 SetName(charset);
937}
938
939wxCSConv::~wxCSConv()
940{
941 Clear();
942}
943
944wxCSConv::wxCSConv(const wxCSConv& conv)
945 : wxMBConv()
946{
947 Clear();
948 SetName(conv.m_name);
949}
950
951wxCSConv& wxCSConv::operator=(const wxCSConv& conv)
952{
953 Clear();
954 SetName(conv.m_name);
955 return *this;
956}
957
958void wxCSConv::Clear()
959{
960 if (m_name)
961 free(m_name);
962 if (m_cset)
963 delete m_cset;
964 m_name = NULL;
965 m_cset = NULL;
966}
967
968void wxCSConv::SetName(const wxChar *charset)
969{
970 if (charset)
971 {
972 m_name = wxStrdup(charset);
973 m_deferred = TRUE;
974 }
975}
976
977void wxCSConv::LoadNow()
978{
979 if ( m_deferred )
980 {
981 // it would probably be better to make GetSystemEncodingName() always
982 // available (i.e. even when wxUSE_INTL == 0)?
983#if wxUSE_INTL
984 if ( !m_name )
985 {
986 wxString name = wxLocale::GetSystemEncodingName();
987 if ( !name.empty() )
988 {
989 SetName(name);
990 }
991 }
992#endif // wxUSE_INTL
993
994 // wxGetCharacterSet() complains about NULL name
995 m_cset = m_name ? wxGetCharacterSet(m_name) : NULL;
996 m_deferred = FALSE;
997 }
998}
999
1000size_t wxCSConv::MB2WC(wchar_t *buf, const char *psz, size_t n) const
1001{
1002 ((wxCSConv *)this)->LoadNow(); // discard constness
1003
1004 if (m_cset)
1005 return m_cset->MB2WC(buf, psz, n);
1006
1007 // latin-1 (direct)
1008 size_t len = strlen(psz);
1009
1010 if (buf)
1011 {
1012 for (size_t c = 0; c <= len; c++)
1013 buf[c] = (unsigned char)(psz[c]);
1014 }
1015
1016 return len;
1017}
1018
1019size_t wxCSConv::WC2MB(char *buf, const wchar_t *psz, size_t n) const
1020{
1021 ((wxCSConv *)this)->LoadNow(); // discard constness
1022
1023 if (m_cset)
1024 return m_cset->WC2MB(buf, psz, n);
1025
1026 // latin-1 (direct)
1027 const size_t len = wxWcslen(psz);
1028 if (buf)
1029 {
1030 for (size_t c = 0; c <= len; c++)
1031 buf[c] = (psz[c] > 0xff) ? '?' : psz[c];
1032 }
1033
1034 return len;
1035}
1036
1037#endif // wxUSE_WCHAR_T
1038
1039