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_(tocode), fromcode_(fromcode)
69 bool IconvProcessor::init()
73 iconv_t cd = iconv_open(tocode_.c_str(), fromcode_.c_str());
74 if (cd != (iconv_t)(-1)) {
75 h_ = make_unique<Handler>(cd);
78 lyxerr << "Error returned from iconv_open" << endl;
81 lyxerr << "EINVAL The conversion from " << fromcode_ << " to "
82 << tocode_ << " is not supported by the implementation."
86 lyxerr << "\tSome other error: " << errno << endl;
93 int IconvProcessor::convert(char const * buf, size_t buflen,
94 char * outbuf, size_t maxoutsize)
102 char ICONV_CONST * inbuf = const_cast<char ICONV_CONST *>(buf);
103 size_t inbytesleft = buflen;
104 size_t outbytesleft = maxoutsize;
106 int res = iconv(h_->cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
108 // flush out remaining data. This is needed because iconv sometimes
109 // holds back chars in the stream, waiting for a combination character
110 // (see e.g. http://sources.redhat.com/bugzilla/show_bug.cgi?id=1124)
111 iconv(h_->cd, NULL, NULL, &outbuf, &outbytesleft);
114 //lyxerr << "Inbytesleft: " << inbytesleft << endl;
115 //lyxerr << "Outbytesleft: " << outbytesleft << endl;
118 // Everything went well.
119 return maxoutsize - outbytesleft;
121 // There are some errors in the conversion
122 lyxerr << "Error returned from iconv" << endl;
125 lyxerr << "E2BIG There is not sufficient room at *outbuf." << endl;
128 lyxerr << "EILSEQ An invalid multibyte sequence"
129 << " has been encountered in the input.\n"
130 << "When converting from " << fromcode_
131 << " to " << tocode_ << ".\n";
132 lyxerr << "Input:" << hex;
133 for (size_t i = 0; i < buflen; ++i) {
134 // char may be signed, avoid output of
135 // something like 0xffffffc2
136 boost::uint32_t const b =
137 *reinterpret_cast<unsigned char const *>(buf + i);
138 lyxerr << " 0x" << (unsigned int)b;
140 lyxerr << dec << endl;
143 lyxerr << "EINVAL An incomplete multibyte sequence"
144 << " has been encountered in the input.\n"
145 << "When converting from " << fromcode_
146 << " to " << tocode_ << ".\n";
147 lyxerr << "Input:" << hex;
148 for (size_t i = 0; i < buflen; ++i) {
149 // char may be signed, avoid output of
150 // something like 0xffffffc2
151 boost::uint32_t const b =
152 *reinterpret_cast<unsigned char const *>(buf + i);
153 lyxerr << " 0x" << (unsigned int)b;
155 lyxerr << dec << endl;
158 lyxerr << "\tSome other error: " << errno << endl;
161 // We got an error so we close down the conversion engine
170 template<typename RetType, typename InType>
172 iconv_convert(IconvProcessor & processor, InType const * buf, size_t buflen)
175 return vector<RetType>();
177 char const * inbuf = reinterpret_cast<char const *>(buf);
178 size_t inbytesleft = buflen * sizeof(InType);
180 static QThreadStorage<std::vector<char> *> static_outbuf;
181 if (!static_outbuf.hasLocalData())
182 static_outbuf.setLocalData(new std::vector<char>(32768));
183 std::vector<char> & outbuf = *static_outbuf.localData();
184 // The number of UCS4 code points in buf is at most inbytesleft.
185 // The output encoding will use at most
186 // max_encoded_bytes(pimpl_->tocode_) per UCS4 code point.
187 size_t maxoutbufsize = max_encoded_bytes(processor.to()) * inbytesleft;
188 if (outbuf.size() < maxoutbufsize)
189 outbuf.resize(maxoutbufsize);
191 int bytes = processor.convert(inbuf, inbytesleft, &outbuf[0], outbuf.size());
194 // FIXME Maybe throw an exception and handle that in the caller?
195 return vector<RetType>();
197 RetType const * tmp = reinterpret_cast<RetType const *>(&outbuf[0]);
198 return vector<RetType>(tmp, tmp + bytes / sizeof(RetType));
204 IconvProcessor & utf8ToUcs4()
206 static QThreadStorage<IconvProcessor *> processor;
207 if (!processor.hasLocalData())
208 processor.setLocalData(new IconvProcessor(ucs4_codeset, "UTF-8"));
209 return *processor.localData();
213 vector<char_type> utf8_to_ucs4(vector<char> const & utf8str)
216 return vector<char_type>();
218 return utf8_to_ucs4(&utf8str[0], utf8str.size());
223 utf8_to_ucs4(char const * utf8str, size_t ls)
225 return iconv_convert<char_type>(utf8ToUcs4(), utf8str, ls);
230 utf16_to_ucs4(unsigned short const * s, size_t ls)
232 static QThreadStorage<IconvProcessor *> processor;
233 if (!processor.hasLocalData())
234 processor.setLocalData(new IconvProcessor(ucs4_codeset, utf16_codeset));
235 return iconv_convert<char_type>(*processor.localData(), s, ls);
239 vector<unsigned short>
240 ucs4_to_utf16(char_type const * s, size_t ls)
242 static QThreadStorage<IconvProcessor *> processor;
243 if (!processor.hasLocalData())
244 processor.setLocalData(new IconvProcessor(utf16_codeset, ucs4_codeset));
245 return iconv_convert<unsigned short>(*processor.localData(), s, ls);
249 IconvProcessor & ucs4ToUtf8()
251 static QThreadStorage<IconvProcessor *> processor;
252 if (!processor.hasLocalData())
253 processor.setLocalData(new IconvProcessor("UTF-8", ucs4_codeset));
254 return *processor.localData();
259 IconvProcessor & getProc(map<string, IconvProcessor> & processors,
260 string const & encoding, bool to)
262 string const & fromcode = to ? ucs4_codeset : encoding;
263 string const & tocode = to ? encoding : ucs4_codeset;
264 map<string, IconvProcessor>::iterator const it = processors.find(encoding);
265 if (it == processors.end()) {
266 IconvProcessor p(fromcode, tocode);
267 return processors.insert(make_pair(encoding, move(p))).first->second;
276 ucs4_to_utf8(char_type c)
278 return iconv_convert<char>(ucs4ToUtf8(), &c, 1);
283 ucs4_to_utf8(vector<char_type> const & ucs4str)
286 return vector<char>();
288 return ucs4_to_utf8(&ucs4str[0], ucs4str.size());
293 ucs4_to_utf8(char_type const * ucs4str, size_t ls)
295 return iconv_convert<char>(ucs4ToUtf8(), ucs4str, ls);
300 eightbit_to_ucs4(char const * s, size_t ls, string const & encoding)
302 static QThreadStorage<map<string, IconvProcessor> *> static_processors;
303 if (!static_processors.hasLocalData())
304 static_processors.setLocalData(new map<string, IconvProcessor>);
305 map<string, IconvProcessor> & processors = *static_processors.localData();
306 IconvProcessor & processor = getProc(processors, encoding, true);
307 return iconv_convert<char_type>(processor, s, ls);
313 map<string, IconvProcessor> & ucs4To8bitProcessors()
315 static QThreadStorage<map<string, IconvProcessor> *> processors;
316 if (!processors.hasLocalData())
317 processors.setLocalData(new map<string, IconvProcessor>);
318 return *processors.localData();
324 ucs4_to_eightbit(char_type const * ucs4str, size_t ls, string const & encoding)
326 map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
327 IconvProcessor & processor = getProc(processors, encoding, false);
328 return iconv_convert<char>(processor, ucs4str, ls);
332 char ucs4_to_eightbit(char_type ucs4, string const & encoding)
334 map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
335 IconvProcessor & processor = getProc(processors, encoding, false);
337 int const bytes = processor.convert((char *)(&ucs4), 4, &out, 1);
344 void ucs4_to_multibytes(char_type ucs4, vector<char> & out,
345 string const & encoding)
347 static QThreadStorage<map<string, IconvProcessor> *> static_processors;
348 if (!static_processors.hasLocalData())
349 static_processors.setLocalData(new map<string, IconvProcessor>);
350 map<string, IconvProcessor> & processors = *static_processors.localData();
351 IconvProcessor & processor = getProc(processors, encoding, false);
353 int bytes = processor.convert((char *)(&ucs4), 4, &out[0], 4);
360 int max_encoded_bytes(std::string const & encoding)
362 // FIXME: this information should be transferred to lib/encodings
363 // UTF8 uses at most 4 bytes to represent one UCS4 code point
364 // (see RFC 3629). RFC 2279 specifies 6 bytes, but that
365 // information is outdated, and RFC 2279 has been superseded by
367 // The CJK encodings use (different) multibyte representation as well.
368 // All other encodings encode one UCS4 code point in one byte
369 // (and can therefore only encode a subset of UCS4)
370 // Furthermore, all encodings that use shifting (like SJIS) do not work with
371 // iconv_codecvt_facet.
372 if (encoding == "UTF-8" ||
374 encoding == "EUC-TW")
376 else if (encoding == "EUC-JP")
378 else if (encoding == "ISO-2022-JP")
380 else if (encoding == "BIG5" ||
381 encoding == "EUC-KR" ||
382 encoding == "EUC-CN" ||
383 encoding == "SJIS" ||