]> git.lyx.org Git - lyx.git/blob - src/support/docstring.C
Fix several filename and environment variable encoding problems
[lyx.git] / src / support / docstring.C
1 /**
2  * \file docstring.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 "docstring.h"
14 #include "qstring_helpers.h"
15 #include "unicode.h"
16
17 #include <locale>
18 #include <iostream>
19
20 #include <QFile>
21
22 #include <boost/assert.hpp>
23
24
25 namespace lyx {
26
27
28 docstring const from_ascii(char const * ascii)
29 {
30         docstring s;
31         for (char const * c = ascii; *c; ++c) {
32                 BOOST_ASSERT(static_cast<unsigned char>(*c) < 0x80);
33                 s.push_back(*c);
34         }
35         return s;
36 }
37
38
39 docstring const from_ascii(std::string const & ascii)
40 {
41         int const len = ascii.length();
42         for (int i = 0; i < len; ++i)
43                 BOOST_ASSERT(static_cast<unsigned char>(ascii[i]) < 0x80);
44         return docstring(ascii.begin(), ascii.end());
45 }
46
47
48 std::string const to_ascii(docstring const & ucs4)
49 {
50         int const len = ucs4.length();
51         std::string ascii;
52         ascii.resize(len);
53         for (int i = 0; i < len; ++i) {
54                 BOOST_ASSERT(ucs4[i] < 0x80);
55                 ascii[i] = static_cast<char>(ucs4[i]);
56         }
57         return ascii;
58 }
59
60
61 void utf8_to_ucs4(std::string const & utf8, docstring & ucs4)
62 {
63         size_t n = utf8.size();
64         // as utf8 is a multi-byte encoding, there would be at most
65         // n characters:
66         ucs4.resize(n);
67         if (n == 0)
68                 return;
69
70         int maxoutsize = n * 4;
71         // basic_string::data() is not recognized by some old gcc version
72         // so we use &(ucs4[0]) instead.
73         char * outbuf = (char *)(&(ucs4[0]));
74         int bytes = utf8ToUcs4().convert(utf8.c_str(), n, outbuf, maxoutsize);
75
76         // adjust to the real converted size
77         ucs4.resize(bytes/4);
78 }
79
80
81 docstring const from_utf8(std::string const & utf8)
82 {
83         docstring ucs4;
84         utf8_to_ucs4(utf8, ucs4);
85         return ucs4;
86 }
87
88
89 std::string const to_utf8(docstring const & ucs4)
90 {
91         std::vector<char> const utf8 =
92                 ucs4_to_utf8(ucs4.data(), ucs4.size());
93         return std::string(utf8.begin(), utf8.end());
94 }
95
96
97 docstring const from_local8bit(std::string const & s)
98 {
99         return qstring_to_ucs4(QString::fromLocal8Bit(s.data(), s.length()));
100 }
101
102
103 const char* to_local8bit_failure::what() const throw()
104 {
105         return "A string could not be converted from unicode to the local 8 bit encoding.";
106 }
107
108
109 std::string const to_local8bit(docstring const & s)
110 {
111         // This conversion can fail, depending on input.
112         if (s.empty())
113                 return std::string();
114         QByteArray const local = toqstr(s).toLocal8Bit();
115         if (local.size() == 0)
116                 throw to_local8bit_failure();
117         return std::string(local.begin(), local.end());
118 }
119
120
121 docstring const from_filesystem8bit(std::string const & s)
122 {
123         QByteArray const encoded(s.c_str(), s.length());
124         return qstring_to_ucs4(QFile::decodeName(encoded));
125 }
126
127
128 bool operator==(lyx::docstring const & l, char const * r)
129 {
130         int const len = l.length();
131         for (int i = 0; i < len; ++i) {
132                 BOOST_ASSERT(static_cast<unsigned char>(r[i]) < 0x80);
133                 if (!r[i])
134                         return false;
135                 if (l[i] != lyx::docstring::value_type(r[i]))
136                         return false;
137         }
138         return r[len] == '\0';
139 }
140
141
142 lyx::docstring operator+(lyx::docstring const & l, char const * r)
143 {
144         lyx::docstring s(l);
145         for (char const * c = r; *c; ++c) {
146                 BOOST_ASSERT(static_cast<unsigned char>(*c) < 0x80);
147                 s.push_back(*c);
148         }
149         return s;
150 }
151
152
153 lyx::docstring operator+(char const * l, lyx::docstring const & r)
154 {
155         lyx::docstring s;
156         for (char const * c = l; *c; ++c) {
157                 BOOST_ASSERT(static_cast<unsigned char>(*c) < 0x80);
158                 s.push_back(*c);
159         }
160         s += r;
161         return s;
162 }
163
164
165 lyx::docstring operator+(lyx::docstring const & l, char r)
166 {
167         BOOST_ASSERT(static_cast<unsigned char>(r) < 0x80);
168         return l + lyx::docstring::value_type(r);
169 }
170
171
172 lyx::docstring operator+(char l, lyx::docstring const & r)
173 {
174         BOOST_ASSERT(static_cast<unsigned char>(l) < 0x80);
175         return lyx::docstring::value_type(l) + r;
176 }
177
178
179 lyx::docstring & operator+=(lyx::docstring & l, char const * r)
180 {
181         for (char const * c = r; *c; ++c) {
182                 BOOST_ASSERT(static_cast<unsigned char>(*c) < 0x80);
183                 l.push_back(*c);
184         }
185         return l;
186 }
187
188
189 lyx::docstring & operator+=(lyx::docstring & l, char r)
190 {
191         BOOST_ASSERT(static_cast<unsigned char>(r) < 0x80);
192         l.push_back(r);
193         return l;
194 }
195
196 } // namespace lyx
197
198 #if (!defined(HAVE_WCHAR_T) || SIZEOF_WCHAR_T != 4) && defined(__GNUC__)
199
200 // gcc does not have proper locale facets for lyx::char_type if
201 // sizeof(wchar_t) == 2, so we have to implement them on our own.
202
203
204 // We get undefined references to these virtual methods. This looks like
205 // a bug in gcc. The implementation here does not do anything useful, since
206 // it is overriden in ascii_ctype_facet.
207 namespace std {
208 template<> ctype<lyx::char_type>::~ctype() {}
209 template<> bool
210 ctype<lyx::char_type>::do_is(ctype<lyx::char_type>::mask, lyx::char_type) const { return false; }
211 template<> lyx::char_type const *
212 ctype<lyx::char_type>::do_is(const lyx::char_type *, const lyx::char_type *, ctype<lyx::char_type>::mask *) const { return 0; }
213 template<> const lyx::char_type *
214 ctype<lyx::char_type>::do_scan_is(ctype<lyx::char_type>::mask, const lyx::char_type *, const lyx::char_type *) const { return 0; }
215 template<> const lyx::char_type *
216 ctype<lyx::char_type>::do_scan_not(ctype<lyx::char_type>::mask, const lyx::char_type *, const lyx::char_type *) const { return 0; }
217 template<> lyx::char_type ctype<lyx::char_type>::do_toupper(lyx::char_type) const { return 0; }
218 template<> const lyx::char_type * ctype<lyx::char_type>::do_toupper(lyx::char_type *, lyx::char_type const *) const { return 0; }
219 template<> lyx::char_type ctype<lyx::char_type>::do_tolower(lyx::char_type) const { return 0; }
220 template<> const lyx::char_type * ctype<lyx::char_type>::do_tolower(lyx::char_type *, lyx::char_type const *) const { return 0; }
221 template<> lyx::char_type ctype<lyx::char_type>::do_widen(char) const { return 0; }
222 template<> const char *
223 ctype<lyx::char_type>::do_widen(const char *, const char *, lyx::char_type *) const { return 0; }
224 template<> char
225 ctype<lyx::char_type>::do_narrow(const lyx::char_type, char) const { return 0; }
226 template<> const lyx::char_type *
227 ctype<lyx::char_type>::do_narrow(const lyx::char_type *, const lyx::char_type *, char, char *) const { return 0; }
228 }
229
230
231 namespace lyx {
232
233 class ctype_failure : public std::bad_cast {
234 public:
235         ctype_failure() throw() : std::bad_cast() {}
236         virtual ~ctype_failure() throw() {}
237         virtual const char* what() const throw()
238         {
239                 return "The ctype<lyx::char_type> locale facet does only support ASCII characters on this platform.";
240         }
241 };
242
243
244 class num_put_failure : public std::bad_cast {
245 public:
246         num_put_failure() throw() : std::bad_cast() {}
247         virtual ~num_put_failure() throw() {}
248         virtual const char* what() const throw()
249         {
250                 return "The num_put locale facet does only support ASCII characters on this platform.";
251         }
252 };
253
254
255 /// ctype facet for UCS4 characters. The implementation does only support pure
256 /// ASCII, since we do not need anything else for now.
257 /// The code is partly stolen from std::ctype<wchar_t> from gcc.
258 class ascii_ctype_facet : public std::ctype<lyx::char_type>
259 {
260 public:
261         typedef lyx::char_type char_type;
262         typedef wctype_t wmask_type;
263         explicit ascii_ctype_facet(size_t refs = 0) : std::ctype<char_type>(refs)
264         {
265                 M_initialize_ctype();
266         }
267 protected:
268         bool       M_narrow_ok;
269         char       M_narrow[128];
270         wint_t     M_widen[1 + static_cast<unsigned char>(-1)];
271         mask       M_bit[16];
272         wmask_type M_wmask[16];
273         wmask_type M_convert_to_wmask(const mask m) const
274         {
275                 wmask_type ret;
276                 switch (m) {
277                         case space:  ret = wctype("space");  break;
278                         case print:  ret = wctype("print");  break;
279                         case cntrl:  ret = wctype("cntrl");  break;
280                         case upper:  ret = wctype("upper");  break;
281                         case lower:  ret = wctype("lower");  break;
282                         case alpha:  ret = wctype("alpha");  break;
283                         case digit:  ret = wctype("digit");  break;
284                         case punct:  ret = wctype("punct");  break;
285                         case xdigit: ret = wctype("xdigit"); break;
286                         case alnum:  ret = wctype("alnum");  break;
287                         case graph:  ret = wctype("graph");  break;
288                         default:     ret = wmask_type();
289                 }
290                 return ret;
291         }
292         void M_initialize_ctype()
293         {
294                 wint_t i;
295                 for (i = 0; i < 128; ++i) {
296                         const int c = wctob(i);
297                         if (c == EOF)
298                                 break;
299                         else
300                                 M_narrow[i] = static_cast<char>(c);
301                 }
302                 if (i == 128)
303                         M_narrow_ok = true;
304                 else
305                         M_narrow_ok = false;
306                 for (size_t i = 0; i < sizeof(M_widen) / sizeof(wint_t); ++i)
307                         M_widen[i] = btowc(i);
308
309                 for (size_t i = 0; i <= 15; ++i) {
310                         M_bit[i] = static_cast<mask>(1 << i);
311                         M_wmask[i] = M_convert_to_wmask(M_bit[i]);
312                 }
313         }
314         virtual ~ascii_ctype_facet() {}
315         char_type do_toupper(char_type c) const
316         {
317                 if (c >= 0x80)
318                         throw ctype_failure();
319                 return toupper(static_cast<int>(c));
320         }
321         char_type const * do_toupper(char_type * lo, char_type const * hi) const
322         {
323                 while (lo < hi) {
324                         if (*lo >= 0x80)
325                                 throw ctype_failure();
326                         *lo = toupper(static_cast<int>(*lo));
327                         ++lo;
328                 }
329                 return hi;
330         }
331         char_type do_tolower(char_type c) const
332         {
333                 if (c >= 0x80)
334                         throw ctype_failure();
335                 return tolower(c);
336         }
337         char_type const * do_tolower(char_type * lo, char_type const * hi) const
338         {
339                 while (lo < hi) {
340                         if (*lo >= 0x80)
341                                 throw ctype_failure();
342                         *lo = tolower(*lo);
343                         ++lo;
344                 }
345                 return hi;
346         }
347         bool do_is(mask m, char_type c) const
348         {
349                 if (c >= 0x80)
350                         throw ctype_failure();
351                 // The code below works because c is in the ASCII range.
352                 // We could not use iswctype() which is designed for a 2byte
353                 // whar_t without encoding conversion otherwise.
354                 bool ret = false;
355                 // Generically, 15 (instead of 10) since we don't know the numerical
356                 // encoding of the various categories in /usr/include/ctype.h.
357                 const size_t bitmasksize = 15;
358                 for (size_t bitcur = 0; bitcur <= bitmasksize; ++bitcur)
359                         if (m & M_bit[bitcur] &&
360                             iswctype(static_cast<int>(c), M_wmask[bitcur])) {
361                                 ret = true;
362                                 break;
363                         }
364                 return ret;
365         }
366         char_type const * do_is(char_type const * lo, char_type const * hi, mask * vec) const
367         {
368                 for (;lo < hi; ++vec, ++lo) {
369                         if (*lo >= 0x80)
370                                 throw ctype_failure();
371                         // The code below works because c is in the ASCII range.
372                         // We could not use iswctype() which is designed for a 2byte
373                         // whar_t without encoding conversion otherwise.
374                         // Generically, 15 (instead of 10) since we don't know the numerical
375                         // encoding of the various categories in /usr/include/ctype.h.
376                         const size_t bitmasksize = 15;
377                         mask m = 0;
378                         for (size_t bitcur = 0; bitcur <= bitmasksize; ++bitcur)
379                                 if (iswctype(static_cast<int>(*lo), M_wmask[bitcur]))
380                                         m |= M_bit[bitcur];
381                         *vec = m;
382                 }
383                 return hi;
384         }
385         char_type const * do_scan_is(mask m, char_type const * lo, char_type const * hi) const
386         {
387                 while (lo < hi && !this->do_is(m, *lo))
388                         ++lo;
389                 return lo;
390         }
391         char_type const * do_scan_not(mask m, char_type const * lo, char_type const * hi) const
392         {
393                 while (lo < hi && this->do_is(m, *lo) != 0)
394                         ++lo;
395                 return lo;
396         }
397         char_type do_widen(char c) const
398         {
399                 if (static_cast<unsigned char>(c) < 0x80)
400                         return c;
401                 throw ctype_failure();
402         }
403         const char* do_widen(const char* lo, const char* hi, char_type* dest) const
404         {
405                 while (lo < hi) {
406                         if (static_cast<unsigned char>(*lo) >= 0x80)
407                                 throw ctype_failure();
408                         *dest = *lo;
409                         ++lo;
410                         ++dest;
411                 }
412                 return hi;
413         }
414         char do_narrow(char_type wc, char) const
415         {
416                 if (wc < 0x80)
417                         return static_cast<char>(wc);
418                 throw ctype_failure();
419         }
420         const char_type * do_narrow(const char_type * lo, const char_type * hi, char, char * dest) const
421         {
422                 while (lo < hi) {
423                         if (*lo < 0x80)
424                                 *dest = static_cast<char>(*lo);
425                         else
426                                 throw ctype_failure();
427                         ++lo;
428                         ++dest;
429                 }
430                 return hi;
431         }
432 };
433
434
435 /// Facet for outputting numbers to odocstreams as ascii.
436 /// Here we simply need defining the virtual do_put functions.
437 class ascii_num_put_facet : public std::num_put<lyx::char_type, std::ostreambuf_iterator<lyx::char_type, std::char_traits<lyx::char_type> > >
438 {
439         typedef std::ostreambuf_iterator<lyx::char_type, std::char_traits<lyx::char_type> > iter_type;
440 public:
441         ascii_num_put_facet(size_t refs = 0) : std::num_put<lyx::char_type, iter_type>(refs) {}
442
443         /// Facet for converting numbers to ascii strings.
444         class string_num_put_facet : public std::num_put<char, std::basic_string<char>::iterator>
445         {
446         public:
447                 string_num_put_facet() : std::num_put<char, std::basic_string<char>::iterator>(1) {}
448         };
449
450 protected:
451         iter_type
452         do_put(iter_type oit, std::ios_base & b, char_type fill, bool v) const
453         {
454                 return do_put_helper(oit, b, fill, v);
455         }
456
457         iter_type
458         do_put(iter_type oit, std::ios_base & b, char_type fill, long v) const
459         {
460                 return do_put_helper(oit, b, fill, v);
461         }
462
463         iter_type
464         do_put(iter_type oit, std::ios_base & b, char_type fill, unsigned long v) const
465         {
466                 return do_put_helper(oit, b, fill, v);
467         }
468
469 #ifdef _GLIBCXX_USE_LONG_LONG
470         iter_type
471         do_put(iter_type oit, std::ios_base & b, char_type fill, long long v) const
472         {
473                 return do_put_helper(oit, b, fill, v);
474         }
475
476         iter_type
477         do_put(iter_type oit, std::ios_base & b, char_type fill, unsigned long long v) const
478         {
479                 return do_put_helper(oit, b, fill, v);
480         }
481 #endif
482
483         iter_type
484         do_put(iter_type oit, std::ios_base & b, char_type fill, double v) const
485         {
486                 return do_put_helper(oit, b, fill, v);
487         }
488
489         iter_type
490         do_put(iter_type oit, std::ios_base & b, char_type fill, long double v) const
491         {
492                 return do_put_helper(oit, b, fill, v);
493         }
494
495         iter_type
496         do_put(iter_type oit, std::ios_base & b, char_type fill, void const * v) const
497         {
498                 return do_put_helper(oit, b, fill, v);
499         }
500
501 private:
502         template <typename ValueType>
503         iter_type
504         do_put_helper(iter_type oit, std::ios_base & b, char_type fill, ValueType v) const
505         {
506                 if (fill >= 0x80)
507                         throw num_put_failure();
508
509                 std::streamsize const sz = b.width() > b.precision() ?
510                                            b.width() : b.precision();
511                 // 64 is large enough, unless width or precision are bigger
512                 std::streamsize const wd = (sz > 56 ? sz : 56) + 8;
513                 std::string s(wd, '\0');
514                 string_num_put_facet f;
515                 std::string::const_iterator cit = s.begin();
516                 std::string::const_iterator end =
517                         f.put(s.begin(), b, fill, v);
518                 for (; cit != end; ++cit, ++oit)
519                         *oit = *cit;
520
521                 return oit;
522         }
523 };
524
525
526 /// Facet for inputting ascii representations of numbers from idocstreams.
527 /// Here we simply need defining the virtual do_get functions.
528 class ascii_num_get_facet : public std::num_get<lyx::char_type, std::istreambuf_iterator<lyx::char_type, std::char_traits<lyx::char_type> > >
529 {
530         typedef std::istreambuf_iterator<lyx::char_type, std::char_traits<lyx::char_type> > iter_type;
531 public:
532         ascii_num_get_facet(size_t refs = 0) : std::num_get<lyx::char_type, iter_type>(refs) {}
533
534         /// Facet for converting ascii representation of numbers to a value.
535         class string_num_get_facet : public std::num_get<char, std::basic_string<char>::iterator>
536         {
537         public:
538                 string_num_get_facet() : std::num_get<char, std::basic_string<char>::iterator>(1) {}
539         };
540
541 private:
542         bool isNumpunct(lyx::char_type const c) const
543         {
544                 /// Only account for the standard numpunct "C" locale facet.
545                 return c < 0x80 && (c == '-' || c == '+' || isdigit(c)
546                         || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')
547                         || c == 'x' || c == 'X');
548         }
549
550 protected:
551         iter_type
552         do_get(iter_type iit, iter_type eit, std::ios_base & b,
553                 std::ios_base::iostate & err, long & v) const
554         {
555                 std::string s;
556                 s.reserve(64);
557                 for (; iit != eit && isNumpunct(*iit); ++iit)
558                         s += static_cast<char>(*iit);
559                 // We add another character, not part of the numpunct facet,
560                 // in order to avoid setting the eofbit in the stream state,
561                 // which would prevent any further read. The space seems a
562                 // good choice here.
563                 s += ' ';
564                 string_num_get_facet f;
565                 f.get(s.begin(), s.end(), b, err, v);
566
567                 return iit;
568         }
569 };
570
571
572 /// class to add our facets to the global locale
573 class locale_initializer {
574 public:
575         locale_initializer()
576         {
577                 std::locale global;
578                 std::locale const loc1(global, new ascii_ctype_facet);
579                 std::locale const loc2(loc1, new ascii_num_put_facet);
580                 std::locale const loc3(loc2, new ascii_num_get_facet);
581                 std::locale::global(loc3);
582         }
583 };
584
585
586 namespace {
587
588 /// make sure that our facets get used
589 static locale_initializer initializer;
590
591 }
592 }
593 #endif