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
58 // noncopyable because iconv_close() is called in destructor
59 Impl(Impl const &) = delete;
60 Impl & operator=(Impl const &) = delete;
62 Impl(string const & to, string const & from)
63 : cd(invalid_cd), tocode_(to), fromcode_(from)
68 if (cd != invalid_cd && iconv_close(cd) == -1)
69 LYXERR0("Error returned from iconv_close(" << errno << ')');
78 IconvProcessor::IconvProcessor(char const * tocode, char const * fromcode)
79 : pimpl_(new IconvProcessor::Impl(tocode, fromcode))
84 IconvProcessor::IconvProcessor(IconvProcessor const & other)
85 : pimpl_(new IconvProcessor::Impl(other.pimpl_->tocode_, other.pimpl_->fromcode_))
90 IconvProcessor::~IconvProcessor()
96 IconvProcessor & IconvProcessor::operator=(IconvProcessor const & other)
100 pimpl_ = new Impl(other.pimpl_->tocode_, other.pimpl_->fromcode_);
106 bool IconvProcessor::init()
108 if (pimpl_->cd != invalid_cd)
111 pimpl_->cd = iconv_open(pimpl_->tocode_.c_str(), pimpl_->fromcode_.c_str());
112 if (pimpl_->cd != invalid_cd)
115 lyxerr << "Error returned from iconv_open" << endl;
118 lyxerr << "EINVAL The conversion from " << pimpl_->fromcode_
119 << " to " << pimpl_->tocode_
120 << " is not supported by the implementation."
124 lyxerr << "\tSome other error: " << errno << endl;
131 int IconvProcessor::convert(char const * buf, size_t buflen,
132 char * outbuf, size_t maxoutsize)
137 if (pimpl_->cd == invalid_cd) {
142 char ICONV_CONST * inbuf = const_cast<char ICONV_CONST *>(buf);
143 size_t inbytesleft = buflen;
144 size_t outbytesleft = maxoutsize;
146 int res = iconv(pimpl_->cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
148 // flush out remaining data. This is needed because iconv sometimes
149 // holds back chars in the stream, waiting for a combination character
150 // (see e.g. http://sources.redhat.com/bugzilla/show_bug.cgi?id=1124)
151 iconv(pimpl_->cd, NULL, NULL, &outbuf, &outbytesleft);
154 //lyxerr << "Inbytesleft: " << inbytesleft << endl;
155 //lyxerr << "Outbytesleft: " << outbytesleft << endl;
158 // Everything went well.
159 return maxoutsize - outbytesleft;
161 // There are some errors in the conversion
162 lyxerr << "Error returned from iconv" << endl;
165 lyxerr << "E2BIG There is not sufficient room at *outbuf." << endl;
168 lyxerr << "EILSEQ An invalid multibyte sequence"
169 << " has been encountered in the input.\n"
170 << "When converting from " << pimpl_->fromcode_
171 << " to " << pimpl_->tocode_ << ".\n";
172 lyxerr << "Input:" << hex;
173 for (size_t i = 0; i < buflen; ++i) {
174 // char may be signed, avoid output of
175 // something like 0xffffffc2
176 boost::uint32_t const b =
177 *reinterpret_cast<unsigned char const *>(buf + i);
178 lyxerr << " 0x" << (unsigned int)b;
180 lyxerr << dec << endl;
183 lyxerr << "EINVAL An incomplete multibyte sequence"
184 << " has been encountered in the input.\n"
185 << "When converting from " << pimpl_->fromcode_
186 << " to " << pimpl_->tocode_ << ".\n";
187 lyxerr << "Input:" << hex;
188 for (size_t i = 0; i < buflen; ++i) {
189 // char may be signed, avoid output of
190 // something like 0xffffffc2
191 boost::uint32_t const b =
192 *reinterpret_cast<unsigned char const *>(buf + i);
193 lyxerr << " 0x" << (unsigned int)b;
195 lyxerr << dec << endl;
198 lyxerr << "\tSome other error: " << errno << endl;
201 // We got an error so we close down the conversion engine
202 if (iconv_close(pimpl_->cd) == -1) {
203 lyxerr << "Error returned from iconv_close("
204 << errno << ")" << endl;
206 pimpl_->cd = invalid_cd;
211 std::string IconvProcessor::from() const
213 return pimpl_->fromcode_;
217 std::string IconvProcessor::to() const
219 return pimpl_->tocode_;
226 template<typename RetType, typename InType>
228 iconv_convert(IconvProcessor & processor, InType const * buf, size_t buflen)
231 return vector<RetType>();
233 char const * inbuf = reinterpret_cast<char const *>(buf);
234 size_t inbytesleft = buflen * sizeof(InType);
236 static QThreadStorage<std::vector<char> *> static_outbuf;
237 if (!static_outbuf.hasLocalData())
238 static_outbuf.setLocalData(new std::vector<char>(32768));
239 std::vector<char> & outbuf = *static_outbuf.localData();
240 // The number of UCS4 code points in buf is at most inbytesleft.
241 // The output encoding will use at most
242 // max_encoded_bytes(pimpl_->tocode_) per UCS4 code point.
243 size_t maxoutbufsize = max_encoded_bytes(processor.to()) * inbytesleft;
244 if (outbuf.size() < maxoutbufsize)
245 outbuf.resize(maxoutbufsize);
247 int bytes = processor.convert(inbuf, inbytesleft, &outbuf[0], outbuf.size());
250 // FIXME Maybe throw an exception and handle that in the caller?
251 return vector<RetType>();
253 RetType const * tmp = reinterpret_cast<RetType const *>(&outbuf[0]);
254 return vector<RetType>(tmp, tmp + bytes / sizeof(RetType));
260 IconvProcessor & utf8ToUcs4()
262 static QThreadStorage<IconvProcessor *> processor;
263 if (!processor.hasLocalData())
264 processor.setLocalData(new IconvProcessor(ucs4_codeset, "UTF-8"));
265 return *processor.localData();
269 vector<char_type> utf8_to_ucs4(vector<char> const & utf8str)
272 return vector<char_type>();
274 return utf8_to_ucs4(&utf8str[0], utf8str.size());
279 utf8_to_ucs4(char const * utf8str, size_t ls)
281 return iconv_convert<char_type>(utf8ToUcs4(), utf8str, ls);
286 utf16_to_ucs4(unsigned short const * s, size_t ls)
288 static QThreadStorage<IconvProcessor *> processor;
289 if (!processor.hasLocalData())
290 processor.setLocalData(new IconvProcessor(ucs4_codeset, utf16_codeset));
291 return iconv_convert<char_type>(*processor.localData(), s, ls);
295 vector<unsigned short>
296 ucs4_to_utf16(char_type const * s, size_t ls)
298 static QThreadStorage<IconvProcessor *> processor;
299 if (!processor.hasLocalData())
300 processor.setLocalData(new IconvProcessor(utf16_codeset, ucs4_codeset));
301 return iconv_convert<unsigned short>(*processor.localData(), s, ls);
305 IconvProcessor & ucs4ToUtf8()
307 static QThreadStorage<IconvProcessor *> processor;
308 if (!processor.hasLocalData())
309 processor.setLocalData(new IconvProcessor("UTF-8", ucs4_codeset));
310 return *processor.localData();
315 ucs4_to_utf8(char_type c)
317 return iconv_convert<char>(ucs4ToUtf8(), &c, 1);
322 ucs4_to_utf8(vector<char_type> const & ucs4str)
325 return vector<char>();
327 return ucs4_to_utf8(&ucs4str[0], ucs4str.size());
332 ucs4_to_utf8(char_type const * ucs4str, size_t ls)
334 return iconv_convert<char>(ucs4ToUtf8(), ucs4str, ls);
339 eightbit_to_ucs4(char const * s, size_t ls, string const & encoding)
341 static QThreadStorage<map<string, IconvProcessor> *> static_processors;
342 if (!static_processors.hasLocalData())
343 static_processors.setLocalData(new map<string, IconvProcessor>);
344 map<string, IconvProcessor> & processors = *static_processors.localData();
345 if (processors.find(encoding) == processors.end()) {
346 IconvProcessor processor(ucs4_codeset, encoding.c_str());
347 processors.insert(make_pair(encoding, processor));
349 return iconv_convert<char_type>(processors[encoding], s, ls);
355 map<string, IconvProcessor> & ucs4To8bitProcessors()
357 static QThreadStorage<map<string, IconvProcessor> *> processors;
358 if (!processors.hasLocalData())
359 processors.setLocalData(new map<string, IconvProcessor>);
360 return *processors.localData();
367 ucs4_to_eightbit(char_type const * ucs4str, size_t ls, string const & encoding)
369 map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
370 if (processors.find(encoding) == processors.end()) {
371 IconvProcessor processor(encoding.c_str(), ucs4_codeset);
372 processors.insert(make_pair(encoding, processor));
374 return iconv_convert<char>(processors[encoding], ucs4str, ls);
378 char ucs4_to_eightbit(char_type ucs4, string const & encoding)
380 map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
381 map<string, IconvProcessor>::iterator it = processors.find(encoding);
382 if (it == processors.end()) {
383 IconvProcessor processor(encoding.c_str(), ucs4_codeset);
384 it = processors.insert(make_pair(encoding, processor)).first;
388 int const bytes = it->second.convert((char *)(&ucs4), 4, &out, 1);
395 void ucs4_to_multibytes(char_type ucs4, vector<char> & out,
396 string const & encoding)
398 static QThreadStorage<map<string, IconvProcessor> *> static_processors;
399 if (!static_processors.hasLocalData())
400 static_processors.setLocalData(new map<string, IconvProcessor>);
401 map<string, IconvProcessor> & processors = *static_processors.localData();
402 map<string, IconvProcessor>::iterator it = processors.find(encoding);
403 if (it == processors.end()) {
404 IconvProcessor processor(encoding.c_str(), ucs4_codeset);
405 it = processors.insert(make_pair(encoding, processor)).first;
409 int bytes = it->second.convert((char *)(&ucs4), 4, &out[0], 4);
416 int max_encoded_bytes(std::string const & encoding)
418 // FIXME: this information should be transferred to lib/encodings
419 // UTF8 uses at most 4 bytes to represent one UCS4 code point
420 // (see RFC 3629). RFC 2279 specifies 6 bytes, but that
421 // information is outdated, and RFC 2279 has been superseded by
423 // The CJK encodings use (different) multibyte representation as well.
424 // All other encodings encode one UCS4 code point in one byte
425 // (and can therefore only encode a subset of UCS4)
426 // Furthermore, all encodings that use shifting (like SJIS) do not work with
427 // iconv_codecvt_facet.
428 if (encoding == "UTF-8" ||
430 encoding == "EUC-TW")
432 else if (encoding == "EUC-JP")
434 else if (encoding == "ISO-2022-JP")
436 else if (encoding == "BIG5" ||
437 encoding == "EUC-KR" ||
438 encoding == "EUC-CN" ||
439 encoding == "SJIS" ||