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