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