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