1 /* ncmpc (Ncurses MPD Client)
2 * (c) 2004-2009 The Music Player Daemon Project
3 * Project homepage: http://musicpd.org
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.
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.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
20 #include "charset.h"
22 #include <assert.h>
23 #include <string.h>
24 #include <glib.h>
26 #ifdef ENABLE_LOCALE
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 }
36 #endif
38 unsigned
39 utf8_width(const char *str)
40 {
41 assert(str != NULL);
43 #if defined(ENABLE_MULTIBYTE) && !defined(ENABLE_WIDE)
44 return g_utf8_strlen(str, -1);
45 #else
46 #ifdef ENABLE_WIDE
47 if (g_utf8_validate(str, -1, NULL)) {
48 size_t len = g_utf8_strlen(str, -1);
49 unsigned width = 0;
50 gunichar c;
52 while (len--) {
53 c = g_utf8_get_char(str);
54 width += g_unichar_iswide(c) ? 2 : 1;
55 str += g_unichar_to_utf8(c, NULL);
56 }
58 return width;
59 } else
60 #endif
61 return strlen(str);
62 #endif
63 }
65 char *
66 utf8_to_locale(const char *utf8str)
67 {
68 #ifdef ENABLE_LOCALE
69 gchar *str;
71 assert(utf8str != NULL);
73 if (noconvert)
74 return g_strdup(utf8str);
76 str = g_convert_with_fallback(utf8str, -1,
77 charset, "utf-8",
78 NULL, NULL, NULL, NULL);
79 if (str == NULL)
80 return g_strdup(utf8str);
82 return str;
83 #else
84 return g_strdup(utf8str);
85 #endif
86 }
88 char *
89 locale_to_utf8(const char *localestr)
90 {
91 #ifdef ENABLE_LOCALE
92 gchar *str;
94 assert(localestr != NULL);
96 if (noconvert)
97 return g_strdup(localestr);
99 str = g_convert_with_fallback(localestr, -1,
100 "utf-8", charset,
101 NULL, NULL, NULL, NULL);
102 if (str == NULL)
103 return g_strdup(localestr);
105 return str;
106 #else
107 return g_strdup(localestr);
108 #endif
109 }