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