]> git.lyx.org Git - lyx.git/blob - src/support/unicode.cpp
adec55299c552221a6fbb7c8aef2657e9c1df9b3
[lyx.git] / src / support / unicode.cpp
1 /**
2  * \file unicode.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  *
10  * A collection of unicode conversion functions, using iconv.
11  */
12
13 #include <config.h>
14
15 #include "support/unicode.h"
16 #include "support/debug.h"
17
18 #include <QThreadStorage>
19
20 #include <iconv.h>
21
22 #include <boost/cstdint.hpp>
23
24 #include <cerrno>
25 #include <map>
26 #include <ostream>
27 //Needed in MSVC
28 #include <string>
29
30
31 using namespace std;
32
33 namespace {
34
35 #ifdef WORDS_BIGENDIAN
36         char const * utf16_codeset = "UTF16-BE";
37 #else
38         char const * utf16_codeset = "UTF16-LE";
39 #endif
40
41 }
42
43
44 namespace lyx {
45
46 #ifdef WORDS_BIGENDIAN
47         char const * ucs4_codeset = "UCS-4BE";
48 #else
49         char const * ucs4_codeset = "UCS-4LE";
50 #endif
51
52
53 struct IconvProcessor::Handler {
54         // assumes cd is valid
55         Handler(iconv_t const cd) : cd(cd) {}
56         ~Handler() {
57                 if (iconv_close(cd) == -1)
58                         LYXERR0("Error returned from iconv_close(" << errno << ')');
59         }
60         iconv_t const cd;
61 };
62
63
64 IconvProcessor::IconvProcessor(string tocode, string fromcode)
65         : tocode_(tocode), fromcode_(fromcode)
66 {}
67
68
69 // for gcc 4.6
70 IconvProcessor::IconvProcessor(IconvProcessor && other)
71         : tocode_(move(other.tocode_)), fromcode_(move(other.fromcode_)),
72           h_(move(other.h_))
73 {}
74
75
76 bool IconvProcessor::init()
77 {
78         if (h_)
79                 return true;
80         iconv_t cd = iconv_open(tocode_.c_str(), fromcode_.c_str());
81         if (cd != (iconv_t)(-1)) {
82                 h_ = make_unique<Handler>(cd);
83                 return true;
84         }
85         lyxerr << "Error returned from iconv_open" << endl;
86         switch (errno) {
87         case EINVAL:
88                 lyxerr << "EINVAL The conversion from " << fromcode_ << " to "
89                        << tocode_ << " is not supported by the implementation."
90                        << endl;
91                 break;
92         default:
93                 lyxerr << "\tSome other error: " << errno << endl;
94                 break;
95         }
96         return false;
97 }
98
99
100 int IconvProcessor::convert(char const * buf, size_t buflen,
101                             char * outbuf, size_t maxoutsize)
102 {
103         if (buflen == 0)
104                 return 0;
105
106         if (!h_ && !init())
107                 return -1;
108
109         char ICONV_CONST * inbuf = const_cast<char ICONV_CONST *>(buf);
110         size_t inbytesleft = buflen;
111         size_t outbytesleft = maxoutsize;
112
113         int res = iconv(h_->cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
114
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);
119
120         //lyxerr << dec;
121         //lyxerr << "Inbytesleft: " << inbytesleft << endl;
122         //lyxerr << "Outbytesleft: " << outbytesleft << endl;
123
124         if (res != -1)
125                 // Everything went well.
126                 return maxoutsize - outbytesleft;
127
128         // There are some errors in the conversion
129         lyxerr << "Error returned from iconv" << endl;
130         switch (errno) {
131                 case E2BIG:
132                         lyxerr << "E2BIG  There is not sufficient room at *outbuf." << endl;
133                         break;
134                 case EILSEQ:
135                         lyxerr << "EILSEQ An invalid multibyte sequence"
136                                 << " has been encountered in the input.\n"
137                                 << "When converting from " << fromcode_
138                                 << " to " << tocode_ << ".\n";
139                         lyxerr << "Input:" << hex;
140                         for (size_t i = 0; i < buflen; ++i) {
141                                 // char may be signed, avoid output of
142                                 // something like 0xffffffc2
143                                 boost::uint32_t const b =
144                                         *reinterpret_cast<unsigned char const *>(buf + i);
145                                 lyxerr << " 0x" << (unsigned int)b;
146                         }
147                         lyxerr << dec << endl;
148                         break;
149                 case EINVAL:
150                         lyxerr << "EINVAL An incomplete multibyte sequence"
151                                 << " has been encountered in the input.\n"
152                                 << "When converting from " << fromcode_
153                                 << " to " << tocode_ << ".\n";
154                         lyxerr << "Input:" << hex;
155                         for (size_t i = 0; i < buflen; ++i) {
156                                 // char may be signed, avoid output of
157                                 // something like 0xffffffc2
158                                 boost::uint32_t const b =
159                                         *reinterpret_cast<unsigned char const *>(buf + i);
160                                 lyxerr << " 0x" << (unsigned int)b;
161                         }
162                         lyxerr << dec << endl;
163                         break;
164                 default:
165                         lyxerr << "\tSome other error: " << errno << endl;
166                         break;
167         }
168         // We got an error so we close down the conversion engine
169         h_.reset();
170         return -1;
171 }
172
173
174 namespace {
175
176
177 template<typename RetType, typename InType>
178 vector<RetType>
179 iconv_convert(IconvProcessor & processor, InType const * buf, size_t buflen)
180 {
181         if (buflen == 0)
182                 return vector<RetType>();
183
184         char const * inbuf = reinterpret_cast<char const *>(buf);
185         size_t inbytesleft = buflen * sizeof(InType);
186
187         static QThreadStorage<std::vector<char> *> static_outbuf;
188         if (!static_outbuf.hasLocalData())
189                 static_outbuf.setLocalData(new std::vector<char>(32768));
190         std::vector<char> & outbuf = *static_outbuf.localData();
191         // The number of UCS4 code points in buf is at most inbytesleft.
192         // The output encoding will use at most
193         // max_encoded_bytes(pimpl_->tocode_) per UCS4 code point.
194         size_t maxoutbufsize = max_encoded_bytes(processor.to()) * inbytesleft;
195         if (outbuf.size() < maxoutbufsize)
196                 outbuf.resize(maxoutbufsize);
197
198         int bytes = processor.convert(inbuf, inbytesleft, &outbuf[0], outbuf.size());
199         if (bytes <= 0)
200                 // Conversion failed
201                 // FIXME Maybe throw an exception and handle that in the caller?
202                 return vector<RetType>();
203
204         RetType const * tmp = reinterpret_cast<RetType const *>(&outbuf[0]);
205         return vector<RetType>(tmp, tmp + bytes / sizeof(RetType));
206 }
207
208 } // anon namespace
209
210
211 IconvProcessor & utf8ToUcs4()
212 {
213         static QThreadStorage<IconvProcessor *> processor;
214         if (!processor.hasLocalData())
215                 processor.setLocalData(new IconvProcessor(ucs4_codeset, "UTF-8"));
216         return *processor.localData();
217 }
218
219
220 vector<char_type> utf8_to_ucs4(vector<char> const & utf8str)
221 {
222         if (utf8str.empty())
223                 return vector<char_type>();
224
225         return utf8_to_ucs4(&utf8str[0], utf8str.size());
226 }
227
228
229 vector<char_type>
230 utf8_to_ucs4(char const * utf8str, size_t ls)
231 {
232         return iconv_convert<char_type>(utf8ToUcs4(), utf8str, ls);
233 }
234
235
236 vector<char_type>
237 utf16_to_ucs4(unsigned short const * s, size_t ls)
238 {
239         static QThreadStorage<IconvProcessor *> processor;
240         if (!processor.hasLocalData())
241                 processor.setLocalData(new IconvProcessor(ucs4_codeset, utf16_codeset));
242         return iconv_convert<char_type>(*processor.localData(), s, ls);
243 }
244
245
246 vector<unsigned short>
247 ucs4_to_utf16(char_type const * s, size_t ls)
248 {
249         static QThreadStorage<IconvProcessor *> processor;
250         if (!processor.hasLocalData())
251                 processor.setLocalData(new IconvProcessor(utf16_codeset, ucs4_codeset));
252         return iconv_convert<unsigned short>(*processor.localData(), s, ls);
253 }
254
255
256 IconvProcessor & ucs4ToUtf8()
257 {
258         static QThreadStorage<IconvProcessor *> processor;
259         if (!processor.hasLocalData())
260                 processor.setLocalData(new IconvProcessor("UTF-8", ucs4_codeset));
261         return *processor.localData();
262 }
263
264 namespace {
265
266 IconvProcessor & getProc(map<string, IconvProcessor> & processors,
267                          string const & encoding, bool to)
268 {
269         string const & fromcode = to ? ucs4_codeset : encoding;
270         string const & tocode = to ? encoding : ucs4_codeset;
271         map<string, IconvProcessor>::iterator const it = processors.find(encoding);
272         if (it == processors.end()) {
273                 IconvProcessor p(fromcode, tocode);
274                 return processors.insert(make_pair(encoding, move(p))).first->second;
275         } else
276                 return it->second;
277 }
278
279 } //anon namespace
280
281
282 vector<char>
283 ucs4_to_utf8(char_type c)
284 {
285         return iconv_convert<char>(ucs4ToUtf8(), &c, 1);
286 }
287
288
289 vector<char>
290 ucs4_to_utf8(vector<char_type> const & ucs4str)
291 {
292         if (ucs4str.empty())
293                 return vector<char>();
294
295         return ucs4_to_utf8(&ucs4str[0], ucs4str.size());
296 }
297
298
299 vector<char>
300 ucs4_to_utf8(char_type const * ucs4str, size_t ls)
301 {
302         return iconv_convert<char>(ucs4ToUtf8(), ucs4str, ls);
303 }
304
305
306 vector<char_type>
307 eightbit_to_ucs4(char const * s, size_t ls, string const & encoding)
308 {
309         static QThreadStorage<map<string, IconvProcessor> *> static_processors;
310         if (!static_processors.hasLocalData())
311                 static_processors.setLocalData(new map<string, IconvProcessor>);
312         map<string, IconvProcessor> & processors = *static_processors.localData();
313         IconvProcessor & processor = getProc(processors, encoding, true);
314         return iconv_convert<char_type>(processor, s, ls);
315 }
316
317
318 namespace {
319
320 map<string, IconvProcessor> & ucs4To8bitProcessors()
321 {
322         static QThreadStorage<map<string, IconvProcessor> *> processors;
323         if (!processors.hasLocalData())
324                 processors.setLocalData(new map<string, IconvProcessor>);
325         return *processors.localData();
326 }
327
328 }
329
330 vector<char>
331 ucs4_to_eightbit(char_type const * ucs4str, size_t ls, string const & encoding)
332 {
333         map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
334         IconvProcessor & processor = getProc(processors, encoding, false);
335         return iconv_convert<char>(processor, ucs4str, ls);
336 }
337
338
339 char ucs4_to_eightbit(char_type ucs4, string const & encoding)
340 {
341         map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
342         IconvProcessor & processor = getProc(processors, encoding, false);
343         char out;
344         int const bytes = processor.convert((char *)(&ucs4), 4, &out, 1);
345         if (bytes > 0)
346                 return out;
347         return 0;
348 }
349
350
351 void ucs4_to_multibytes(char_type ucs4, vector<char> & out,
352         string const & encoding)
353 {
354         static QThreadStorage<map<string, IconvProcessor> *> static_processors;
355         if (!static_processors.hasLocalData())
356                 static_processors.setLocalData(new map<string, IconvProcessor>);
357         map<string, IconvProcessor> & processors = *static_processors.localData();
358         IconvProcessor & processor = getProc(processors, encoding, false);
359         out.resize(4);
360         int bytes = processor.convert((char *)(&ucs4), 4, &out[0], 4);
361         if (bytes > 0)
362                 out.resize(bytes);
363         else
364                 out.clear();
365 }
366
367 int max_encoded_bytes(std::string const & encoding)
368 {
369         // FIXME: this information should be transferred to lib/encodings
370         // UTF8 uses at most 4 bytes to represent one UCS4 code point
371         // (see RFC 3629). RFC 2279 specifies 6 bytes, but that
372         // information is outdated, and RFC 2279 has been superseded by
373         // RFC 3629.
374         // The CJK encodings use (different) multibyte representation as well.
375         // All other encodings encode one UCS4 code point in one byte
376         // (and can therefore only encode a subset of UCS4)
377         // Furthermore, all encodings that use shifting (like SJIS) do not work with
378         // iconv_codecvt_facet.
379         if (encoding == "UTF-8" ||
380             encoding == "GB" ||
381             encoding == "EUC-TW")
382                 return 4;
383         else if (encoding == "EUC-JP")
384                 return 3;
385         else if (encoding == "ISO-2022-JP")
386                 return 8;
387         else if (encoding == "BIG5" ||
388                  encoding == "EUC-KR" ||
389                  encoding == "EUC-CN" ||
390                  encoding == "SJIS" ||
391                  encoding == "GBK")
392                 return 2;
393         else
394                 return 1;
395 }
396
397 } // namespace lyx