]> git.lyx.org Git - features.git/blob - src/support/unicode.cpp
Remove support for gcc 4.6
[features.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_(move(tocode)), fromcode_(move(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                 case EINVAL:
129                         lyxerr << (errno == EINVAL
130                                    ? "EINVAL An incomplete "
131                                    : "EILSEQ An invalid ")
132                                 << "multibyte sequence has been encountered in the input.\n"
133                                 << "When converting from " << fromcode_
134                                 << " to " << tocode_ << ".\n";
135                         lyxerr << "Input:" << hex;
136                         for (size_t i = 0; i < buflen; ++i) {
137                                 // char may be signed, avoid output of
138                                 // something like 0xffffffc2
139                                 boost::uint32_t const b =
140                                         *reinterpret_cast<unsigned char const *>(buf + i);
141                                 lyxerr << " 0x" << (unsigned int)b;
142                         }
143                         lyxerr << dec << endl;
144                         break;
145                 default:
146                         lyxerr << "\tSome other error: " << errno << endl;
147                         break;
148         }
149         // We got an error so we close down the conversion engine
150         h_.reset();
151         return -1;
152 }
153
154
155 namespace {
156
157
158 template<typename RetType, typename InType>
159 vector<RetType>
160 iconv_convert(IconvProcessor & processor, InType const * buf, size_t buflen)
161 {
162         if (buflen == 0)
163                 return vector<RetType>();
164
165         char const * inbuf = reinterpret_cast<char const *>(buf);
166         size_t inbytesleft = buflen * sizeof(InType);
167
168         static QThreadStorage<std::vector<char> *> static_outbuf;
169         if (!static_outbuf.hasLocalData())
170                 static_outbuf.setLocalData(new std::vector<char>(32768));
171         std::vector<char> & outbuf = *static_outbuf.localData();
172         // The number of UCS4 code points in buf is at most inbytesleft.
173         // The output encoding will use at most
174         // max_encoded_bytes(pimpl_->tocode_) per UCS4 code point.
175         size_t maxoutbufsize = max_encoded_bytes(processor.to()) * inbytesleft;
176         if (outbuf.size() < maxoutbufsize)
177                 outbuf.resize(maxoutbufsize);
178
179         int bytes = processor.convert(inbuf, inbytesleft, &outbuf[0], outbuf.size());
180         if (bytes <= 0)
181                 // Conversion failed
182                 // FIXME Maybe throw an exception and handle that in the caller?
183                 return vector<RetType>();
184
185         RetType const * tmp = reinterpret_cast<RetType const *>(&outbuf[0]);
186         return vector<RetType>(tmp, tmp + bytes / sizeof(RetType));
187 }
188
189 } // namespace
190
191
192 IconvProcessor & utf8ToUcs4()
193 {
194         static QThreadStorage<IconvProcessor *> processor;
195         if (!processor.hasLocalData())
196                 processor.setLocalData(new IconvProcessor(ucs4_codeset, "UTF-8"));
197         return *processor.localData();
198 }
199
200
201 vector<char_type> utf8_to_ucs4(vector<char> const & utf8str)
202 {
203         if (utf8str.empty())
204                 return vector<char_type>();
205
206         return utf8_to_ucs4(&utf8str[0], utf8str.size());
207 }
208
209
210 vector<char_type>
211 utf8_to_ucs4(char const * utf8str, size_t ls)
212 {
213         return iconv_convert<char_type>(utf8ToUcs4(), utf8str, ls);
214 }
215
216
217 vector<char_type>
218 utf16_to_ucs4(unsigned short const * s, size_t ls)
219 {
220         static QThreadStorage<IconvProcessor *> processor;
221         if (!processor.hasLocalData())
222                 processor.setLocalData(new IconvProcessor(ucs4_codeset, utf16_codeset));
223         return iconv_convert<char_type>(*processor.localData(), s, ls);
224 }
225
226
227 vector<unsigned short>
228 ucs4_to_utf16(char_type const * s, size_t ls)
229 {
230         static QThreadStorage<IconvProcessor *> processor;
231         if (!processor.hasLocalData())
232                 processor.setLocalData(new IconvProcessor(utf16_codeset, ucs4_codeset));
233         return iconv_convert<unsigned short>(*processor.localData(), s, ls);
234 }
235
236
237 IconvProcessor & ucs4ToUtf8()
238 {
239         static QThreadStorage<IconvProcessor *> processor;
240         if (!processor.hasLocalData())
241                 processor.setLocalData(new IconvProcessor("UTF-8", ucs4_codeset));
242         return *processor.localData();
243 }
244
245 namespace {
246
247 IconvProcessor & getProc(map<string, IconvProcessor> & processors,
248                          string const & encoding, bool to)
249 {
250         string const & fromcode = to ? ucs4_codeset : encoding;
251         string const & tocode = to ? encoding : ucs4_codeset;
252         map<string, IconvProcessor>::iterator const it = processors.find(encoding);
253         if (it == processors.end()) {
254                 IconvProcessor p(fromcode, tocode);
255                 return processors.insert(make_pair(encoding, move(p))).first->second;
256         } else
257                 return it->second;
258 }
259
260 } // namespace
261
262
263 vector<char>
264 ucs4_to_utf8(char_type c)
265 {
266         return iconv_convert<char>(ucs4ToUtf8(), &c, 1);
267 }
268
269
270 vector<char>
271 ucs4_to_utf8(vector<char_type> const & ucs4str)
272 {
273         if (ucs4str.empty())
274                 return vector<char>();
275
276         return ucs4_to_utf8(&ucs4str[0], ucs4str.size());
277 }
278
279
280 vector<char>
281 ucs4_to_utf8(char_type const * ucs4str, size_t ls)
282 {
283         return iconv_convert<char>(ucs4ToUtf8(), ucs4str, ls);
284 }
285
286
287 vector<char_type>
288 eightbit_to_ucs4(char const * s, size_t ls, string const & encoding)
289 {
290         static QThreadStorage<map<string, IconvProcessor> *> static_processors;
291         if (!static_processors.hasLocalData())
292                 static_processors.setLocalData(new map<string, IconvProcessor>);
293         map<string, IconvProcessor> & processors = *static_processors.localData();
294         IconvProcessor & processor = getProc(processors, encoding, true);
295         return iconv_convert<char_type>(processor, s, ls);
296 }
297
298
299 namespace {
300
301 map<string, IconvProcessor> & ucs4To8bitProcessors()
302 {
303         static QThreadStorage<map<string, IconvProcessor> *> processors;
304         if (!processors.hasLocalData())
305                 processors.setLocalData(new map<string, IconvProcessor>);
306         return *processors.localData();
307 }
308
309 } // namespace
310
311 vector<char>
312 ucs4_to_eightbit(char_type const * ucs4str, size_t ls, string const & encoding)
313 {
314         map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
315         IconvProcessor & processor = getProc(processors, encoding, false);
316         return iconv_convert<char>(processor, ucs4str, ls);
317 }
318
319
320 char ucs4_to_eightbit(char_type ucs4, string const & encoding)
321 {
322         map<string, IconvProcessor> & processors(ucs4To8bitProcessors());
323         IconvProcessor & processor = getProc(processors, encoding, false);
324         char out;
325         int const bytes = processor.convert((char *)(&ucs4), 4, &out, 1);
326         if (bytes > 0)
327                 return out;
328         return 0;
329 }
330
331
332 void ucs4_to_multibytes(char_type ucs4, vector<char> & out,
333         string const & encoding)
334 {
335         static QThreadStorage<map<string, IconvProcessor> *> static_processors;
336         if (!static_processors.hasLocalData())
337                 static_processors.setLocalData(new map<string, IconvProcessor>);
338         map<string, IconvProcessor> & processors = *static_processors.localData();
339         IconvProcessor & processor = getProc(processors, encoding, false);
340         out.resize(4);
341         int bytes = processor.convert((char *)(&ucs4), 4, &out[0], 4);
342         if (bytes > 0)
343                 out.resize(bytes);
344         else
345                 out.clear();
346 }
347
348 int max_encoded_bytes(std::string const & encoding)
349 {
350         // FIXME: this information should be transferred to lib/encodings
351         // UTF8 uses at most 4 bytes to represent one UCS4 code point
352         // (see RFC 3629). RFC 2279 specifies 6 bytes, but that
353         // information is outdated, and RFC 2279 has been superseded by
354         // RFC 3629.
355         // The CJK encodings use (different) multibyte representation as well.
356         // All other encodings encode one UCS4 code point in one byte
357         // (and can therefore only encode a subset of UCS4)
358         // Furthermore, all encodings that use shifting (like SJIS) do not work with
359         // iconv_codecvt_facet.
360         if (encoding == "UTF-8" ||
361             encoding == "GB" ||
362             encoding == "EUC-TW")
363                 return 4;
364         else if (encoding == "EUC-JP")
365                 return 3;
366         else if (encoding == "ISO-2022-JP")
367                 return 8;
368         else if (encoding == "BIG5" ||
369                  encoding == "EUC-KR" ||
370                  encoding == "EUC-CN" ||
371                  encoding == "SJIS" ||
372                  encoding == "GBK")
373                 return 2;
374         else
375                 return 1;
376 }
377
378 } // namespace lyx