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