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";
53 struct IconvProcessor::Handler {
54 // assumes cd is valid
55 Handler(iconv_t const cd) : cd(cd) {}
57 if (iconv_close(cd) == -1)
58 LYXERR0("Error returned from iconv_close(" << errno << ')');
64 IconvProcessor::IconvProcessor(string tocode, string fromcode)
65 : tocode_(move(tocode)), fromcode_(move(fromcode))
70 IconvProcessor::IconvProcessor(IconvProcessor && other)
71 : tocode_(move(other.tocode_)), fromcode_(move(other.fromcode_)),
76 bool IconvProcessor::init()
80 iconv_t cd = iconv_open(tocode_.c_str(), fromcode_.c_str());
81 if (cd != (iconv_t)(-1)) {
82 h_ = make_unique<Handler>(cd);
85 lyxerr << "Error returned from iconv_open" << endl;
88 lyxerr << "EINVAL The conversion from " << fromcode_ << " to "
89 << tocode_ << " is not supported by the implementation."
93 lyxerr << "\tSome other error: " << errno << endl;
100 int IconvProcessor::convert(char const * buf, size_t buflen,
101 char * outbuf, size_t maxoutsize)
109 char ICONV_CONST * inbuf = const_cast<char ICONV_CONST *>(buf);
110 size_t inbytesleft = buflen;
111 size_t outbytesleft = maxoutsize;
113 int res = iconv(h_->cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
115 // flush out remaining data. This is needed because iconv sometimes
116 // holds back chars in the stream, waiting for a combination character
117 // (see e.g. http://sources.redhat.com/bugzilla/show_bug.cgi?id=1124)
118 iconv(h_->cd, NULL, NULL, &outbuf, &outbytesleft);
121 //lyxerr << "Inbytesleft: " << inbytesleft << endl;
122 //lyxerr << "Outbytesleft: " << outbytesleft << endl;
125 // Everything went well.
126 return maxoutsize - outbytesleft;
128 // There are some errors in the conversion
129 lyxerr << "Error returned from iconv" << endl;
132 lyxerr << "E2BIG There is not sufficient room at *outbuf." << endl;
136 lyxerr << (errno == EINVAL
137 ? "EINVAL An incomplete "
138 : "EILSEQ An invalid ")
139 << "multibyte sequence has been encountered in the input.\n"
140 << "When converting from " << fromcode_
141 << " to " << tocode_ << ".\n";
142 lyxerr << "Input:" << hex;
143 for (size_t i = 0; i < buflen; ++i) {
144 // char may be signed, avoid output of
145 // something like 0xffffffc2
146 boost::uint32_t const b =
147 *reinterpret_cast<unsigned char const *>(buf + i);
148 lyxerr << " 0x" << (unsigned int)b;
150 lyxerr << dec << endl;
153 lyxerr << "\tSome other error: " << errno << endl;
156 // We got an error so we close down the conversion engine
165 template<typename RetType, typename InType>
167 iconv_convert(IconvProcessor & processor, InType const * buf, size_t buflen)
170 return vector<RetType>();
172 char const * inbuf = reinterpret_cast<char const *>(buf);
173 size_t inbytesleft = buflen * sizeof(InType);
175 static QThreadStorage<std::vector<char> *> static_outbuf;
176 if (!static_outbuf.hasLocalData())
177 static_outbuf.setLocalData(new std::vector<char>(32768));
178 std::vector<char> & outbuf = *static_outbuf.localData();
179 // The number of UCS4 code points in buf is at most inbytesleft.
180 // The output encoding will use at most
181 // max_encoded_bytes(pimpl_->tocode_) per UCS4 code point.
182 size_t maxoutbufsize = max_encoded_bytes(processor.to()) * inbytesleft;
183 if (outbuf.size() < maxoutbufsize)
184 outbuf.resize(maxoutbufsize);
186 int bytes = processor.convert(inbuf, inbytesleft, &outbuf[0], outbuf.size());
189 // FIXME Maybe throw an exception and handle that in the caller?
190 return vector<RetType>();
192 RetType const * tmp = reinterpret_cast<RetType const *>(&outbuf[0]);
193 return vector<RetType>(tmp, tmp + bytes / sizeof(RetType));
199 IconvProcessor & utf8ToUcs4()
201 static QThreadStorage<IconvProcessor *> processor;
202 if (!processor.hasLocalData())
203 processor.setLocalData(new IconvProcessor(ucs4_codeset, "UTF-8"));
204 return *processor.localData();
208 vector<char_type> utf8_to_ucs4(vector<char> const & utf8str)
211 return vector<char_type>();
213 return utf8_to_ucs4(&utf8str[0], utf8str.size());
218 utf8_to_ucs4(char const * utf8str, size_t ls)
220 return iconv_convert<char_type>(utf8ToUcs4(), utf8str, ls);
225 utf16_to_ucs4(unsigned short const * s, size_t ls)
227 static QThreadStorage<IconvProcessor *> processor;
228 if (!processor.hasLocalData())
229 processor.setLocalData(new IconvProcessor(ucs4_codeset, utf16_codeset));
230 return iconv_convert<char_type>(*processor.localData(), s, ls);
234 vector<unsigned short>
235 ucs4_to_utf16(char_type const * s, size_t ls)
237 static QThreadStorage<IconvProcessor *> processor;
238 if (!processor.hasLocalData())
239 processor.setLocalData(new IconvProcessor(utf16_codeset, ucs4_codeset));
240 return iconv_convert<unsigned short>(*processor.localData(), s, ls);
244 IconvProcessor & ucs4ToUtf8()
246 static QThreadStorage<IconvProcessor *> processor;
247 if (!processor.hasLocalData())
248 processor.setLocalData(new IconvProcessor("UTF-8", ucs4_codeset));
249 return *processor.localData();
254 IconvProcessor & getProc(map<string, IconvProcessor> & processors,
255 string const & encoding, bool to)
257 string const & fromcode = to ? ucs4_codeset : encoding;
258 string const & tocode = to ? encoding : ucs4_codeset;
259 map<string, IconvProcessor>::iterator const it = processors.find(encoding);
260 if (it == processors.end()) {
261 IconvProcessor p(fromcode, tocode);
262 return processors.insert(make_pair(encoding, move(p))).first->second;
271 ucs4_to_utf8(char_type c)
273 return iconv_convert<char>(ucs4ToUtf8(), &c, 1);
278 ucs4_to_utf8(vector<char_type> const & ucs4str)
281 return vector<char>();
283 return ucs4_to_utf8(&ucs4str[0], ucs4str.size());
288 ucs4_to_utf8(char_type const * ucs4str, size_t ls)
290 return iconv_convert<char>(ucs4ToUtf8(), ucs4str, ls);
295 eightbit_to_ucs4(char const * s, size_t ls, string const & encoding)
297 static QThreadStorage<map<string, IconvProcessor> *> static_processors;
298 if (!static_processors.hasLocalData())
299 static_processors.setLocalData(new map<string, IconvProcessor>);
300 map<string, IconvProcessor> & processors = *static_processors.localData();
301 IconvProcessor & processor = getProc(processors, encoding, true);
302 return iconv_convert<char_type>(processor, s, ls);
308 map<string, IconvProcessor> & ucs4To8bitProcessors()
310 static QThreadStorage<map<string, IconvProcessor> *> processors;
311 if (!processors.hasLocalData())
312 processors.setLocalData(new map<string, IconvProcessor>);
313 return *processors.localData();
319 ucs4_to_eightbit(char_type const * ucs4str, size_t ls, string const & encoding)
321 map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
322 IconvProcessor & processor = getProc(processors, encoding, false);
323 return iconv_convert<char>(processor, ucs4str, ls);
327 char ucs4_to_eightbit(char_type ucs4, string const & encoding)
329 map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
330 IconvProcessor & processor = getProc(processors, encoding, false);
332 int const bytes = processor.convert((char *)(&ucs4), 4, &out, 1);
339 void ucs4_to_multibytes(char_type ucs4, vector<char> & out,
340 string const & encoding)
342 static QThreadStorage<map<string, IconvProcessor> *> static_processors;
343 if (!static_processors.hasLocalData())
344 static_processors.setLocalData(new map<string, IconvProcessor>);
345 map<string, IconvProcessor> & processors = *static_processors.localData();
346 IconvProcessor & processor = getProc(processors, encoding, false);
348 int bytes = processor.convert((char *)(&ucs4), 4, &out[0], 4);
355 int max_encoded_bytes(std::string const & encoding)
357 // FIXME: this information should be transferred to lib/encodings
358 // UTF8 uses at most 4 bytes to represent one UCS4 code point
359 // (see RFC 3629). RFC 2279 specifies 6 bytes, but that
360 // information is outdated, and RFC 2279 has been superseded by
362 // The CJK encodings use (different) multibyte representation as well.
363 // All other encodings encode one UCS4 code point in one byte
364 // (and can therefore only encode a subset of UCS4)
365 // Furthermore, all encodings that use shifting (like SJIS) do not work with
366 // iconv_codecvt_facet.
367 if (encoding == "UTF-8" ||
369 encoding == "EUC-TW")
371 else if (encoding == "EUC-JP")
373 else if (encoding == "ISO-2022-JP")
375 else if (encoding == "BIG5" ||
376 encoding == "EUC-KR" ||
377 encoding == "EUC-CN" ||
378 encoding == "SJIS" ||