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