]> git.lyx.org Git - lyx.git/blob - src/support/docstream.cpp
cc44c13722a3699895a7b448840b4bcd26f2651b
[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 "docstream.h"
14 #include "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
271 const char * iconv_codecvt_facet_exception::what() const throw()
272 {
273         return "iconv problem in iconv_codecvt_facet initialization";
274 }
275
276
277 idocfstream::idocfstream(string const & encoding) : base()
278 {
279         std::locale global;
280         std::locale locale(global, new iconv_codecvt_facet(encoding, in));
281         imbue(locale);
282 }
283
284
285 idocfstream::idocfstream(const char* s, std::ios_base::openmode mode,
286                          string const & encoding)
287         : base()
288 {
289         // We must imbue the stream before openening the file
290         std::locale global;
291         std::locale locale(global, new iconv_codecvt_facet(encoding, in));
292         imbue(locale);
293         open(s, mode);
294 }
295
296
297 odocfstream::odocfstream(string const & encoding) : base()
298 {
299         std::locale global;
300         std::locale locale(global, new iconv_codecvt_facet(encoding, out));
301         imbue(locale);
302 }
303
304
305 odocfstream::odocfstream(const char* s, std::ios_base::openmode mode,
306                          string const & encoding)
307         : base()
308 {
309         // We must imbue the stream before openening the file
310         std::locale global;
311         std::locale locale(global, new iconv_codecvt_facet(encoding, out));
312         imbue(locale);
313         open(s, mode);
314 }
315
316
317 SetEnc setEncoding(string const & encoding)
318 {
319         return SetEnc(encoding);
320 }
321
322
323 odocstream & operator<<(odocstream & os, SetEnc e)
324 {
325         if (std::has_facet<iconv_codecvt_facet>(os.rdbuf()->getloc())) {
326                 // This stream must be a file stream, since we never imbue
327                 // any other stream with a locale having a iconv_codecvt_facet.
328                 // Flush the stream so that all pending output is written
329                 // with the old encoding.
330                 os.flush();
331                 std::locale locale(os.rdbuf()->getloc(),
332                         new iconv_codecvt_facet(e.encoding, std::ios_base::out));
333                 // FIXME Does changing the codecvt facet of an open file
334                 // stream always work? It does with gcc 4.1, but I have read
335                 // somewhere that it does not with MSVC.
336                 // What does the standard say?
337                 os.imbue(locale);
338         }
339         return os;
340 }
341
342
343 #if ! defined(USE_WCHAR_T)
344 odocstream & operator<<(odocstream & os, char c)
345 {
346         os.put(c);
347         return os;
348 }
349 #endif
350
351 }
352
353 #if ! defined(USE_WCHAR_T) && defined(__GNUC__)
354 // We get undefined references to these virtual methods. This looks like
355 // a bug in gcc. The implementation here does not do anything useful, since
356 // it is overriden in iconv_codecvt_facet.
357 namespace std {
358 template<> codecvt<lyx::char_type, char, mbstate_t>::result
359 codecvt<lyx::char_type, char, mbstate_t>::do_out(mbstate_t &, const lyx::char_type *, const lyx::char_type *, const lyx::char_type *&,
360                 char *, char *, char *&) const { return error; }
361 template<> codecvt<lyx::char_type, char, mbstate_t>::result
362 codecvt<lyx::char_type, char, mbstate_t>::do_unshift(mbstate_t &, char *, char *, char *&) const { return error; }
363 template<> codecvt<lyx::char_type, char, mbstate_t>::result
364 codecvt<lyx::char_type, char, mbstate_t>::do_in(mbstate_t &, const char *, const char *, const char *&,
365                 lyx::char_type *, lyx::char_type *, lyx::char_type *&) const { return error; }
366 template<> int codecvt<lyx::char_type, char, mbstate_t>::do_encoding() const throw() { return 0; }
367 template<> bool codecvt<lyx::char_type, char, mbstate_t>::do_always_noconv() const throw() { return true; }
368 #if __GNUC__ == 3 && __GNUC_MINOR__ < 4
369 template<> int codecvt<lyx::char_type, char, mbstate_t>::do_length(mbstate_t const &, const char *, const char *, size_t) const { return 1; }
370 #else
371 template<> int codecvt<lyx::char_type, char, mbstate_t>::do_length(mbstate_t &, const char *, const char *, size_t) const { return 1; }
372 #endif
373 template<> int codecvt<lyx::char_type, char, mbstate_t>::do_max_length() const throw() { return 4; }
374 }
375 #endif