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
truename() const36 string_type numpunct<lyx::char_type>::truename() const
37 {
38 return lyx::from_ascii(numpunct<char>::truename());
39 }
40
falsename() const41 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.
iconv_codecvt_facet(string const & encoding="UTF-8",ios_base::openmode inout=ios_base::in|ios_base::out,size_t refs=0)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 }
encoding() const91 string const & encoding() const { return encoding_; }
92 protected:
~iconv_codecvt_facet()93 virtual ~iconv_codecvt_facet()
94 {
95 if (in_cd_ != (iconv_t)(-1))
96 if (iconv_close(in_cd_) == -1) {
97 fprintf(stderr, "Error %d returned from iconv_close(in_cd_): %s\n",
98 errno, strerror(errno));
99 fflush(stderr);
100 }
101 if (out_cd_ != (iconv_t)(-1))
102 if (iconv_close(out_cd_) == -1) {
103 fprintf(stderr, "Error %d returned from iconv_close(out_cd_): %s\n",
104 errno, strerror(errno));
105 fflush(stderr);
106 }
107 }
do_out(state_type &,intern_type const * from,intern_type const * from_end,intern_type const * & from_next,extern_type * to,extern_type * to_end,extern_type * & to_next) const108 virtual result do_out(state_type &, intern_type const * from,
109 intern_type const * from_end, intern_type const *& from_next,
110 extern_type * to, extern_type * to_end,
111 extern_type *& to_next) const
112 {
113 #define WORKAROUND_ICONV_BUG 1
114 #if WORKAROUND_ICONV_BUG
115 // Due to a bug in some iconv versions, when the last char
116 // in the buffer is a wide char and the output encoding is
117 // ISO-2022-JP and we are going to switch to another encoding,
118 // the appropriate escape sequence for changing the character
119 // set is not output (see bugs 5216, 5280, and also 5489).
120 // As a workaround, we append a nul char in order to force
121 // a switch to ASCII, and then remove it from output after
122 // the conversion.
123 intern_type * from_new = 0;
124 intern_type const * from_old = from;
125 size_t extra = 0;
126 if (*(from_end - 1) >= 0x80 && encoding_ == "ISO-2022-JP") {
127 size_t len = from_end - from;
128 from_new = new intern_type[len + 1];
129 memcpy(from_new, from, len * sizeof(intern_type));
130 from_new[len] = 0;
131 from_end = from_new + len + 1;
132 from = from_new;
133 extra = 1;
134 }
135 #endif
136 size_t inbytesleft = (from_end - from) * sizeof(intern_type);
137 size_t outbytesleft = (to_end - to) * sizeof(extern_type);
138 #if WORKAROUND_ICONV_BUG
139 outbytesleft += extra * sizeof(extern_type);
140 #endif
141 from_next = from;
142 to_next = to;
143 result const retval = do_iconv(out_cd_,
144 reinterpret_cast<char const **>(&from_next),
145 &inbytesleft, &to_next, &outbytesleft);
146 #if WORKAROUND_ICONV_BUG
147 // Remove from output the nul char that we inserted at the end
148 // of the input buffer in order to circumvent an iconv bug.
149 if (from_new) {
150 --to_next;
151 --from_next;
152 from_next = from_old + (from_next - from);
153 from = from_old;
154 delete[] from_new;
155 }
156 #endif
157 if (retval == base::error) {
158 fprintf(stderr,
159 "Error %d returned from iconv when converting from %s to %s: %s\n",
160 errno, ucs4_codeset, encoding_.c_str(),
161 strerror(errno));
162 fputs("Converted input:", stderr);
163 for (intern_type const * i = from; i < from_next; ++i) {
164 unsigned int const c = *i;
165 fprintf(stderr, " 0x%04x", c);
166 }
167 unsigned int const c = *from_next;
168 fprintf(stderr, "\nStopped at: 0x%04x\n", c);
169 fputs("Unconverted input:", stderr);
170 for (intern_type const * i = from_next + 1; i < from_end; ++i) {
171 unsigned int const c = *i;
172 fprintf(stderr, " 0x%04x", c);
173 }
174 fputs("\nConverted output:", stderr);
175 for (extern_type const * i = to; i < to_next; ++i) {
176 // extern_type may be signed, avoid output of
177 // something like 0xffffffc2
178 unsigned int const c =
179 *reinterpret_cast<unsigned char const *>(i);
180 fprintf(stderr, " 0x%02x", c);
181 }
182 fputc('\n', stderr);
183 fflush(stderr);
184 }
185 return retval;
186 }
do_unshift(state_type &,extern_type * to,extern_type *,extern_type * & to_next) const187 virtual result do_unshift(state_type &, extern_type * to,
188 extern_type *, extern_type *& to_next) const
189 {
190 // utf8 does not use shifting
191 to_next = to;
192 return base::noconv;
193 }
do_in(state_type &,extern_type const * from,extern_type const * from_end,extern_type const * & from_next,intern_type * to,intern_type * to_end,intern_type * & to_next) const194 virtual result do_in(state_type &,
195 extern_type const * from, extern_type const * from_end,
196 extern_type const *& from_next,
197 intern_type * to, intern_type * to_end,
198 intern_type *& to_next) const
199 {
200 size_t inbytesleft = (from_end - from) * sizeof(extern_type);
201 size_t outbytesleft = (to_end - to) * sizeof(intern_type);
202 from_next = from;
203 to_next = to;
204 result const retval = do_iconv(in_cd_, &from_next, &inbytesleft,
205 reinterpret_cast<char **>(&to_next),
206 &outbytesleft);
207 if (retval == base::error) {
208 fprintf(stderr,
209 "Error %d returned from iconv when converting from %s to %s: %s\n",
210 errno, encoding_.c_str(), ucs4_codeset,
211 strerror(errno));
212 fputs("Converted input:", stderr);
213 for (extern_type const * i = from; i < from_next; ++i) {
214 // extern_type may be signed, avoid output of
215 // something like 0xffffffc2
216 unsigned int const c =
217 *reinterpret_cast<unsigned char const *>(i);
218 fprintf(stderr, " 0x%02x", c);
219 }
220 unsigned int const c =
221 *reinterpret_cast<unsigned char const *>(from_next);
222 fprintf(stderr, "\nStopped at: 0x%02x\n", c);
223 fputs("Unconverted input:", stderr);
224 for (extern_type const * i = from_next + 1; i < from_end; ++i) {
225 unsigned int const c =
226 *reinterpret_cast<unsigned char const *>(i);
227 fprintf(stderr, " 0x%02x", c);
228 }
229 fputs("\nConverted output:", stderr);
230 for (intern_type const * i = to; i < to_next; ++i) {
231 unsigned int const c = *i;
232 fprintf(stderr, " 0x%02x", c);
233 }
234 fputc('\n', stderr);
235 fflush(stderr);
236 }
237 return retval;
238 }
do_encoding() const239 virtual int do_encoding() const throw()
240 {
241 return 0;
242 }
do_always_noconv() const243 virtual bool do_always_noconv() const throw()
244 {
245 return false;
246 }
do_length(state_type &,extern_type const * from,extern_type const * end,size_t max) const247 virtual int do_length(state_type & /*state*/, extern_type const * from,
248 extern_type const * end, size_t max) const
249 {
250 // The docs are a bit unclear about this method.
251 // It seems that we should calculate the actual length of the
252 // converted sequence, but that would not make sense, since
253 // once could just do the conversion directly.
254 // Therefore we just return the number of unconverted
255 // characters, since that is the best guess we can do.
256 #if 0
257 intern_type * to = new intern_type[max];
258 intern_type * to_end = to + max;
259 intern_type * to_next = to;
260 extern_type const * from_next = from;
261 do_in(state, from, end, from_next, to, to_end, to_next);
262 delete[] to;
263 return to_next - to;
264 #else
265 size_t const length = end - from;
266 return min(length, max);
267 #endif
268 }
do_max_length() const269 virtual int do_max_length() const throw()
270 {
271 return lyx::max_encoded_bytes(encoding_);
272 }
273 private:
274 /// Do the actual conversion. The interface is equivalent to that of
275 /// iconv() (but const correct).
do_iconv(iconv_t cd,char const ** from,size_t * inbytesleft,char ** to,size_t * outbytesleft) const276 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
311
312
313 namespace lyx {
314
315 template<class Ios>
setEncoding(Ios & ios,string const & encoding,ios_base::openmode mode)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
what() const325 const char * iconv_codecvt_facet_exception::what() const throw()
326 {
327 return "iconv problem in iconv_codecvt_facet initialization";
328 }
329
330
ifdocstream()331 ifdocstream::ifdocstream() : base()
332 {
333 setEncoding(*this, "UTF-8", in);
334 }
335
336
ifdocstream(SetEnc const & enc)337 ifdocstream::ifdocstream(SetEnc const & enc) : base()
338 {
339 setEncoding(*this, enc.encoding, in);
340 }
341
342
ifdocstream(const char * s,ios_base::openmode mode,string const & encoding)343 ifdocstream::ifdocstream(const char* s, ios_base::openmode mode,
344 string const & encoding)
345 : base()
346 {
347 setEncoding(*this, encoding, in);
348 open(s, mode);
349 }
350
351
ofdocstream()352 ofdocstream::ofdocstream(): base()
353 {
354 setEncoding(*this, "UTF-8", out);
355 }
356
357
ofdocstream(SetEnc const & enc)358 ofdocstream::ofdocstream(SetEnc const & enc) : base()
359 {
360 setEncoding(*this, enc.encoding, out);
361 }
362
363
ofdocstream(const char * s,ios_base::openmode mode,string const & encoding)364 ofdocstream::ofdocstream(const char* s, ios_base::openmode mode,
365 string const & encoding)
366 : base()
367 {
368 setEncoding(*this, encoding, out);
369 open(s, mode);
370 }
371
372
reset(string const & encoding)373 void ofdocstream::reset(string const & encoding)
374 {
375 setEncoding(*this, encoding, out);
376 }
377
378
379
setEncoding(string const & encoding)380 SetEnc setEncoding(string const & encoding)
381 {
382 return SetEnc(encoding);
383 }
384
385
operator <<(odocstream & os,SetEnc e)386 odocstream & operator<<(odocstream & os, SetEnc e)
387 {
388 if (has_facet<iconv_codecvt_facet>(os.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 iconv_codecvt_facet const & facet =
392 use_facet<iconv_codecvt_facet>(os.rdbuf()->getloc());
393
394 // FIXME Changing the codecvt facet of an open file is allowed,
395 // but unsafe for facets that use internal state (see the thread
396 // "iostreams: Does imbue() need to be called before open()?"
397 // in comp.std.c++.
398 // Currently it seems to work with gcc and MSVC, but not with
399 // clang on OS X.
400 // Avoid imbueing with the same encoding again if possible.
401 if (facet.encoding() == e.encoding)
402 return os;
403
404 // Flush the stream so that all pending output is written
405 // with the old encoding.
406 os.flush();
407
408 locale locale(os.rdbuf()->getloc(),
409 new iconv_codecvt_facet(e.encoding, ios_base::out));
410 os.imbue(locale);
411 }
412 return os;
413 }
414
415
operator <<(idocstream & is,SetEnc e)416 idocstream & operator<<(idocstream & is, SetEnc e)
417 {
418 if (has_facet<iconv_codecvt_facet>(is.rdbuf()->getloc())) {
419 // This stream must be a file stream, since we never imbue
420 // any other stream with a locale having a iconv_codecvt_facet.
421 iconv_codecvt_facet const & facet =
422 use_facet<iconv_codecvt_facet>(is.rdbuf()->getloc());
423
424 // FIXME Changing the codecvt facet of an open file is allowed,
425 // but unsafe for facets that use internal state (see the thread
426 // "iostreams: Does imbue() need to be called before open()?"
427 // in comp.std.c++.
428 // Currently it seems to work with gcc and MSVC, but not with
429 // clang on OS X.
430 // Avoid imbueing with the same encoding again if possible.
431 if (facet.encoding() == e.encoding)
432 return is;
433
434 locale locale(is.rdbuf()->getloc(),
435 new iconv_codecvt_facet(e.encoding, ios_base::in));
436 is.imbue(locale);
437 }
438 return is;
439 }
440
441
442 #if ! defined(USE_WCHAR_T)
operator <<(odocstream & os,char c)443 odocstream & operator<<(odocstream & os, char c)
444 {
445 os.put(c);
446 return os;
447 }
448 #endif
449
450 } // namespace lyx
451
452
453 #if ! defined(USE_WCHAR_T) && defined(__GNUC__)
454 // We get undefined references to these virtual methods. This looks like
455 // a bug in gcc. The implementation here does not do anything useful, since
456 // it is overriden in iconv_codecvt_facet.
457 namespace std {
458
459 template<> codecvt<lyx::char_type, char, mbstate_t>::result
do_out(mbstate_t &,const lyx::char_type *,const lyx::char_type *,const lyx::char_type * &,char *,char *,char * &) const460 codecvt<lyx::char_type, char, mbstate_t>::do_out(
461 mbstate_t &, const lyx::char_type *, const lyx::char_type *,
462 const lyx::char_type *&, char *, char *, char *&) const
463 {
464 return error;
465 }
466
467
468 template<> codecvt<lyx::char_type, char, mbstate_t>::result
do_unshift(mbstate_t &,char *,char *,char * &) const469 codecvt<lyx::char_type, char, mbstate_t>::do_unshift(
470 mbstate_t &, char *, char *, char *&) const
471 {
472 return error;
473 }
474
475
476 template<> codecvt<lyx::char_type, char, mbstate_t>::result
do_in(mbstate_t &,const char *,const char *,const char * &,lyx::char_type *,lyx::char_type *,lyx::char_type * &) const477 codecvt<lyx::char_type, char, mbstate_t>::do_in(
478 mbstate_t &, const char *, const char *, const char *&,
479 lyx::char_type *, lyx::char_type *, lyx::char_type *&) const
480 {
481 return error;
482 }
483
484
485 template<>
do_encoding() const486 int codecvt<lyx::char_type, char, mbstate_t>::do_encoding() const throw()
487 {
488 return 0;
489 }
490
491
492 template<>
do_always_noconv() const493 bool codecvt<lyx::char_type, char, mbstate_t>::do_always_noconv() const throw()
494 {
495 return true;
496 }
497
498 template<>
do_length(mbstate_t &,const char *,const char *,size_t) const499 int codecvt<lyx::char_type, char, mbstate_t>::do_length(
500 mbstate_t &, const char *, const char *, size_t) const
501 {
502 return 1;
503 }
504
505 template<>
do_max_length() const506 int codecvt<lyx::char_type, char, mbstate_t>::do_max_length() const throw()
507 {
508 return 4;
509 }
510
511 } // namespace std
512 #endif
513