1 /*****************************************************************************
2 * unicode.c: Unicode <-> locale functions
3 *****************************************************************************
4 * Copyright (C) 2005-2006 the VideoLAN team
5 * Copyright © 2005-2008 Rémi Denis-Courmont
7 * Authors: Rémi Denis-Courmont <rem # videolan.org>
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
39 #include <sys/types.h>
45 #if defined (ASSUME_UTF8)
48 #elif defined (WIN32) || defined (UNDER_CE)
52 static char *locale_dup (const char *string, bool from)
57 len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
58 0, string, -1, NULL, 0);
59 wchar_t *wide = malloc (len * sizeof (wchar_t));
63 MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
64 len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
68 WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
74 #elif defined (HAVE_ICONV)
77 static char *locale_dup (const char *string, bool from)
79 vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : "",
81 if (hd == (vlc_iconv_t)(-1))
82 return NULL; /* Uho! */
84 const char *iptr = string;
85 size_t inb = strlen (string);
86 size_t outb = inb * 6 + 1;
87 char output[outb], *optr = output;
89 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
95 vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
101 assert (*iptr == '\0');
102 assert (*optr == '\0');
103 assert (strlen (output) == (size_t)(optr - output));
104 return strdup (output);
108 # error No UTF8 charset conversion implemented on this platform!
113 * Releases (if needed) a localized or uniformized string.
114 * @param str non-NULL return value from FromLocale() or ToLocale().
116 void LocaleFree (const char *str)
127 * Converts a string from the system locale character encoding to UTF-8.
129 * @param locale nul-terminated string to convert
131 * @return a nul-terminated UTF-8 string, or NULL in case of error.
132 * To avoid memory leak, you have to pass the result to LocaleFree()
133 * when it is no longer needed.
135 char *FromLocale (const char *locale)
138 return (char *)locale;
140 return locale ? locale_dup (locale, true) : NULL;
145 * converts a string from the system locale character encoding to utf-8,
146 * the result is always allocated on the heap.
148 * @param locale nul-terminated string to convert
150 * @return a nul-terminated utf-8 string, or null in case of error.
151 * The result must be freed using free() - as with the strdup() function.
153 char *FromLocaleDup (const char *locale)
156 return strdup (locale);
158 return locale_dup (locale, true);
164 * ToLocale: converts an UTF-8 string to local system encoding.
166 * @param utf8 nul-terminated string to be converted
168 * @return a nul-terminated string, or NULL in case of error.
169 * To avoid memory leak, you have to pass the result to LocaleFree()
170 * when it is no longer needed.
172 char *ToLocale (const char *utf8)
177 return utf8 ? locale_dup (utf8, false) : NULL;
183 * converts a string from UTF-8 to the system locale character encoding,
184 * the result is always allocated on the heap.
186 * @param utf8 nul-terminated string to convert
188 * @return a nul-terminated string, or null in case of error.
189 * The result must be freed using free() - as with the strdup() function.
191 char *ToLocaleDup (const char *utf8)
194 return strdup (utf8);
196 return locale_dup (utf8, false);
201 * Formats an UTF-8 string as vfprintf(), then print it, with
202 * appropriate conversion to local encoding.
204 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
207 return vfprintf (stream, fmt, ap);
212 # if defined( WIN32 ) && !defined( UNDER_CE )
213 /* Writing to the console is a lot of fun on Microsoft Windows.
214 * If you use the standard I/O functions, you must use the OEM code page,
215 * which is different from the usual ANSI code page. Or maybe not, if the
216 * user called "chcp". Anyway, we prefer Unicode. */
217 int fd = _fileno (stream);
218 if (likely(fd != -1) && _isatty (fd))
220 res = vasprintf (&str, fmt, ap);
221 if (unlikely(res == -1))
224 size_t wlen = 2 * (res + 1);
225 wchar_t *wide = malloc (wlen);
226 if (likely(wide != NULL))
228 wlen = MultiByteToWideChar (CP_UTF8, 0, str, res + 1, wide, wlen);
231 HANDLE h = (HANDLE)(intptr_t)_get_osfhandle (fd);
234 WriteConsoleW (h, wide, wlen - 1, &out, NULL);
247 res = vasprintf (&str, fmt, ap);
248 if (unlikely(res == -1))
251 char *ansi = ToLocaleDup (str);
254 fputs (ansi, stream);
261 * Formats an UTF-8 string as fprintf(), then print it, with
262 * appropriate conversion to local encoding.
264 int utf8_fprintf( FILE *stream, const char *fmt, ... )
270 res = utf8_vfprintf( stream, fmt, ap );
276 static char *CheckUTF8( char *str, char rep )
278 uint8_t *ptr = (uint8_t *)str;
279 assert (str != NULL);
291 int charlen = clz8 (c ^ 0xFF);
294 case 0: // 7-bit ASCII character -> OK
298 case 1: // continuation byte -> error
302 assert (charlen >= 2 && charlen <= 4);
304 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
305 for (int i = 1; i < charlen; i++)
307 assert (cp < (1 << 26));
310 if ((c >> 6) != 2) // not a continuation byte
313 cp = (cp << 6) | (ptr[i] & 0x3f);
319 if (cp > 0x10FFFF) // beyond Unicode
322 if (cp >= 0xD800 && cp < 0xC000) // UTF-16 surrogate
325 if (cp < 128) // ASCII overlong
327 if (cp < (1u << (5 * charlen - 3))) // overlong
344 * Replaces invalid/overlong UTF-8 sequences with question marks.
345 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
346 * so we don't try that, even though it would be less disruptive.
348 * @return str if it was valid UTF-8, NULL if not.
350 char *EnsureUTF8( char *str )
352 return CheckUTF8( str, '?' );
357 * Checks whether a string is a valid UTF-8 byte sequence.
359 * @param str nul-terminated string to be checked
361 * @return str if it was valid UTF-8, NULL if not.
363 const char *IsUTF8( const char *str )
365 return CheckUTF8( (char *)str, 0 );
369 * Converts a string from the given character encoding to utf-8.
371 * @return a nul-terminated utf-8 string, or null in case of error.
372 * The result must be freed using free().
374 char *FromCharset(const char *charset, const void *data, size_t data_size)
376 vlc_iconv_t handle = vlc_iconv_open ("UTF-8", charset);
377 if (handle == (vlc_iconv_t)(-1))
381 for(unsigned mul = 4; mul < 8; mul++ )
383 size_t in_size = data_size;
384 const char *in = data;
385 size_t out_max = mul * data_size;
386 char *tmp = out = malloc (1 + out_max);
390 if (vlc_iconv (handle, &in, &in_size, &tmp, &out_max) != (size_t)(-1)) {
400 vlc_iconv_close(handle);