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