]> git.lyx.org Git - lyx.git/blob - src/support/docstream.C
Display error/warning dialogs if possible.
[lyx.git] / src / support / docstream.C
1 /**
2  * \file docstream.C
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                 // 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                 // All other encodings encode one UCS4 code point in one byte
214                 // (and can therefore only encode a subset of UCS4)
215                 return encoding_ == "UTF-8" ? 4 : 1;
216         }
217 private:
218         /// Do the actual conversion. The interface is equivalent to that of
219         /// iconv() (but const correct).
220         inline base::result do_iconv(iconv_t cd, char const ** from,
221                         size_t * inbytesleft, char ** to, size_t * outbytesleft) const
222         {
223                 char const * const to_start = *to;
224                 size_t converted = iconv(cd, const_cast<char ICONV_CONST **>(from),
225                                 inbytesleft, to, outbytesleft);
226                 if (converted == (size_t)(-1)) {
227                         switch(errno) {
228                         case EINVAL:
229                         case E2BIG:
230                                 return base::partial;
231                         case EILSEQ:
232                         default:
233                                 return base::error;
234                         }
235                 }
236                 if (*to == to_start)
237                         return base::noconv;
238                 return base::ok;
239         }
240         iconv_t in_cd_;
241         iconv_t out_cd_;
242         /// The narrow encoding
243         std::string encoding_;
244 };
245
246 } // namespace anon
247
248
249 namespace lyx {
250
251
252 const char * iconv_codecvt_facet_exception::what() const throw()
253 {
254         return "iconv problem in iconv_codecvt_facet initialization";
255 }
256
257
258 idocfstream::idocfstream(string const & encoding) : base()
259 {
260         std::locale global;
261         std::locale locale(global, new iconv_codecvt_facet(encoding, in));
262         imbue(locale);
263 }
264
265         
266 idocfstream::idocfstream(const char* s, std::ios_base::openmode mode,
267                          string const & encoding)
268         : base()
269 {
270         // We must imbue the stream before openening the file
271         std::locale global;
272         std::locale locale(global, new iconv_codecvt_facet(encoding, in));
273         imbue(locale);
274         open(s, mode);
275 }
276
277
278 odocfstream::odocfstream(string const & encoding) : base()
279 {
280         std::locale global;
281         std::locale locale(global, new iconv_codecvt_facet(encoding, out));
282         imbue(locale);
283 }
284
285
286 odocfstream::odocfstream(const char* s, std::ios_base::openmode mode,
287                          string const & encoding)
288         : base()
289 {
290         // We must imbue the stream before openening the file
291         std::locale global;
292         std::locale locale(global, new iconv_codecvt_facet(encoding, out));
293         imbue(locale);
294         open(s, mode);
295 }
296
297
298 SetEnc setEncoding(string const & encoding)
299 {
300         return SetEnc(encoding);
301 }
302
303
304 odocstream & operator<<(odocstream & os, SetEnc e)
305 {
306         if (std::has_facet<iconv_codecvt_facet>(os.rdbuf()->getloc())) {
307                 // This stream must be a file stream, since we never imbue
308                 // any other stream with a locale having a iconv_codecvt_facet.
309                 // Flush the stream so that all pending output is written
310                 // with the old encoding.
311                 os.flush();
312                 std::locale locale(os.rdbuf()->getloc(),
313                         new iconv_codecvt_facet(e.encoding, std::ios_base::out));
314                 // FIXME Does changing the codecvt facet of an open file
315                 // stream always work? It does with gcc 4.1, but I have read
316                 // somewhere that it does not with MSVC.
317                 // What does the standard say?
318                 os.imbue(locale);
319         }
320         return os;
321 }
322
323 }
324
325 #if (!defined(HAVE_WCHAR_T) || SIZEOF_WCHAR_T != 4) && defined(__GNUC__)
326 // We get undefined references to these virtual methods. This looks like
327 // a bug in gcc. The implementation here does not do anything useful, since
328 // it is overriden in iconv_codecvt_facet.
329 namespace std {
330 template<> codecvt<lyx::char_type, char, mbstate_t>::result
331 codecvt<lyx::char_type, char, mbstate_t>::do_out(mbstate_t &, const lyx::char_type *, const lyx::char_type *, const lyx::char_type *&,
332                 char *, char *, char *&) const { return error; }
333 template<> codecvt<lyx::char_type, char, mbstate_t>::result
334 codecvt<lyx::char_type, char, mbstate_t>::do_unshift(mbstate_t &, char *, char *, char *&) const { return error; }
335 template<> codecvt<lyx::char_type, char, mbstate_t>::result
336 codecvt<lyx::char_type, char, mbstate_t>::do_in(mbstate_t &, const char *, const char *, const char *&,
337                 lyx::char_type *, lyx::char_type *, lyx::char_type *&) const { return error; }
338 template<> int codecvt<lyx::char_type, char, mbstate_t>::do_encoding() const throw() { return 0; }
339 template<> bool codecvt<lyx::char_type, char, mbstate_t>::do_always_noconv() const throw() { return true; }
340 #if __GNUC__ == 3 && __GNUC_MINOR__ < 4
341 template<> int codecvt<lyx::char_type, char, mbstate_t>::do_length(mbstate_t const &, const char *, const char *, size_t) const { return 1; }
342 #else
343 template<> int codecvt<lyx::char_type, char, mbstate_t>::do_length(mbstate_t &, const char *, const char *, size_t) const { return 1; }
344 #endif
345 template<> int codecvt<lyx::char_type, char, mbstate_t>::do_max_length() const throw() { return 4; }
346 }
347 #endif