]> git.sesse.net Git - vlc/blob - src/text/unicode.c
Add some fallback for language we have a translation
[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 = malloc (len * sizeof (wchar_t));
122     if (wide == NULL)
123         return NULL;
124
125     MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
126     len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
127                                    NULL, 0, NULL, NULL);
128     out = malloc (len);
129     if (out != NULL)
130         WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
131                              NULL, NULL);
132     free (wide);
133     return out;
134 #else
135     (void)from;
136     return (char *)string;
137 #endif
138 }
139
140
141 static inline char *locale_dup (const char *string, bool from)
142 {
143     assert( string );
144
145 #if defined (USE_ICONV)
146     if (find_charset ())
147         return strdup (string);
148     return locale_fast (string, from);
149 #elif defined (USE_MB2MB)
150     return locale_fast (string, from);
151 #else
152     (void)from;
153     return strdup (string);
154 #endif
155 }
156
157 /**
158  * Releases (if needed) a localized or uniformized string.
159  * @param str non-NULL return value from FromLocale() or ToLocale().
160  */
161 void LocaleFree (const char *str)
162 {
163 #if defined (USE_ICONV)
164     if (!find_charset ())
165         free ((char *)str);
166 #elif defined (USE_MB2MB)
167     free ((char *)str);
168 #else
169     (void)str;
170 #endif
171 }
172
173
174 /**
175  * Converts a string from the system locale character encoding to UTF-8.
176  *
177  * @param locale nul-terminated string to convert
178  *
179  * @return a nul-terminated UTF-8 string, or NULL in case of error.
180  * To avoid memory leak, you have to pass the result to LocaleFree()
181  * when it is no longer needed.
182  */
183 char *FromLocale (const char *locale)
184 {
185     return locale_fast (locale, true);
186 }
187
188 /**
189  * converts a string from the system locale character encoding to utf-8,
190  * the result is always allocated on the heap.
191  *
192  * @param locale nul-terminated string to convert
193  *
194  * @return a nul-terminated utf-8 string, or null in case of error.
195  * The result must be freed using free() - as with the strdup() function.
196  */
197 char *FromLocaleDup (const char *locale)
198 {
199     return locale_dup (locale, true);
200 }
201
202
203 /**
204  * ToLocale: converts an UTF-8 string to local system encoding.
205  *
206  * @param utf8 nul-terminated string to be converted
207  *
208  * @return a nul-terminated string, or NULL in case of error.
209  * To avoid memory leak, you have to pass the result to LocaleFree()
210  * when it is no longer needed.
211  */
212 char *ToLocale (const char *utf8)
213 {
214     return locale_fast (utf8, false);
215 }
216
217
218 /**
219  * converts a string from UTF-8 to the system locale character encoding,
220  * the result is always allocated on the heap.
221  *
222  * @param utf8 nul-terminated string to convert
223  *
224  * @return a nul-terminated string, or null in case of error.
225  * The result must be freed using free() - as with the strdup() function.
226  */
227 char *ToLocaleDup (const char *utf8)
228 {
229     return locale_dup (utf8, false);
230 }
231
232 /**
233  * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
234  * appropriate conversion to local encoding.
235  */
236 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
237 {
238     char *utf8;
239     int res = vasprintf( &utf8, fmt, ap );
240     if( res == -1 )
241         return -1;
242
243     *str = ToLocaleDup( utf8 );
244     free( utf8 );
245     return res;
246 }
247
248 /**
249  * Formats an UTF-8 string as vfprintf(), then print it, with
250  * appropriate conversion to local encoding.
251  */
252 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
253 {
254     char *str;
255     int res = utf8_vasprintf( &str, fmt, ap );
256     if( res == -1 )
257         return -1;
258
259     fputs( str, stream );
260     free( str );
261     return res;
262 }
263
264 /**
265  * Formats an UTF-8 string as fprintf(), then print it, with
266  * appropriate conversion to local encoding.
267  */
268 int utf8_fprintf( FILE *stream, const char *fmt, ... )
269 {
270     va_list ap;
271     int res;
272
273     va_start( ap, fmt );
274     res = utf8_vfprintf( stream, fmt, ap );
275     va_end( ap );
276     return res;
277 }
278
279
280 static char *CheckUTF8( char *str, char rep )
281 {
282     uint8_t *ptr = (uint8_t *)str;
283     assert (str != NULL);
284
285     for (;;)
286     {
287         uint8_t c = ptr[0];
288         int charlen = -1;
289
290         if (c == '\0')
291             break;
292
293         for (int i = 0; i < 7; i++)
294             if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
295             {
296                 charlen = i;
297                 break;
298             }
299
300         switch (charlen)
301         {
302             case 0: // 7-bit ASCII character -> OK
303                 ptr++;
304                 continue;
305
306             case -1: // 1111111x -> error
307             case 1: // continuation byte -> error
308                 goto error;
309         }
310
311         assert (charlen >= 2);
312
313         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
314         for (int i = 1; i < charlen; i++)
315         {
316             assert (cp < (1 << 26));
317             c = ptr[i];
318
319             if ((c == '\0') // unexpected end of string
320              || ((c >> 6) != 2)) // not a continuation byte
321                 goto error;
322
323             cp = (cp << 6) | (ptr[i] & 0x3f);
324         }
325
326         if (cp < 128) // overlong (special case for ASCII)
327             goto error;
328         if (cp < (1u << (5 * charlen - 3))) // overlong
329             goto error;
330
331         ptr += charlen;
332         continue;
333
334     error:
335         if (rep == 0)
336             return NULL;
337         *ptr++ = rep;
338         str = NULL;
339     }
340
341     return str;
342 }
343
344 /**
345  * Replaces invalid/overlong UTF-8 sequences with question marks.
346  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
347  * so we don't try that, even though it would be less disruptive.
348  *
349  * @return str if it was valid UTF-8, NULL if not.
350  */
351 char *EnsureUTF8( char *str )
352 {
353     return CheckUTF8( str, '?' );
354 }
355
356
357 /**
358  * Checks whether a string is a valid UTF-8 byte sequence.
359  *
360  * @param str nul-terminated string to be checked
361  *
362  * @return str if it was valid UTF-8, NULL if not.
363  */
364 const char *IsUTF8( const char *str )
365 {
366     return CheckUTF8( (char *)str, 0 );
367 }