701fd2105bd6eb1afaf5a4e8a67cb64170c8abc3
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"
21 #include "i18n.h"
23 #include <assert.h>
24 #include <string.h>
25 #include <glib.h>
27 extern void screen_status_printf(const char *format, ...);
29 static bool noconvert = true;
30 static const char *charset;
32 const char *
33 charset_init(void)
34 {
35 noconvert = g_get_charset(&charset);
36 return charset;
37 }
39 unsigned
40 utf8_width(const char *str)
41 {
42 assert(str != NULL);
44 if (g_utf8_validate(str, -1, NULL)) {
45 size_t len = g_utf8_strlen(str, -1);
46 unsigned width = 0;
47 gunichar c;
49 while (len--) {
50 c = g_utf8_get_char(str);
51 width += g_unichar_iswide(c) ? 2 : 1;
52 str += g_unichar_to_utf8(c, NULL);
53 }
55 return width;
56 } else
57 return strlen(str);
58 }
60 char *
61 utf8_to_locale(const char *utf8str)
62 {
63 gchar *str;
64 gsize rb, wb;
65 GError *error;
67 assert(utf8str != NULL);
69 if (noconvert)
70 return g_strdup(utf8str);
72 rb = 0; /* bytes read */
73 wb = 0; /* bytes written */
74 error = NULL;
75 str = g_locale_from_utf8(utf8str,
76 strlen(utf8str),
77 &wb, &rb,
78 &error);
79 if (error) {
80 screen_status_printf(_("Error: Unable to convert characters to %s"),
81 charset);
82 g_error_free(error);
83 return g_strdup(utf8str);
84 }
86 return str;
87 }
89 char *
90 locale_to_utf8(const char *localestr)
91 {
92 gchar *str;
93 gsize rb, wb;
94 GError *error;
96 assert(localestr != NULL);
98 if (noconvert)
99 return g_strdup(localestr);
101 rb = 0; /* bytes read */
102 wb = 0; /* bytes written */
103 error = NULL;
104 str = g_locale_to_utf8(localestr,
105 strlen(localestr),
106 &wb, &rb,
107 &error);
108 if (error) {
109 screen_status_printf(_("Error: Unable to convert characters to UTF-8"));
110 g_error_free(error);
111 return g_strdup(localestr);
112 }
114 return str;
115 }