3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Lars Gullik Bjønnes
8 * Full author contact details are available in file CREDITS.
10 * A collection of unicode conversion functions, using iconv.
15 #include "support/unicode.h"
16 #include "support/debug.h"
18 #include <QThreadStorage>
22 #include <boost/cstdint.hpp>
35 #ifdef WORDS_BIGENDIAN
36 char const * utf16_codeset = "UTF16-BE";
38 char const * utf16_codeset = "UTF16-LE";
46 #ifdef WORDS_BIGENDIAN
47 char const * ucs4_codeset = "UCS-4BE";
49 char const * ucs4_codeset = "UCS-4LE";
52 static const iconv_t invalid_cd = (iconv_t)(-1);
55 class IconvProcessor::Impl
57 // noncopyable because iconv_close() is called in destructor
59 Impl & operator=(Impl const &);
61 Impl(string const & to, string const & from)
62 : cd(invalid_cd), tocode_(to), fromcode_(from)
67 if (cd != invalid_cd && iconv_close(cd) == -1)
68 LYXERR0("Error returned from iconv_close(" << errno << ')');
77 IconvProcessor::IconvProcessor(char const * tocode, char const * fromcode)
78 : pimpl_(new IconvProcessor::Impl(tocode, fromcode))
83 IconvProcessor::IconvProcessor(IconvProcessor const & other)
84 : pimpl_(new IconvProcessor::Impl(other.pimpl_->tocode_, other.pimpl_->fromcode_))
89 IconvProcessor::~IconvProcessor()
95 IconvProcessor & IconvProcessor::operator=(IconvProcessor const & other)
99 pimpl_ = new Impl(other.pimpl_->tocode_, other.pimpl_->fromcode_);
105 bool IconvProcessor::init()
107 if (pimpl_->cd != invalid_cd)
110 pimpl_->cd = iconv_open(pimpl_->tocode_.c_str(), pimpl_->fromcode_.c_str());
111 if (pimpl_->cd != invalid_cd)
114 lyxerr << "Error returned from iconv_open" << endl;
117 lyxerr << "EINVAL The conversion from " << pimpl_->fromcode_
118 << " to " << pimpl_->tocode_
119 << " is not supported by the implementation."
123 lyxerr << "\tSome other error: " << errno << endl;
130 int IconvProcessor::convert(char const * buf, size_t buflen,
131 char * outbuf, size_t maxoutsize)
136 if (pimpl_->cd == invalid_cd) {
141 char ICONV_CONST * inbuf = const_cast<char ICONV_CONST *>(buf);
142 size_t inbytesleft = buflen;
143 size_t outbytesleft = maxoutsize;
145 int res = iconv(pimpl_->cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
147 // flush out remaining data. This is needed because iconv sometimes
148 // holds back chars in the stream, waiting for a combination character
149 // (see e.g. http://sources.redhat.com/bugzilla/show_bug.cgi?id=1124)
150 iconv(pimpl_->cd, NULL, NULL, &outbuf, &outbytesleft);
153 //lyxerr << "Inbytesleft: " << inbytesleft << endl;
154 //lyxerr << "Outbytesleft: " << outbytesleft << endl;
157 // Everything went well.
158 return maxoutsize - outbytesleft;
160 // There are some errors in the conversion
161 lyxerr << "Error returned from iconv" << endl;
164 lyxerr << "E2BIG There is not sufficient room at *outbuf." << endl;
167 lyxerr << "EILSEQ An invalid multibyte sequence"
168 << " has been encountered in the input.\n"
169 << "When converting from " << pimpl_->fromcode_
170 << " to " << pimpl_->tocode_ << ".\n";
171 lyxerr << "Input:" << hex;
172 for (size_t i = 0; i < buflen; ++i) {
173 // char may be signed, avoid output of
174 // something like 0xffffffc2
175 boost::uint32_t const b =
176 *reinterpret_cast<unsigned char const *>(buf + i);
177 lyxerr << " 0x" << (unsigned int)b;
179 lyxerr << dec << endl;
182 lyxerr << "EINVAL An incomplete multibyte sequence"
183 << " has been encountered in the input.\n"
184 << "When converting from " << pimpl_->fromcode_
185 << " to " << pimpl_->tocode_ << ".\n";
186 lyxerr << "Input:" << hex;
187 for (size_t i = 0; i < buflen; ++i) {
188 // char may be signed, avoid output of
189 // something like 0xffffffc2
190 boost::uint32_t const b =
191 *reinterpret_cast<unsigned char const *>(buf + i);
192 lyxerr << " 0x" << (unsigned int)b;
194 lyxerr << dec << endl;
197 lyxerr << "\tSome other error: " << errno << endl;
200 // We got an error so we close down the conversion engine
201 if (iconv_close(pimpl_->cd) == -1) {
202 lyxerr << "Error returned from iconv_close("
203 << errno << ")" << endl;
205 pimpl_->cd = invalid_cd;
210 std::string IconvProcessor::from() const
212 return pimpl_->fromcode_;
216 std::string IconvProcessor::to() const
218 return pimpl_->tocode_;
225 template<typename RetType, typename InType>
227 iconv_convert(IconvProcessor & processor, InType const * buf, size_t buflen)
230 return vector<RetType>();
232 char const * inbuf = reinterpret_cast<char const *>(buf);
233 size_t inbytesleft = buflen * sizeof(InType);
235 static QThreadStorage<std::vector<char> *> static_outbuf;
236 if (!static_outbuf.hasLocalData())
237 static_outbuf.setLocalData(new std::vector<char>(32768));
238 std::vector<char> & outbuf = *static_outbuf.localData();
239 // The number of UCS4 code points in buf is at most inbytesleft.
240 // The output encoding will use at most
241 // max_encoded_bytes(pimpl_->tocode_) per UCS4 code point.
242 size_t maxoutbufsize = max_encoded_bytes(processor.to()) * inbytesleft;
243 if (outbuf.size() < maxoutbufsize)
244 outbuf.resize(maxoutbufsize);
246 int bytes = processor.convert(inbuf, inbytesleft, &outbuf[0], outbuf.size());
249 // FIXME Maybe throw an exception and handle that in the caller?
250 return vector<RetType>();
252 RetType const * tmp = reinterpret_cast<RetType const *>(&outbuf[0]);
253 return vector<RetType>(tmp, tmp + bytes / sizeof(RetType));
259 IconvProcessor & utf8ToUcs4()
261 static QThreadStorage<IconvProcessor *> processor;
262 if (!processor.hasLocalData())
263 processor.setLocalData(new IconvProcessor(ucs4_codeset, "UTF-8"));
264 return *processor.localData();
268 vector<char_type> utf8_to_ucs4(vector<char> const & utf8str)
271 return vector<char_type>();
273 return utf8_to_ucs4(&utf8str[0], utf8str.size());
278 utf8_to_ucs4(char const * utf8str, size_t ls)
280 return iconv_convert<char_type>(utf8ToUcs4(), utf8str, ls);
285 utf16_to_ucs4(unsigned short const * s, size_t ls)
287 static QThreadStorage<IconvProcessor *> processor;
288 if (!processor.hasLocalData())
289 processor.setLocalData(new IconvProcessor(ucs4_codeset, utf16_codeset));
290 return iconv_convert<char_type>(*processor.localData(), s, ls);
294 vector<unsigned short>
295 ucs4_to_utf16(char_type const * s, size_t ls)
297 static QThreadStorage<IconvProcessor *> processor;
298 if (!processor.hasLocalData())
299 processor.setLocalData(new IconvProcessor(utf16_codeset, ucs4_codeset));
300 return iconv_convert<unsigned short>(*processor.localData(), s, ls);
304 IconvProcessor & ucs4ToUtf8()
306 static QThreadStorage<IconvProcessor *> processor;
307 if (!processor.hasLocalData())
308 processor.setLocalData(new IconvProcessor("UTF-8", ucs4_codeset));
309 return *processor.localData();
314 ucs4_to_utf8(char_type c)
316 return iconv_convert<char>(ucs4ToUtf8(), &c, 1);
321 ucs4_to_utf8(vector<char_type> const & ucs4str)
324 return vector<char>();
326 return ucs4_to_utf8(&ucs4str[0], ucs4str.size());
331 ucs4_to_utf8(char_type const * ucs4str, size_t ls)
333 return iconv_convert<char>(ucs4ToUtf8(), ucs4str, ls);
338 eightbit_to_ucs4(char const * s, size_t ls, string const & encoding)
340 static QThreadStorage<map<string, IconvProcessor> *> static_processors;
341 if (!static_processors.hasLocalData())
342 static_processors.setLocalData(new map<string, IconvProcessor>);
343 map<string, IconvProcessor> & processors = *static_processors.localData();
344 if (processors.find(encoding) == processors.end()) {
345 IconvProcessor processor(ucs4_codeset, encoding.c_str());
346 processors.insert(make_pair(encoding, processor));
348 return iconv_convert<char_type>(processors[encoding], s, ls);
354 map<string, IconvProcessor> & ucs4To8bitProcessors()
356 static QThreadStorage<map<string, IconvProcessor> *> processors;
357 if (!processors.hasLocalData())
358 processors.setLocalData(new map<string, IconvProcessor>);
359 return *processors.localData();
366 ucs4_to_eightbit(char_type const * ucs4str, size_t ls, string const & encoding)
368 map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
369 if (processors.find(encoding) == processors.end()) {
370 IconvProcessor processor(encoding.c_str(), ucs4_codeset);
371 processors.insert(make_pair(encoding, processor));
373 return iconv_convert<char>(processors[encoding], ucs4str, ls);
377 char ucs4_to_eightbit(char_type ucs4, string const & encoding)
379 map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
380 map<string, IconvProcessor>::iterator it = processors.find(encoding);
381 if (it == processors.end()) {
382 IconvProcessor processor(encoding.c_str(), ucs4_codeset);
383 it = processors.insert(make_pair(encoding, processor)).first;
387 int const bytes = it->second.convert((char *)(&ucs4), 4, &out, 1);
394 void ucs4_to_multibytes(char_type ucs4, vector<char> & out,
395 string const & encoding)
397 static QThreadStorage<map<string, IconvProcessor> *> static_processors;
398 if (!static_processors.hasLocalData())
399 static_processors.setLocalData(new map<string, IconvProcessor>);
400 map<string, IconvProcessor> & processors = *static_processors.localData();
401 map<string, IconvProcessor>::iterator it = processors.find(encoding);
402 if (it == processors.end()) {
403 IconvProcessor processor(encoding.c_str(), ucs4_codeset);
404 it = processors.insert(make_pair(encoding, processor)).first;
408 int bytes = it->second.convert((char *)(&ucs4), 4, &out[0], 4);
415 int max_encoded_bytes(std::string const & encoding)
417 // FIXME: this information should be transferred to lib/encodings
418 // UTF8 uses at most 4 bytes to represent one UCS4 code point
419 // (see RFC 3629). RFC 2279 specifies 6 bytes, but that
420 // information is outdated, and RFC 2279 has been superseded by
422 // The CJK encodings use (different) multibyte representation as well.
423 // All other encodings encode one UCS4 code point in one byte
424 // (and can therefore only encode a subset of UCS4)
425 // Furthermore, all encodings that use shifting (like SJIS) do not work with
426 // iconv_codecvt_facet.
427 if (encoding == "UTF-8" ||
429 encoding == "EUC-TW")
431 else if (encoding == "EUC-JP")
433 else if (encoding == "ISO-2022-JP")
435 else if (encoding == "BIG5" ||
436 encoding == "EUC-KR" ||
437 encoding == "EUC-CN" ||
438 encoding == "SJIS" ||