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