Code

configure.ac: added --disable-locale option
[ncmpc.git] / src / charset.c
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 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         return NULL;
36 }
37 #endif
39 unsigned
40 utf8_width(const char *str)
41 {
42         assert(str != NULL);
44 #ifdef ENABLE_WIDE
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 ENABLE_LOCALE
66         gchar *str;
68         assert(utf8str != NULL);
70         if (noconvert)
71                 return g_strdup(utf8str);
73         str = g_convert_with_fallback(utf8str, -1,
74                                       charset, "utf-8",
75                                       NULL, NULL, NULL, NULL);
76         if (str == NULL)
77                 return g_strdup(utf8str);
79         return str;
80 #else
81         return g_strdup(utf8str);
82 #endif
83 }
85 char *
86 locale_to_utf8(const char *localestr)
87 {
88 #ifdef ENABLE_LOCALE
89         gchar *str;
91         assert(localestr != NULL);
93         if (noconvert)
94                 return g_strdup(localestr);
96         str = g_convert_with_fallback(localestr, -1,
97                                       "utf-8", charset,
98                                       NULL, NULL, NULL, NULL);
99         if (str == NULL)
100                 return g_strdup(localestr);
102         return str;
103 #else
104         return g_strdup(localestr);
105 #endif