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