1 /*
2 * (c) 2006 by Kalle Wallin <kaw@linux.se>
3 * Copyright (C) 2008 Max Kellermann <max@duempel.org>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17 *
18 */
20 #include "charset.h"
22 #include <assert.h>
23 #include <string.h>
24 #include <glib.h>
26 #ifdef HAVE_LOCALE_H
27 static bool noconvert = true;
28 static const char *charset;
30 const char *
31 charset_init(void)
32 {
33 noconvert = g_get_charset(&charset);
34 return charset;
35 return NULL;
36 }
37 #endif
39 unsigned
40 utf8_width(const char *str)
41 {
42 assert(str != NULL);
44 #ifdef HAVE_LOCALE_H
45 if (g_utf8_validate(str, -1, NULL)) {
46 size_t len = g_utf8_strlen(str, -1);
47 unsigned width = 0;
48 gunichar c;
50 while (len--) {
51 c = g_utf8_get_char(str);
52 width += g_unichar_iswide(c) ? 2 : 1;
53 str += g_unichar_to_utf8(c, NULL);
54 }
56 return width;
57 } else
58 #endif
59 return strlen(str);
60 }
62 char *
63 utf8_to_locale(const char *utf8str)
64 {
65 #ifdef HAVE_LOCALE_H
66 gchar *str;
67 GError *error;
69 assert(utf8str != NULL);
71 if (noconvert)
72 return g_strdup(utf8str);
74 str = g_convert_with_fallback(utf8str, -1,
75 charset, "utf-8",
76 NULL, NULL, NULL,
77 &error);
78 if (str == NULL) {
79 g_error_free(error);
80 return g_strdup(utf8str);
81 }
83 return str;
84 #else
85 return g_strdup(utf8str);
86 #endif
87 }
89 char *
90 locale_to_utf8(const char *localestr)
91 {
92 #ifdef HAVE_LOCALE_H
93 gchar *str;
94 GError *error;
96 assert(localestr != NULL);
98 if (noconvert)
99 return g_strdup(localestr);
101 str = g_convert_with_fallback(localestr, -1,
102 "utf-8", charset,
103 NULL, NULL, NULL,
104 &error);
105 if (str == NULL) {
106 g_error_free(error);
107 return g_strdup(localestr);
108 }
110 return str;
111 #else
112 return g_strdup(localestr);
113 #endif
114 }