]> git.lyx.org Git - lyx.git/blob - src/support/docstream.cpp
an example for the sweave module, prepared by Gregor Gorjanc
[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
90                 // in the buffer is a wide char and the output encoding is
91                 // ISO-2022-JP and we are going to switch to another encoding,
92                 // the appropriate escape sequence for changing the character
93                 // set is not output (see bugs 5216, 5280, and also 5489).
94                 // As a workaround, we append a nul char in order to force
95                 // a switch to ASCII, and then remove it from output after
96                 // the conversion.
97                 intern_type * from_new = 0;
98                 intern_type const * from_old = from;
99                 size_t extra = 0;
100                 if (*(from_end - 1) >= 0x80 && encoding_ == "ISO-2022-JP") {
101                         size_t len = from_end - from;
102                         from_new = new intern_type[len + 1];
103                         memcpy(from_new, from, len * sizeof(intern_type));
104                         from_new[len] = 0;
105                         from_end = from_new + len + 1;
106                         from = from_new;
107                         extra = 1;
108                 }
109 #endif
110                 size_t inbytesleft = (from_end - from) * sizeof(intern_type);
111                 size_t outbytesleft = (to_end - to) * sizeof(extern_type);
112 #if WORKAROUND_ICONV_BUG
113                 outbytesleft += extra * sizeof(extern_type);
114 #endif
115                 from_next = from;
116                 to_next = to;
117                 result const retval = do_iconv(out_cd_,
118                                 reinterpret_cast<char const **>(&from_next),
119                                 &inbytesleft, &to_next, &outbytesleft);
120 #if WORKAROUND_ICONV_BUG
121                 // Remove from output the nul char that we inserted at the end
122                 // of the input buffer in order to circumvent an iconv bug.
123                 if (from_new) {
124                         --to_next;
125                         --from_next;
126                         from_next = from_old + (from_next - from);
127                         from = from_old;
128                         delete[] from_new;
129                 }
130 #endif
131                 if (retval == base::error) {
132                         fprintf(stderr,
133                                 "Error %d returned from iconv when converting from %s to %s: %s\n",
134                                 errno, ucs4_codeset, encoding_.c_str(),
135                                 strerror(errno));
136                         fputs("Converted input:", stderr);
137                         for (intern_type const * i = from; i < from_next; ++i) {
138                                 unsigned int const c = *i;
139                                 fprintf(stderr, " 0x%04x", c);
140                         }
141                         unsigned int const c = *from_next;
142                         fprintf(stderr, "\nStopped at: 0x%04x\n", c);
143                         fputs("Unconverted input:", stderr);
144                         for (intern_type const * i = from_next + 1; i < from_end; ++i) {
145                                 unsigned int const c = *i;
146                                 fprintf(stderr, " 0x%04x", c);
147                         }
148                         fputs("\nConverted output:", stderr);
149                         for (extern_type const * i = to; i < to_next; ++i) {
150                                 // extern_type may be signed, avoid output of
151                                 // something like 0xffffffc2
152                                 unsigned int const c =
153                                         *reinterpret_cast<unsigned char const *>(i);
154                                 fprintf(stderr, " 0x%02x", c);
155                         }
156                         fputc('\n', stderr);
157                         fflush(stderr);
158                 }
159                 return retval;
160         }
161         virtual result do_unshift(state_type &, extern_type * to,
162                         extern_type *, extern_type *& to_next) const
163         {
164                 // utf8 does not use shifting
165                 to_next = to;
166                 return base::noconv;
167         }
168         virtual result do_in(state_type &,
169                         extern_type const * from, extern_type const * from_end,
170                         extern_type const *& from_next,
171                         intern_type * to, intern_type * to_end,
172                         intern_type *& to_next) const
173         {
174                 size_t inbytesleft = (from_end - from) * sizeof(extern_type);
175                 size_t outbytesleft = (to_end - to) * sizeof(intern_type);
176                 from_next = from;
177                 to_next = to;
178                 result const retval = do_iconv(in_cd_, &from_next, &inbytesleft,
179                                 reinterpret_cast<char **>(&to_next),
180                                 &outbytesleft);
181                 if (retval == base::error) {
182                         fprintf(stderr,
183                                 "Error %d returned from iconv when converting from %s to %s: %s\n",
184                                 errno, encoding_.c_str(), ucs4_codeset,
185                                 strerror(errno));
186                         fputs("Converted input:", stderr);
187                         for (extern_type const * i = from; i < from_next; ++i) {
188                                 // extern_type may be signed, avoid output of
189                                 // something like 0xffffffc2
190                                 unsigned int const c =
191                                         *reinterpret_cast<unsigned char const *>(i);
192                                 fprintf(stderr, " 0x%02x", c);
193                         }
194                         unsigned int const c =
195                                 *reinterpret_cast<unsigned char const *>(from_next);
196                         fprintf(stderr, "\nStopped at: 0x%02x\n", c);
197                         fputs("Unconverted input:", stderr);
198                         for (extern_type const * i = from_next + 1; i < from_end; ++i) {
199                                 unsigned int const c =
200                                         *reinterpret_cast<unsigned char const *>(i);
201                                 fprintf(stderr, " 0x%02x", c);
202                         }
203                         fputs("\nConverted output:", stderr);
204                         for (intern_type const * i = to; i < to_next; ++i) {
205                                 unsigned int const c = *i;
206                                 fprintf(stderr, " 0x%02x", c);
207                         }
208                         fputc('\n', stderr);
209                         fflush(stderr);
210                 }
211                 return retval;
212         }
213         virtual int do_encoding() const throw()
214         {
215                 return 0;
216         }
217         virtual bool do_always_noconv() const throw()
218         {
219                 return false;
220         }
221         virtual int do_length(state_type & /*state*/, extern_type const * from,
222                         extern_type const * end, size_t max) const
223         {
224                 // The docs are a bit unclear about this method.
225                 // It seems that we should calculate the actual length of the
226                 // converted sequence, but that would not make sense, since
227                 // once could just do the conversion directly.
228                 // Therefore we just return the number of unconverted
229                 // characters, since that is the best guess we can do.
230 #if 0
231                 intern_type * to = new intern_type[max];
232                 intern_type * to_end = to + max;
233                 intern_type * to_next = to;
234                 extern_type const * from_next = from;
235                 do_in(state, from, end, from_next, to, to_end, to_next);
236                 delete[] to;
237                 return to_next - to;
238 #else
239                 size_t const length = end - from;
240                 return min(length, max);
241 #endif
242         }
243         virtual int do_max_length() const throw()
244         {
245                 // FIXME: this information should be transferred to lib/encodings
246                 // UTF8 uses at most 4 bytes to represent one UCS4 code point
247                 // (see RFC 3629). RFC 2279 specifies 6 bytes, but that
248                 // information is outdated, and RFC 2279 has been superseded by
249                 // RFC 3629.
250                 // The CJK encodings use (different) multibyte representation as well.
251                 // All other encodings encode one UCS4 code point in one byte
252                 // (and can therefore only encode a subset of UCS4)
253                 // Note that BIG5 and SJIS do not work with LaTeX (see lib/encodings). 
254                 // Furthermore, all encodings that use shifting (like SJIS) do not work with 
255                 // iconv_codecvt_facet.
256                 if (encoding_ == "UTF-8" ||
257                     encoding_ == "GB" ||
258                     encoding_ == "EUC-TW")
259                         return 4;
260                 else if (encoding_ == "EUC-JP")
261                         return 3;
262                 else if (encoding_ == "ISO-2022-JP")
263                         return 8;
264                 else if (encoding_ == "BIG5" ||
265                          encoding_ == "EUC-KR" ||
266                          encoding_ == "EUC-CN" ||
267                          encoding_ == "SJIS" ||
268                          encoding_ == "GBK")
269                         return 2;
270                 else
271                         return 1;
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                 // Flush the stream so that all pending output is written
380                 // with the old encoding.
381                 os.flush();
382                 locale locale(os.rdbuf()->getloc(),
383                         new iconv_codecvt_facet(e.encoding, ios_base::out));
384                 // FIXME Does changing the codecvt facet of an open file
385                 // stream always work? It does with gcc 4.1, but I have read
386                 // somewhere that it does not with MSVC.
387                 // What does the standard say?
388                 os.imbue(locale);
389         }
390         return os;
391 }
392
393
394 //CHECKME: I just copied the code above, and have no idea whether it
395 //is correct... (JMarc)
396 idocstream & operator<<(idocstream & is, SetEnc e)
397 {
398         if (has_facet<iconv_codecvt_facet>(is.rdbuf()->getloc())) {
399                 // This stream must be a file stream, since we never imbue
400                 // any other stream with a locale having a iconv_codecvt_facet.
401                 // Flush the stream so that all pending output is written
402                 // with the old encoding.
403                 //is.flush();
404                 locale locale(is.rdbuf()->getloc(),
405                         new iconv_codecvt_facet(e.encoding, ios_base::in));
406                 // FIXME Does changing the codecvt facet of an open file
407                 // stream always work? It does with gcc 4.1, but I have read
408                 // somewhere that it does not with MSVC.
409                 // What does the standard say?
410                 is.imbue(locale);
411         }
412         return is;
413 }
414
415
416 #if ! defined(USE_WCHAR_T)
417 odocstream & operator<<(odocstream & os, char c)
418 {
419         os.put(c);
420         return os;
421 }
422 #endif
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 #if __GNUC__ == 3 && __GNUC_MINOR__ < 4
472
473 template<>
474 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
475         mbstate_t const &, const char *, const char *, size_t) const
476 {
477         return 1;
478 }
479
480 #else
481
482 template<>
483 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
484         mbstate_t &, const char *, const char *, size_t) const
485 {
486         return 1;
487 }
488
489 #endif
490
491 template<>
492 int codecvt<lyx::char_type, char, mbstate_t>::do_max_length() const throw()
493 {
494         return 4;
495 }
496
497 } // namespace std
498 #endif