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