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