]> git.lyx.org Git - lyx.git/blob - src/support/unicode.cpp
RefChanger
[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 bool IconvProcessor::init()
70 {
71         if (h_)
72                 return true;
73         iconv_t cd = iconv_open(tocode_.c_str(), fromcode_.c_str());
74         if (cd != (iconv_t)(-1)) {
75                 h_ = make_unique<Handler>(cd);
76                 return true;
77         }
78         lyxerr << "Error returned from iconv_open" << endl;
79         switch (errno) {
80         case EINVAL:
81                 lyxerr << "EINVAL The conversion from " << fromcode_ << " to "
82                        << tocode_ << " is not supported by the implementation."
83                        << endl;
84                 break;
85         default:
86                 lyxerr << "\tSome other error: " << errno << endl;
87                 break;
88         }
89         return false;
90 }
91
92
93 int IconvProcessor::convert(char const * buf, size_t buflen,
94                             char * outbuf, size_t maxoutsize)
95 {
96         if (buflen == 0)
97                 return 0;
98
99         if (!h_ && !init())
100                 return -1;
101
102         char ICONV_CONST * inbuf = const_cast<char ICONV_CONST *>(buf);
103         size_t inbytesleft = buflen;
104         size_t outbytesleft = maxoutsize;
105
106         int res = iconv(h_->cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
107
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);
112
113         //lyxerr << dec;
114         //lyxerr << "Inbytesleft: " << inbytesleft << endl;
115         //lyxerr << "Outbytesleft: " << outbytesleft << endl;
116
117         if (res != -1)
118                 // Everything went well.
119                 return maxoutsize - outbytesleft;
120
121         // There are some errors in the conversion
122         lyxerr << "Error returned from iconv" << endl;
123         switch (errno) {
124                 case E2BIG:
125                         lyxerr << "E2BIG  There is not sufficient room at *outbuf." << endl;
126                         break;
127                 case EILSEQ:
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;
139                         }
140                         lyxerr << dec << endl;
141                         break;
142                 case EINVAL:
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;
154                         }
155                         lyxerr << dec << endl;
156                         break;
157                 default:
158                         lyxerr << "\tSome other error: " << errno << endl;
159                         break;
160         }
161         // We got an error so we close down the conversion engine
162         h_.reset();
163         return -1;
164 }
165
166
167 namespace {
168
169
170 template<typename RetType, typename InType>
171 vector<RetType>
172 iconv_convert(IconvProcessor & processor, InType const * buf, size_t buflen)
173 {
174         if (buflen == 0)
175                 return vector<RetType>();
176
177         char const * inbuf = reinterpret_cast<char const *>(buf);
178         size_t inbytesleft = buflen * sizeof(InType);
179
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);
190
191         int bytes = processor.convert(inbuf, inbytesleft, &outbuf[0], outbuf.size());
192         if (bytes <= 0)
193                 // Conversion failed
194                 // FIXME Maybe throw an exception and handle that in the caller?
195                 return vector<RetType>();
196
197         RetType const * tmp = reinterpret_cast<RetType const *>(&outbuf[0]);
198         return vector<RetType>(tmp, tmp + bytes / sizeof(RetType));
199 }
200
201 } // anon namespace
202
203
204 IconvProcessor & utf8ToUcs4()
205 {
206         static QThreadStorage<IconvProcessor *> processor;
207         if (!processor.hasLocalData())
208                 processor.setLocalData(new IconvProcessor(ucs4_codeset, "UTF-8"));
209         return *processor.localData();
210 }
211
212
213 vector<char_type> utf8_to_ucs4(vector<char> const & utf8str)
214 {
215         if (utf8str.empty())
216                 return vector<char_type>();
217
218         return utf8_to_ucs4(&utf8str[0], utf8str.size());
219 }
220
221
222 vector<char_type>
223 utf8_to_ucs4(char const * utf8str, size_t ls)
224 {
225         return iconv_convert<char_type>(utf8ToUcs4(), utf8str, ls);
226 }
227
228
229 vector<char_type>
230 utf16_to_ucs4(unsigned short const * s, size_t ls)
231 {
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);
236 }
237
238
239 vector<unsigned short>
240 ucs4_to_utf16(char_type const * s, size_t ls)
241 {
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);
246 }
247
248
249 IconvProcessor & ucs4ToUtf8()
250 {
251         static QThreadStorage<IconvProcessor *> processor;
252         if (!processor.hasLocalData())
253                 processor.setLocalData(new IconvProcessor("UTF-8", ucs4_codeset));
254         return *processor.localData();
255 }
256
257 namespace {
258
259 IconvProcessor & getProc(map<string, IconvProcessor> & processors,
260                          string const & encoding, bool to)
261 {
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;
268         } else
269                 return it->second;
270 }
271
272 } //anon namespace
273
274
275 vector<char>
276 ucs4_to_utf8(char_type c)
277 {
278         return iconv_convert<char>(ucs4ToUtf8(), &c, 1);
279 }
280
281
282 vector<char>
283 ucs4_to_utf8(vector<char_type> const & ucs4str)
284 {
285         if (ucs4str.empty())
286                 return vector<char>();
287
288         return ucs4_to_utf8(&ucs4str[0], ucs4str.size());
289 }
290
291
292 vector<char>
293 ucs4_to_utf8(char_type const * ucs4str, size_t ls)
294 {
295         return iconv_convert<char>(ucs4ToUtf8(), ucs4str, ls);
296 }
297
298
299 vector<char_type>
300 eightbit_to_ucs4(char const * s, size_t ls, string const & encoding)
301 {
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);
308 }
309
310
311 namespace {
312
313 map<string, IconvProcessor> & ucs4To8bitProcessors()
314 {
315         static QThreadStorage<map<string, IconvProcessor> *> processors;
316         if (!processors.hasLocalData())
317                 processors.setLocalData(new map<string, IconvProcessor>);
318         return *processors.localData();
319 }
320
321 }
322
323 vector<char>
324 ucs4_to_eightbit(char_type const * ucs4str, size_t ls, string const & encoding)
325 {
326         map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
327         IconvProcessor & processor = getProc(processors, encoding, false);
328         return iconv_convert<char>(processor, ucs4str, ls);
329 }
330
331
332 char ucs4_to_eightbit(char_type ucs4, string const & encoding)
333 {
334         map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
335         IconvProcessor & processor = getProc(processors, encoding, false);
336         char out;
337         int const bytes = processor.convert((char *)(&ucs4), 4, &out, 1);
338         if (bytes > 0)
339                 return out;
340         return 0;
341 }
342
343
344 void ucs4_to_multibytes(char_type ucs4, vector<char> & out,
345         string const & encoding)
346 {
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);
352         out.resize(4);
353         int bytes = processor.convert((char *)(&ucs4), 4, &out[0], 4);
354         if (bytes > 0)
355                 out.resize(bytes);
356         else
357                 out.clear();
358 }
359
360 int max_encoded_bytes(std::string const & encoding)
361 {
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
366         // RFC 3629.
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" ||
373             encoding == "GB" ||
374             encoding == "EUC-TW")
375                 return 4;
376         else if (encoding == "EUC-JP")
377                 return 3;
378         else if (encoding == "ISO-2022-JP")
379                 return 8;
380         else if (encoding == "BIG5" ||
381                  encoding == "EUC-KR" ||
382                  encoding == "EUC-CN" ||
383                  encoding == "SJIS" ||
384                  encoding == "GBK")
385                 return 2;
386         else
387                 return 1;
388 }
389
390 } // namespace lyx