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