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