1 /****************************************************************************
3 ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtCore module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** No Commercial Usage
11 ** This file contains pre-release code and may not be distributed.
12 ** You may use this file in accordance with the terms and conditions
13 ** contained in the Technology Preview License Agreement accompanying
16 ** GNU Lesser General Public License Usage
17 ** Alternatively, this file may be used under the terms of the GNU Lesser
18 ** General Public License version 2.1 as published by the Free Software
19 ** Foundation and appearing in the file LICENSE.LGPL included in the
20 ** packaging of this file. Please review the following information to
21 ** ensure the GNU Lesser General Public License version 2.1 requirements
22 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 ** In addition, as a special exception, Nokia gives you certain additional
25 ** rights. These rights are described in the Nokia Qt LGPL Exception
26 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 ** If you have questions regarding the use of this file, please contact
29 ** Nokia at qt-info@nokia.com.
40 ****************************************************************************/
42 #include "qiconvcodec_p.h"
43 #include "qtextcodec_p.h"
46 #include <qthreadstorage.h>
53 // unistd.h is needed for the _XOPEN_UNIX macro
55 #if defined(_XOPEN_UNIX) && !defined(Q_OS_QNX) && !defined(Q_OS_OSF)
56 # include <langinfo.h>
59 #if defined(Q_OS_HPUX)
62 #elif defined(Q_OS_AIX)
64 # define UTF16 "UCS-2"
65 #elif defined(Q_OS_FREEBSD) || defined(Q_OS_MAC)
67 # if Q_BYTE_ORDER == Q_BIG_ENDIAN
68 # define UTF16 "UTF-16BE"
70 # define UTF16 "UTF-16LE"
73 # define UTF16 "UTF-16"
80 typedef iconv_t (*Ptr_iconv_open
) (const char*, const char*);
81 typedef size_t (*Ptr_iconv
) (iconv_t
, const char **, size_t *, char **, size_t *);
82 typedef int (*Ptr_iconv_close
) (iconv_t
);
84 static Ptr_iconv_open ptr_iconv_open
= 0;
85 static Ptr_iconv ptr_iconv
= 0;
86 static Ptr_iconv_close ptr_iconv_close
= 0;
91 extern bool qt_locale_initialized
;
93 QIconvCodec::QIconvCodec()
96 utf16Codec
= QTextCodec::codecForMib(1015);
97 Q_ASSERT_X(utf16Codec
!= 0,
98 "QIconvCodec::convertToUnicode",
99 "internal error, UTF-16 codec not found");
101 fprintf(stderr
, "QIconvCodec::convertToUnicode: internal error, UTF-16 codec not found\n");
102 utf16Codec
= reinterpret_cast<QTextCodec
*>(~0);
104 #if defined(Q_OS_MAC)
105 if (ptr_iconv_open
== 0) {
106 QLibrary
libiconv(QLatin1String("/usr/lib/libiconv"));
107 libiconv
.setLoadHints(QLibrary::ExportExternalSymbolsHint
);
109 ptr_iconv_open
= reinterpret_cast<Ptr_iconv_open
>(libiconv
.resolve("libiconv_open"));
111 ptr_iconv_open
= reinterpret_cast<Ptr_iconv_open
>(libiconv
.resolve("iconv_open"));
112 ptr_iconv
= reinterpret_cast<Ptr_iconv
>(libiconv
.resolve("libiconv"));
114 ptr_iconv
= reinterpret_cast<Ptr_iconv
>(libiconv
.resolve("iconv"));
115 ptr_iconv_close
= reinterpret_cast<Ptr_iconv_close
>(libiconv
.resolve("libiconv_close"));
116 if (!ptr_iconv_close
)
117 ptr_iconv_close
= reinterpret_cast<Ptr_iconv_close
>(libiconv
.resolve("iconv_close"));
119 Q_ASSERT_X(ptr_iconv_open
&& ptr_iconv
&& ptr_iconv_close
,
120 "QIconvCodec::QIconvCodec()",
121 "internal error, could not resolve the iconv functions");
124 # define iconv_open ptr_iconv_open
126 # define iconv ptr_iconv
128 # define iconv_close ptr_iconv_close
133 QIconvCodec::~QIconvCodec()
137 QIconvCodec::IconvState::IconvState(iconv_t x
)
138 : buffer(array
), bufferLen(sizeof array
), cd(x
)
142 QIconvCodec::IconvState::~IconvState()
144 if (cd
!= reinterpret_cast<iconv_t
>(-1))
150 void QIconvCodec::IconvState::saveChars(const char *c
, int count
)
152 if (count
> bufferLen
) {
155 buffer
= new char[bufferLen
= count
];
158 memcpy(buffer
, c
, count
);
161 static void qIconvCodecStateFree(QTextCodec::ConverterState
*state
)
163 delete reinterpret_cast<QIconvCodec::IconvState
*>(state
->d
);
166 Q_GLOBAL_STATIC(QThreadStorage
<QIconvCodec::IconvState
*>, toUnicodeState
)
168 QString
QIconvCodec::convertToUnicode(const char* chars
, int len
, ConverterState
*convState
) const
170 if (utf16Codec
== reinterpret_cast<QTextCodec
*>(~0))
171 return QString::fromAscii(chars
, len
);
173 int invalidCount
= 0;
174 int remainingCount
= 0;
175 char *remainingBuffer
= 0;
179 // stateful conversion
180 pstate
= reinterpret_cast<IconvState
**>(&convState
->d
);
183 remainingCount
= convState
->remainingChars
;
184 remainingBuffer
= (*pstate
)->buffer
;
187 convState
->flags
|= FreeFunction
;
188 QTextCodecUnalignedPointer::encode(convState
->state_data
, qIconvCodecStateFree
);
191 QThreadStorage
<QIconvCodec::IconvState
*> *ts
= toUnicodeState();
192 if (!qt_locale_initialized
|| !ts
) {
193 // we're running after the Q_GLOBAL_STATIC has been deleted
194 // or before the QCoreApplication initialization
195 // bad programmer, no cookie for you
196 return QString::fromLatin1(chars
, len
);
199 // stateless conversion -- use thread-local data
200 pstate
= &toUnicodeState()->localData();
204 // first time, create the state
205 iconv_t cd
= QIconvCodec::createIconv_t(UTF16
, 0);
206 if (cd
== reinterpret_cast<iconv_t
>(-1)) {
207 static int reported
= 0;
210 "QIconvCodec::convertToUnicode: using ASCII for conversion, iconv_open failed\n");
212 return QString::fromAscii(chars
, len
);
215 *pstate
= new IconvState(cd
);
218 IconvState
*state
= *pstate
;
219 size_t inBytesLeft
= len
;
220 // best case assumption, each byte is converted into one UTF-16 character, plus 2 bytes for the BOM
222 // GNU doesn't disagree with POSIX :/
223 const char *inBytes
= chars
;
225 char *inBytes
= const_cast<char *>(chars
);
229 if (remainingCount
) {
230 // we have to prepend the remaining bytes from the previous conversion
231 inBytesLeft
+= remainingCount
;
232 in
.resize(inBytesLeft
);
235 memcpy(in
.data(), remainingBuffer
, remainingCount
);
236 memcpy(in
.data() + remainingCount
, chars
, len
);
241 size_t outBytesLeft
= len
* 2 + 2;
242 QByteArray
ba(outBytesLeft
, Qt::Uninitialized
);
243 char *outBytes
= ba
.data();
245 size_t ret
= iconv(state
->cd
, &inBytes
, &inBytesLeft
, &outBytes
, &outBytesLeft
);
246 if (ret
== (size_t) -1) {
247 if (errno
== E2BIG
) {
248 int offset
= ba
.size() - outBytesLeft
;
249 ba
.resize(ba
.size() * 2);
250 outBytes
= ba
.data() + offset
;
251 outBytesLeft
= ba
.size() - offset
;
256 if (errno
== EILSEQ
) {
257 // conversion stopped because of an invalid character in the sequence
259 } else if (errno
== EINVAL
&& convState
) {
260 // conversion stopped because the remaining inBytesLeft make up
261 // an incomplete multi-byte sequence; save them for later
262 state
->saveChars(inBytes
, inBytesLeft
);
263 remainingCount
= inBytesLeft
;
267 if (errno
== EILSEQ
|| errno
== EINVAL
) {
268 // skip the next character
275 // note, cannot use qWarning() since we are implementing the codecForLocale :)
276 perror("QIconvCodec::convertToUnicode: using ASCII for conversion, iconv failed");
280 iconv(state
->cd
, 0, &inBytesLeft
, 0, &outBytesLeft
);
283 return QString::fromAscii(chars
, len
);
285 } while (inBytesLeft
!= 0);
287 QString s
= utf16Codec
->toUnicode(ba
.constData(), ba
.size() - outBytesLeft
);
290 convState
->invalidChars
= invalidCount
;
291 convState
->remainingChars
= remainingCount
;
294 iconv(state
->cd
, 0, &inBytesLeft
, 0, &outBytesLeft
);
300 Q_GLOBAL_STATIC(QThreadStorage
<QIconvCodec::IconvState
*>, fromUnicodeState
)
302 QByteArray
QIconvCodec::convertFromUnicode(const QChar
*uc
, int len
, ConverterState
*convState
) const
308 #if defined(GNU_LIBICONV)
309 const char **inBytesPtr
= const_cast<const char **>(&inBytes
);
311 char **inBytesPtr
= &inBytes
;
314 QThreadStorage
<QIconvCodec::IconvState
*> *ts
= fromUnicodeState();
315 if (!qt_locale_initialized
|| !ts
) {
316 // we're running after the Q_GLOBAL_STATIC has been deleted
317 // or before the QCoreApplication initialization
318 // bad programmer, no cookie for you
320 // this is a special case - zero-sized string should be
321 // translated to empty but not-null QByteArray.
322 return QByteArray("");
323 return QString::fromRawData(uc
, len
).toLatin1();
325 IconvState
*&state
= ts
->localData();
327 state
= new IconvState(QIconvCodec::createIconv_t(0, UTF16
));
328 if (state
->cd
!= reinterpret_cast<iconv_t
>(-1)) {
329 size_t outBytesLeft
= len
+ 3; // +3 for the BOM
330 QByteArray
ba(outBytesLeft
, Qt::Uninitialized
);
331 outBytes
= ba
.data();
334 // give iconv() a BOM
335 QChar bom
[] = { QChar(QChar::ByteOrderMark
) };
336 inBytes
= reinterpret_cast<char *>(bom
);
337 inBytesLeft
= sizeof(bom
);
338 if (iconv(state
->cd
, inBytesPtr
, &inBytesLeft
, &outBytes
, &outBytesLeft
) == (size_t) -1) {
339 perror("QIconvCodec::convertFromUnicode: using ASCII for conversion, iconv failed for BOM");
341 iconv_close(state
->cd
);
342 state
->cd
= reinterpret_cast<iconv_t
>(-1);
344 return QString(uc
, len
).toAscii();
349 if (state
->cd
== reinterpret_cast<iconv_t
>(-1)) {
350 static int reported
= 0;
353 "QIconvCodec::convertFromUnicode: using ASCII for conversion, iconv_open failed\n");
355 return QString(uc
, len
).toAscii();
358 size_t outBytesLeft
= len
;
359 QByteArray
ba(outBytesLeft
, Qt::Uninitialized
);
360 outBytes
= ba
.data();
362 // now feed iconv() the real data
363 inBytes
= const_cast<char *>(reinterpret_cast<const char *>(uc
));
364 inBytesLeft
= len
* sizeof(QChar
);
367 if (convState
&& convState
->remainingChars
) {
368 // we have one surrogate char to be prepended
369 in
.resize(sizeof(QChar
) + len
);
372 QChar remaining
= convState
->state_data
[0];
373 memcpy(in
.data(), &remaining
, sizeof(QChar
));
374 memcpy(in
.data() + sizeof(QChar
), uc
, inBytesLeft
);
376 inBytesLeft
+= sizeof(QChar
);
377 convState
->remainingChars
= 0;
380 int invalidCount
= 0;
381 while (inBytesLeft
!= 0) {
382 if (iconv(state
->cd
, inBytesPtr
, &inBytesLeft
, &outBytes
, &outBytesLeft
) == (size_t) -1) {
383 if (errno
== EINVAL
&& convState
) {
384 // buffer ends in a surrogate
385 Q_ASSERT(inBytesLeft
== 2);
386 convState
->remainingChars
= 1;
387 convState
->state_data
[0] = uc
[len
- 1].unicode();
397 inBytes
+= sizeof(QChar
);
398 inBytesLeft
-= sizeof(QChar
);
403 int offset
= ba
.size() - outBytesLeft
;
404 ba
.resize(ba
.size() * 2);
405 outBytes
= ba
.data() + offset
;
406 outBytesLeft
= ba
.size() - offset
;
411 // note, cannot use qWarning() since we are implementing the codecForLocale :)
412 perror("QIconvCodec::convertFromUnicode: using ASCII for conversion, iconv failed");
414 // reset to initial state
415 iconv(state
->cd
, 0, &inBytesLeft
, 0, &outBytesLeft
);
417 return QString(uc
, len
).toAscii();
423 // reset to initial state
424 iconv(state
->cd
, 0, &inBytesLeft
, 0, &outBytesLeft
);
426 ba
.resize(ba
.size() - outBytesLeft
);
429 convState
->invalidChars
= invalidCount
;
434 QByteArray
QIconvCodec::name() const
439 int QIconvCodec::mibEnum() const
444 iconv_t
QIconvCodec::createIconv_t(const char *to
, const char *from
)
446 Q_ASSERT((to
== 0 && from
!= 0) || (to
!= 0 && from
== 0));
448 iconv_t cd
= (iconv_t
) -1;
449 #if defined(__GLIBC__) || defined(GNU_LIBICONV)
450 // both GLIBC and libgnuiconv will use the locale's encoding if from or to is an empty string
451 static const char empty_codeset
[] = "";
452 const char *codeset
= empty_codeset
;
453 cd
= iconv_open(to
? to
: codeset
, from
? from
: codeset
);
458 #if defined(_XOPEN_UNIX) && !defined(Q_OS_QNX) && !defined(Q_OS_OSF)
459 if (cd
== (iconv_t
) -1) {
460 codeset
= nl_langinfo(CODESET
);
462 cd
= iconv_open(to
? to
: codeset
, from
? from
: codeset
);
466 if (cd
== (iconv_t
) -1) {
467 // Very poorly defined and followed standards causes lots of
468 // code to try to get all the cases... This logic is
469 // duplicated in QTextCodec, so if you change it here, change
472 // Try to determine locale codeset from locale name assigned to
473 // LC_CTYPE category.
475 // First part is getting that locale name. First try setlocale() which
476 // definitely knows it, but since we cannot fully trust it, get ready
477 // to fall back to environment variables.
478 char * ctype
= qstrdup(setlocale(LC_CTYPE
, 0));
480 // Get the first nonempty value from $LC_ALL, $LC_CTYPE, and $LANG
481 // environment variables.
482 char * lang
= qstrdup(qgetenv("LC_ALL").constData());
483 if (!lang
|| lang
[0] == 0 || strcmp(lang
, "C") == 0) {
484 if (lang
) delete [] lang
;
485 lang
= qstrdup(qgetenv("LC_CTYPE").constData());
487 if (!lang
|| lang
[0] == 0 || strcmp(lang
, "C") == 0) {
488 if (lang
) delete [] lang
;
489 lang
= qstrdup(qgetenv("LANG").constData());
492 // Now try these in order:
493 // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)
494 // 2. CODESET from lang if it contains a .CODESET part
495 // 3. ctype (maybe the locale is named "ISO-8859-1" or something)
497 // 5. check for "@euro"
499 // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15)
500 codeset
= ctype
? strchr(ctype
, '.') : 0;
501 if (codeset
&& *codeset
== '.') {
503 cd
= iconv_open(to
? to
: codeset
, from
? from
: codeset
);
506 // 2. CODESET from lang if it contains a .CODESET part
507 codeset
= lang
? strchr(lang
, '.') : 0;
508 if (cd
== (iconv_t
) -1 && codeset
&& *codeset
== '.') {
510 cd
= iconv_open(to
? to
: codeset
, from
? from
: codeset
);
513 // 3. ctype (maybe the locale is named "ISO-8859-1" or something)
514 if (cd
== (iconv_t
) -1 && ctype
&& *ctype
!= 0 && strcmp (ctype
, "C") != 0)
515 cd
= iconv_open(to
? to
: ctype
, from
? from
: ctype
);
519 if (cd
== (iconv_t
) -1 && lang
&& *lang
!= 0)
520 cd
= iconv_open(to
? to
: lang
, from
? from
: lang
);
523 if ((cd
== (iconv_t
) -1 && ctype
&& strstr(ctype
, "@euro")) || (lang
&& strstr(lang
, "@euro")))
524 cd
= iconv_open(to
? to
: "ISO8859-15", from
? from
: "ISO8859-15");