]> git.lyx.org Git - lyx.git/blob - src/support/docstream.cpp
53d403b584cc727d2c42a6a308cdfaec3edee9da
[lyx.git] / src / support / docstream.cpp
1 /**
2  * \file docstream.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Georg Baum
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "support/docstream.h"
14 #include "support/unicode.h"
15
16 #include <cerrno>
17 #include <cstdio>
18 #include <cstring>
19 #include <iconv.h>
20 #include <locale>
21
22 using namespace std;
23
24 using lyx::ucs4_codeset;
25
26 namespace {
27
28 // We use C IO throughout this file, because the facets might be used with
29 // lyxerr in the future.
30
31
32 /// codecvt facet for conversion of UCS4 (internal representation) to UTF8
33 /// (external representation) or vice versa
34 class iconv_codecvt_facet : public codecvt<lyx::char_type, char, mbstate_t>
35 {
36         typedef codecvt<lyx::char_type, char, mbstate_t> base;
37 public:
38         /// Constructor. You have to specify with \p inout whether you want
39         /// to use this facet only for input, only for output or for both.
40         explicit iconv_codecvt_facet(string const & encoding = "UTF-8",
41                         ios_base::openmode inout = ios_base::in | ios_base::out,
42                         size_t refs = 0)
43                 : base(refs), encoding_(encoding)
44         {
45                 if (inout & ios_base::in) {
46                         in_cd_ = iconv_open(ucs4_codeset, encoding.c_str());
47                         if (in_cd_ == (iconv_t)(-1)) {
48                                 fprintf(stderr, "Error %d returned from iconv_open(in_cd_): %s\n",
49                                         errno, strerror(errno));
50                                 fflush(stderr);
51                                 throw lyx::iconv_codecvt_facet_exception();
52                         }
53                 } else
54                         in_cd_ = (iconv_t)(-1);
55                 if (inout & ios_base::out) {
56                         out_cd_ = iconv_open(encoding.c_str(), ucs4_codeset);
57                         if (out_cd_ == (iconv_t)(-1)) {
58                                 fprintf(stderr, "Error %d returned from iconv_open(out_cd_): %s\n",
59                                         errno, strerror(errno));
60                                 fflush(stderr);
61                                 throw lyx::iconv_codecvt_facet_exception();
62                         }
63                 } else
64                         out_cd_ = (iconv_t)(-1);
65         }
66 protected:
67         virtual ~iconv_codecvt_facet()
68         {
69                 if (in_cd_ != (iconv_t)(-1))
70                         if (iconv_close(in_cd_) == -1) {
71                                 fprintf(stderr, "Error %d returned from iconv_close(in_cd_): %s\n",
72                                         errno, strerror(errno));
73                                 fflush(stderr);
74                         }
75                 if (out_cd_ != (iconv_t)(-1))
76                         if (iconv_close(out_cd_) == -1) {
77                                 fprintf(stderr, "Error %d returned from iconv_close(out_cd_): %s\n",
78                                         errno, strerror(errno));
79                                 fflush(stderr);
80                         }
81         }
82         virtual result do_out(state_type &, intern_type const * from,
83                         intern_type const * from_end, intern_type const *& from_next,
84                         extern_type * to, extern_type * to_end,
85                         extern_type *& to_next) const
86         {
87 #define WORKAROUND_ICONV_BUG 1
88 #if WORKAROUND_ICONV_BUG
89                 // Due to a bug in some iconv versions, when the last char in
90                 // the buffer is a wide char, it gets truncated (see bugs 5216,
91                 // 5280, and also 5489). As a workaround, we append a null
92                 // char and then remove it from output after the conversion.
93                 intern_type * from_new = 0;
94                 if (*(from_end - 1) >= 0x80) {
95                         size_t len = from_end - from;
96                         from_new = new intern_type[len + 1];
97                         memcpy(from_new, from, len * sizeof(intern_type));
98                         from_new[len] = 0;
99                         from_end = from_new + len + 1;
100                         from = from_new;
101                 }
102 #endif
103                 size_t inbytesleft = (from_end - from) * sizeof(intern_type);
104                 size_t outbytesleft = (to_end - to) * sizeof(extern_type);
105                 from_next = from;
106                 to_next = to;
107                 result const retval = do_iconv(out_cd_,
108                                 reinterpret_cast<char const **>(&from_next),
109                                 &inbytesleft, &to_next, &outbytesleft);
110 #if WORKAROUND_ICONV_BUG
111                 // Remove from output the null char that we inserted at the end
112                 // of the input buffer in order to circumvent an iconv bug.
113                 if (from_new)
114                         --to_next;
115 #endif
116                 if (retval == base::error) {
117                         fprintf(stderr,
118                                 "Error %d returned from iconv when converting from %s to %s: %s\n",
119                                 errno, ucs4_codeset, encoding_.c_str(),
120                                 strerror(errno));
121                         fputs("Converted input:", stderr);
122                         for (intern_type const * i = from; i < from_next; ++i) {
123                                 unsigned int const c = *i;
124                                 fprintf(stderr, " 0x%04x", c);
125                         }
126                         unsigned int const c = *from_next;
127                         fprintf(stderr, "\nStopped at: 0x%04x\n", c);
128                         fputs("Unconverted input:", stderr);
129                         for (intern_type const * i = from_next + 1; i < from_end; ++i) {
130                                 unsigned int const c = *i;
131                                 fprintf(stderr, " 0x%04x", c);
132                         }
133                         fputs("\nConverted output:", stderr);
134                         for (extern_type const * i = to; i < to_next; ++i) {
135                                 // extern_type may be signed, avoid output of
136                                 // something like 0xffffffc2
137                                 unsigned int const c =
138                                         *reinterpret_cast<unsigned char const *>(i);
139                                 fprintf(stderr, " 0x%02x", c);
140                         }
141                         fputc('\n', stderr);
142                         fflush(stderr);
143                 }
144 #if WORKAROUND_ICONV_BUG
145                 delete[] from_new;
146 #endif
147                 return retval;
148         }
149         virtual result do_unshift(state_type &, extern_type * to,
150                         extern_type *, extern_type *& to_next) const
151         {
152                 // utf8 does not use shifting
153                 to_next = to;
154                 return base::noconv;
155         }
156         virtual result do_in(state_type &,
157                         extern_type const * from, extern_type const * from_end,
158                         extern_type const *& from_next,
159                         intern_type * to, intern_type * to_end,
160                         intern_type *& to_next) const
161         {
162                 size_t inbytesleft = (from_end - from) * sizeof(extern_type);
163                 size_t outbytesleft = (to_end - to) * sizeof(intern_type);
164                 from_next = from;
165                 to_next = to;
166                 result const retval = do_iconv(in_cd_, &from_next, &inbytesleft,
167                                 reinterpret_cast<char **>(&to_next),
168                                 &outbytesleft);
169                 if (retval == base::error) {
170                         fprintf(stderr,
171                                 "Error %d returned from iconv when converting from %s to %s: %s\n",
172                                 errno, encoding_.c_str(), ucs4_codeset,
173                                 strerror(errno));
174                         fputs("Converted input:", stderr);
175                         for (extern_type const * i = from; i < from_next; ++i) {
176                                 // extern_type may be signed, avoid output of
177                                 // something like 0xffffffc2
178                                 unsigned int const c =
179                                         *reinterpret_cast<unsigned char const *>(i);
180                                 fprintf(stderr, " 0x%02x", c);
181                         }
182                         unsigned int const c =
183                                 *reinterpret_cast<unsigned char const *>(from_next);
184                         fprintf(stderr, "\nStopped at: 0x%02x\n", c);
185                         fputs("Unconverted input:", stderr);
186                         for (extern_type const * i = from_next + 1; i < from_end; ++i) {
187                                 unsigned int const c =
188                                         *reinterpret_cast<unsigned char const *>(i);
189                                 fprintf(stderr, " 0x%02x", c);
190                         }
191                         fputs("\nConverted output:", stderr);
192                         for (intern_type const * i = to; i < to_next; ++i) {
193                                 unsigned int const c = *i;
194                                 fprintf(stderr, " 0x%02x", c);
195                         }
196                         fputc('\n', stderr);
197                         fflush(stderr);
198                 }
199                 return retval;
200         }
201         virtual int do_encoding() const throw()
202         {
203                 return 0;
204         }
205         virtual bool do_always_noconv() const throw()
206         {
207                 return false;
208         }
209         virtual int do_length(state_type & /*state*/, extern_type const * from,
210                         extern_type const * end, size_t max) const
211         {
212                 // The docs are a bit unclear about this method.
213                 // It seems that we should calculate the actual length of the
214                 // converted sequence, but that would not make sense, since
215                 // once could just do the conversion directly.
216                 // Therefore we just return the number of unconverted
217                 // characters, since that is the best guess we can do.
218 #if 0
219                 intern_type * to = new intern_type[max];
220                 intern_type * to_end = to + max;
221                 intern_type * to_next = to;
222                 extern_type const * from_next = from;
223                 do_in(state, from, end, from_next, to, to_end, to_next);
224                 delete[] to;
225                 return to_next - to;
226 #else
227                 size_t const length = end - from;
228                 return min(length, max);
229 #endif
230         }
231         virtual int do_max_length() const throw()
232         {
233                 // FIXME: this information should be transferred to lib/encodings
234                 // UTF8 uses at most 4 bytes to represent one UCS4 code point
235                 // (see RFC 3629). RFC 2279 specifies 6 bytes, but that
236                 // information is outdated, and RFC 2279 has been superseded by
237                 // RFC 3629.
238                 // The CJK encodings use (different) multibyte representation as well.
239                 // All other encodings encode one UCS4 code point in one byte
240                 // (and can therefore only encode a subset of UCS4)
241                 // Note that BIG5 and SJIS do not work with LaTeX (see lib/encodings). 
242                 // Furthermore, all encodings that use shifting (like SJIS) do not work with 
243                 // iconv_codecvt_facet.
244                 if (encoding_ == "UTF-8" ||
245                     encoding_ == "GB" ||
246                     encoding_ == "EUC-TW")
247                         return 4;
248                 else if (encoding_ == "EUC-JP" ||
249                          encoding_ == "ISO-2022-JP")
250                         return 3;
251                 else if (encoding_ == "BIG5" ||
252                          encoding_ == "EUC-KR" ||
253                          encoding_ == "EUC-CN" ||
254                          encoding_ == "SJIS" ||
255                          encoding_ == "GBK")
256                         return 2;
257                 else
258                         return 1;
259         }
260 private:
261         /// Do the actual conversion. The interface is equivalent to that of
262         /// iconv() (but const correct).
263         inline base::result do_iconv(iconv_t cd, char const ** from,
264                         size_t * inbytesleft, char ** to, size_t * outbytesleft) const
265         {
266                 char const * const to_start = *to;
267                 size_t converted = iconv(cd, const_cast<char ICONV_CONST **>(from),
268                                 inbytesleft, to, outbytesleft);
269                 if (converted == (size_t)(-1)) {
270                         switch(errno) {
271                         case EINVAL:
272                         case E2BIG:
273                                 return base::partial;
274                         case EILSEQ:
275                         default:
276                                 return base::error;
277                         }
278                 }
279                 if (*to == to_start)
280                         return base::noconv;
281                 return base::ok;
282         }
283         iconv_t in_cd_;
284         iconv_t out_cd_;
285         /// The narrow encoding
286         string encoding_;
287 };
288
289 } // namespace anon
290
291
292 namespace lyx {
293
294 template<class Ios>
295 void setEncoding(Ios & ios, string const & encoding, ios_base::openmode mode)
296 {
297         // We must imbue the stream before openening the file
298         locale global;
299         locale locale(global, new iconv_codecvt_facet(encoding, mode));
300         ios.imbue(locale);
301 }
302
303
304 const char * iconv_codecvt_facet_exception::what() const throw()
305 {
306         return "iconv problem in iconv_codecvt_facet initialization";
307 }
308
309
310 ifdocstream::ifdocstream(string const & encoding) : base()
311 {
312         setEncoding(*this, encoding, in);
313 }
314
315
316 ifdocstream::ifdocstream(const char* s, ios_base::openmode mode,
317                          string const & encoding)
318         : base()
319 {
320         setEncoding(*this, encoding, in);
321         open(s, mode);
322 }
323
324
325 ofdocstream::ofdocstream(): base()
326 {
327         setEncoding(*this, "UTF-8", out);
328 }
329
330
331 ofdocstream::ofdocstream(const char* s, ios_base::openmode mode,
332                          string const & encoding)
333         : base()
334 {
335         setEncoding(*this, encoding, out);
336         open(s, mode);
337 }
338
339
340 void ofdocstream::reset(string const & encoding)
341 {
342         setEncoding(*this, encoding, out);
343 }
344
345
346
347 SetEnc setEncoding(string const & encoding)
348 {
349         return SetEnc(encoding);
350 }
351
352
353 odocstream & operator<<(odocstream & os, SetEnc e)
354 {
355         if (has_facet<iconv_codecvt_facet>(os.rdbuf()->getloc())) {
356                 // This stream must be a file stream, since we never imbue
357                 // any other stream with a locale having a iconv_codecvt_facet.
358                 // Flush the stream so that all pending output is written
359                 // with the old encoding.
360                 os.flush();
361                 locale locale(os.rdbuf()->getloc(),
362                         new iconv_codecvt_facet(e.encoding, ios_base::out));
363                 // FIXME Does changing the codecvt facet of an open file
364                 // stream always work? It does with gcc 4.1, but I have read
365                 // somewhere that it does not with MSVC.
366                 // What does the standard say?
367                 os.imbue(locale);
368         }
369         return os;
370 }
371
372
373 //CHECKME: I just copied the code above, and have no idea whether it
374 //is correct... (JMarc)
375 idocstream & operator<<(idocstream & is, SetEnc e)
376 {
377         if (has_facet<iconv_codecvt_facet>(is.rdbuf()->getloc())) {
378                 // This stream must be a file stream, since we never imbue
379                 // any other stream with a locale having a iconv_codecvt_facet.
380                 // Flush the stream so that all pending output is written
381                 // with the old encoding.
382                 //is.flush();
383                 locale locale(is.rdbuf()->getloc(),
384                         new iconv_codecvt_facet(e.encoding, ios_base::in));
385                 // FIXME Does changing the codecvt facet of an open file
386                 // stream always work? It does with gcc 4.1, but I have read
387                 // somewhere that it does not with MSVC.
388                 // What does the standard say?
389                 is.imbue(locale);
390         }
391         return is;
392 }
393
394
395 #if ! defined(USE_WCHAR_T)
396 odocstream & operator<<(odocstream & os, char c)
397 {
398         os.put(c);
399         return os;
400 }
401 #endif
402
403 }
404
405 #if ! defined(USE_WCHAR_T) && defined(__GNUC__)
406 // We get undefined references to these virtual methods. This looks like
407 // a bug in gcc. The implementation here does not do anything useful, since
408 // it is overriden in iconv_codecvt_facet.
409 namespace std {
410
411 template<> codecvt<lyx::char_type, char, mbstate_t>::result
412 codecvt<lyx::char_type, char, mbstate_t>::do_out(
413         mbstate_t &, const lyx::char_type *, const lyx::char_type *,
414         const lyx::char_type *&, char *, char *, char *&) const
415 {
416         return error;
417 }
418
419
420 template<> codecvt<lyx::char_type, char, mbstate_t>::result
421 codecvt<lyx::char_type, char, mbstate_t>::do_unshift(
422         mbstate_t &, char *, char *, char *&) const
423 {
424         return error;
425 }
426
427
428 template<> codecvt<lyx::char_type, char, mbstate_t>::result
429 codecvt<lyx::char_type, char, mbstate_t>::do_in(
430         mbstate_t &, const char *, const char *, const char *&,
431         lyx::char_type *, lyx::char_type *, lyx::char_type *&) const
432 {
433         return error;
434 }
435
436
437 template<>
438 int codecvt<lyx::char_type, char, mbstate_t>::do_encoding() const throw()
439 {
440         return 0;
441 }
442
443
444 template<>
445 bool codecvt<lyx::char_type, char, mbstate_t>::do_always_noconv() const throw()
446 {
447         return true;
448 }
449
450 #if __GNUC__ == 3 && __GNUC_MINOR__ < 4
451
452 template<>
453 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
454         mbstate_t const &, const char *, const char *, size_t) const
455 {
456         return 1;
457 }
458
459 #else
460
461 template<>
462 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
463         mbstate_t &, const char *, const char *, size_t) const
464 {
465         return 1;
466 }
467
468 #endif
469
470 template<>
471 int codecvt<lyx::char_type, char, mbstate_t>::do_max_length() const throw()
472 {
473         return 4;
474 }
475
476 } // namespace std
477 #endif