Add a constructor from const char * for widestring, begin drawing in GroupScreen.
[ccbs] / bigscreen / widestring.cpp
1 #include <iconv.h>
2 #include <endian.h>
3 #include <exception>
4 #include <pqxx/util>
5 #include "widestring.h"
6
7 static iconv_t ucs4_iconv;
8 static bool iconv_initialized = false;
9
10 widestring::widestring(const char *from)
11 {
12         *this = from;
13 }
14
15 void widestring::operator= (const char *from)
16 {
17         if (!iconv_initialized) {
18 #if __BYTE_ORDER == __LITTLE_ENDIAN
19                 ucs4_iconv = iconv_open("ucs-4le", "utf-8");
20 #else
21                 ucs4_iconv = iconv_open("ucs-4be", "utf-8");
22 #endif
23
24                 iconv_initialized = true;
25         }
26         
27         unsigned bytes = std::strlen(from);
28         char *from_buf = strdup(from);
29         wchar_t *to_buf = new wchar_t[bytes + 1];
30
31         char *inptr = from_buf, *outptr = reinterpret_cast<char *> (to_buf);
32
33         size_t in_left = bytes;
34         size_t out_left = bytes * sizeof(wchar_t);
35
36         size_t ret = iconv(ucs4_iconv, NULL, NULL, &outptr, &out_left);
37         if (ret == (size_t)(-1)) {
38                 throw std::runtime_error("Error in iconv during initialization");
39         }
40
41         ret = iconv(ucs4_iconv, &inptr, &in_left, &outptr, &out_left);
42         if (ret == (size_t)(-1)) {
43                 perror("iconv");
44                 throw std::runtime_error("Error in iconv during conversion");
45         }
46
47         erase(begin(), end());
48         std::copy(to_buf, reinterpret_cast<wchar_t *> (outptr), std::back_inserter(*this));
49
50         free(from_buf);
51         delete[] to_buf;
52 }
53
54 template<>
55 void pqxx::from_string<widestring>(const char *from, widestring &to)
56 {
57         to = from;
58 }
59