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