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