]> git.sesse.net Git - vlc/blob - src/text/unicode.c
Merge branch 1.0-bugfix
[vlc] / src / text / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 the VideoLAN team
5  * Copyright © 2005-2008 Rémi Denis-Courmont
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
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.
13  *
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.
18  *
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  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <vlc_common.h>
32 #include <vlc_charset.h>
33
34 #include <assert.h>
35
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <stdlib.h>
39 #include <sys/types.h>
40 #ifdef UNDER_CE
41 #  include <tchar.h>
42 #endif
43
44 #ifdef __APPLE__
45 /* Define this if the OS always use UTF-8 internally */
46 # define ASSUME_UTF8 1
47 #endif
48
49 #if defined (ASSUME_UTF8)
50 /* Cool */
51 #elif defined (WIN32) || defined (UNDER_CE)
52 # define USE_MB2MB 1
53 #elif defined (HAVE_ICONV)
54 # define USE_ICONV 1
55 #else
56 # error No UTF8 charset conversion implemented on this platform!
57 #endif
58
59 #if defined (USE_ICONV)
60 # include <langinfo.h>
61 static char charset[sizeof ("CSISO11SWEDISHFORNAMES")] = "";
62
63 static void find_charset_once (void)
64 {
65     strlcpy (charset, nl_langinfo (CODESET), sizeof (charset));
66     if (!strcasecmp (charset, "ASCII")
67      || !strcasecmp (charset, "ANSI_X3.4-1968"))
68         strcpy (charset, "UTF-8"); /* superset... */
69 }
70
71 static int find_charset (void)
72 {
73     static pthread_once_t once = PTHREAD_ONCE_INIT;
74     pthread_once (&once, find_charset_once);
75     return !strcasecmp (charset, "UTF-8");
76 }
77 #endif
78
79
80 static char *locale_fast (const char *string, bool from)
81 {
82     if( string == NULL )
83         return NULL;
84
85 #if defined (USE_ICONV)
86     if (find_charset ())
87         return (char *)string;
88
89     vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
90                                      from ? charset : "UTF-8");
91     if (hd == (vlc_iconv_t)(-1))
92         return NULL; /* Uho! */
93
94     const char *iptr = string;
95     size_t inb = strlen (string);
96     size_t outb = inb * 6 + 1;
97     char output[outb], *optr = output;
98
99     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
100     {
101         *optr++ = '?';
102         outb--;
103         iptr++;
104         inb--;
105         vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
106     }
107     *optr = '\0';
108     vlc_iconv_close (hd);
109
110     assert (inb == 0);
111     assert (*iptr == '\0');
112     assert (*optr == '\0');
113     assert (strlen (output) == (size_t)(optr - output));
114     return strdup (output);
115 #elif defined (USE_MB2MB)
116     char *out;
117     int len;
118
119     len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
120                                    0, string, -1, NULL, 0);
121     wchar_t wide[len];
122
123     MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
124     len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
125                                    NULL, 0, NULL, NULL);
126     out = malloc (len);
127     if (out == NULL)
128         return NULL;
129
130     WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
131                          NULL, NULL);
132     return out;
133 #else
134     (void)from;
135     return (char *)string;
136 #endif
137 }
138
139
140 static inline char *locale_dup (const char *string, bool from)
141 {
142     assert( string );
143
144 #if defined (USE_ICONV)
145     if (find_charset ())
146         return strdup (string);
147     return locale_fast (string, from);
148 #elif defined (USE_MB2MB)
149     return locale_fast (string, from);
150 #else
151     (void)from;
152     return strdup (string);
153 #endif
154 }
155
156 /**
157  * Releases (if needed) a localized or uniformized string.
158  * @param str non-NULL return value from FromLocale() or ToLocale().
159  */
160 void LocaleFree (const char *str)
161 {
162 #if defined (USE_ICONV)
163     if (!find_charset ())
164         free ((char *)str);
165 #elif defined (USE_MB2MB)
166     free ((char *)str);
167 #else
168     (void)str;
169 #endif
170 }
171
172
173 /**
174  * Converts a string from the system locale character encoding to UTF-8.
175  *
176  * @param locale nul-terminated string to convert
177  *
178  * @return a nul-terminated UTF-8 string, or NULL in case of error.
179  * To avoid memory leak, you have to pass the result to LocaleFree()
180  * when it is no longer needed.
181  */
182 char *FromLocale (const char *locale)
183 {
184     return locale_fast (locale, true);
185 }
186
187 /**
188  * converts a string from the system locale character encoding to utf-8,
189  * the result is always allocated on the heap.
190  *
191  * @param locale nul-terminated string to convert
192  *
193  * @return a nul-terminated utf-8 string, or null in case of error.
194  * The result must be freed using free() - as with the strdup() function.
195  */
196 char *FromLocaleDup (const char *locale)
197 {
198     return locale_dup (locale, true);
199 }
200
201
202 /**
203  * ToLocale: converts an UTF-8 string to local system encoding.
204  *
205  * @param utf8 nul-terminated string to be converted
206  *
207  * @return a nul-terminated string, or NULL in case of error.
208  * To avoid memory leak, you have to pass the result to LocaleFree()
209  * when it is no longer needed.
210  */
211 char *ToLocale (const char *utf8)
212 {
213     return locale_fast (utf8, false);
214 }
215
216
217 /**
218  * converts a string from UTF-8 to the system locale character encoding,
219  * the result is always allocated on the heap.
220  *
221  * @param utf8 nul-terminated string to convert
222  *
223  * @return a nul-terminated string, or null in case of error.
224  * The result must be freed using free() - as with the strdup() function.
225  */
226 char *ToLocaleDup (const char *utf8)
227 {
228     return locale_dup (utf8, false);
229 }
230
231 /**
232  * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
233  * appropriate conversion to local encoding.
234  */
235 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
236 {
237     char *utf8;
238     int res = vasprintf( &utf8, fmt, ap );
239     if( res == -1 )
240         return -1;
241
242     *str = ToLocaleDup( utf8 );
243     free( utf8 );
244     return res;
245 }
246
247 /**
248  * Formats an UTF-8 string as vfprintf(), then print it, with
249  * appropriate conversion to local encoding.
250  */
251 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
252 {
253     char *str;
254     int res = utf8_vasprintf( &str, fmt, ap );
255     if( res == -1 )
256         return -1;
257
258     fputs( str, stream );
259     free( str );
260     return res;
261 }
262
263 /**
264  * Formats an UTF-8 string as fprintf(), then print it, with
265  * appropriate conversion to local encoding.
266  */
267 int utf8_fprintf( FILE *stream, const char *fmt, ... )
268 {
269     va_list ap;
270     int res;
271
272     va_start( ap, fmt );
273     res = utf8_vfprintf( stream, fmt, ap );
274     va_end( ap );
275     return res;
276 }
277
278
279 static char *CheckUTF8( char *str, char rep )
280 {
281     uint8_t *ptr = (uint8_t *)str;
282     assert (str != NULL);
283
284     for (;;)
285     {
286         uint8_t c = ptr[0];
287         int charlen = -1;
288
289         if (c == '\0')
290             break;
291
292         for (int i = 0; i < 7; i++)
293             if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
294             {
295                 charlen = i;
296                 break;
297             }
298
299         switch (charlen)
300         {
301             case 0: // 7-bit ASCII character -> OK
302                 ptr++;
303                 continue;
304
305             case -1: // 1111111x -> error
306             case 1: // continuation byte -> error
307                 goto error;
308         }
309
310         assert (charlen >= 2);
311
312         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
313         for (int i = 1; i < charlen; i++)
314         {
315             assert (cp < (1 << 26));
316             c = ptr[i];
317
318             if ((c == '\0') // unexpected end of string
319              || ((c >> 6) != 2)) // not a continuation byte
320                 goto error;
321
322             cp = (cp << 6) | (ptr[i] & 0x3f);
323         }
324
325         if (cp < 128) // overlong (special case for ASCII)
326             goto error;
327         if (cp < (1u << (5 * charlen - 3))) // overlong
328             goto error;
329
330         ptr += charlen;
331         continue;
332
333     error:
334         if (rep == 0)
335             return NULL;
336         *ptr++ = rep;
337         str = NULL;
338     }
339
340     return str;
341 }
342
343 /**
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.
347  *
348  * @return str if it was valid UTF-8, NULL if not.
349  */
350 char *EnsureUTF8( char *str )
351 {
352     return CheckUTF8( str, '?' );
353 }
354
355
356 /**
357  * Checks whether a string is a valid UTF-8 byte sequence.
358  *
359  * @param str nul-terminated string to be checked
360  *
361  * @return str if it was valid UTF-8, NULL if not.
362  */
363 const char *IsUTF8( const char *str )
364 {
365     return CheckUTF8( (char *)str, 0 );
366 }