]> git.sesse.net Git - vlc/blob - src/text/unicode.c
lua: improve the apple trailer sd:
[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 #include <errno.h>
44
45 #if defined (ASSUME_UTF8)
46 /* Cool */
47
48 #elif defined (WIN32) || defined (UNDER_CE)
49 # define USE_MB2MB 1
50 # include <io.h>
51
52 static char *locale_dup (const char *string, bool from)
53 {
54     char *out;
55     int len;
56
57     len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
58                                    0, string, -1, NULL, 0);
59     wchar_t *wide = malloc (len * sizeof (wchar_t));
60     if (wide == NULL)
61         return NULL;
62
63     MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
64     len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1,
65                                    NULL, 0, NULL, NULL);
66     out = malloc (len);
67     if (out != NULL)
68         WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len,
69                              NULL, NULL);
70     free (wide);
71     return out;
72 }
73
74 #elif defined (HAVE_ICONV)
75 # define USE_ICONV 1
76
77 static char *locale_dup (const char *string, bool from)
78 {
79     vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : "",
80                                      from ? "" : "UTF-8");
81     if (hd == (vlc_iconv_t)(-1))
82         return NULL; /* Uho! */
83
84     const char *iptr = string;
85     size_t inb = strlen (string);
86     size_t outb = inb * 6 + 1;
87     char output[outb], *optr = output;
88
89     while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
90     {
91         *optr++ = '?';
92         outb--;
93         iptr++;
94         inb--;
95         vlc_iconv (hd, NULL, NULL, NULL, NULL); /* reset */
96     }
97     *optr = '\0';
98     vlc_iconv_close (hd);
99
100     assert (inb == 0);
101     assert (*iptr == '\0');
102     assert (*optr == '\0');
103     assert (strlen (output) == (size_t)(optr - output));
104     return strdup (output);
105 }
106
107 #else
108 # error No UTF8 charset conversion implemented on this platform!
109 #endif
110
111
112 /**
113  * Releases (if needed) a localized or uniformized string.
114  * @param str non-NULL return value from FromLocale() or ToLocale().
115  */
116 void LocaleFree (const char *str)
117 {
118 #ifdef ASSUME_UTF8
119     (void) str;
120 #else
121     free ((char *)str);
122 #endif
123 }
124
125
126 /**
127  * Converts a string from the system locale character encoding to UTF-8.
128  *
129  * @param locale nul-terminated string to convert
130  *
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.
134  */
135 char *FromLocale (const char *locale)
136 {
137 #ifdef ASSUME_UTF8
138     return (char *)locale;
139 #else
140     return locale ? locale_dup (locale, true) : NULL;
141 #endif
142 }
143
144 /**
145  * converts a string from the system locale character encoding to utf-8,
146  * the result is always allocated on the heap.
147  *
148  * @param locale nul-terminated string to convert
149  *
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.
152  */
153 char *FromLocaleDup (const char *locale)
154 {
155 #ifdef ASSUME_UTF8
156     return strdup (locale);
157 #else
158     return locale_dup (locale, true);
159 #endif
160 }
161
162
163 /**
164  * ToLocale: converts an UTF-8 string to local system encoding.
165  *
166  * @param utf8 nul-terminated string to be converted
167  *
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.
171  */
172 char *ToLocale (const char *utf8)
173 {
174 #ifdef ASSUME_UTF8
175     return (char *)utf8;
176 #else
177     return utf8 ? locale_dup (utf8, false) : NULL;
178 #endif
179 }
180
181
182 /**
183  * converts a string from UTF-8 to the system locale character encoding,
184  * the result is always allocated on the heap.
185  *
186  * @param utf8 nul-terminated string to convert
187  *
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.
190  */
191 char *ToLocaleDup (const char *utf8)
192 {
193 #ifdef ASSUME_UTF8
194     return strdup (utf8);
195 #else
196     return locale_dup (utf8, false);
197 #endif
198 }
199
200 /**
201  * Formats an UTF-8 string as vasprintf(), then print it to stdout, with
202  * appropriate conversion to local encoding.
203  */
204 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
205 {
206     char *utf8;
207     int res = vasprintf( &utf8, fmt, ap );
208     if( res == -1 )
209         return -1;
210
211 #ifdef ASSUME_UTF8
212     *str = utf8;
213 #else
214     *str = ToLocaleDup( utf8 );
215     free( utf8 );
216 #endif
217     return res;
218 }
219
220 /**
221  * Formats an UTF-8 string as vfprintf(), then print it, with
222  * appropriate conversion to local encoding.
223  */
224 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
225 {
226     char *str;
227     int res;
228
229 #if defined( WIN32 ) && !defined( UNDER_CE )
230     /* Writing to the console is a lot of fun on Microsoft Windows.
231      * If you use the standard I/O functions, you must use the OEM code page,
232      * which is different from the usual ANSI code page. Or maybe not, if the
233      * user called "chcp". Anyway, we prefer Unicode. */
234     int fd = _fileno (stream);
235     if (likely(fd != -1) && _isatty (fd))
236     {
237         res = vasprintf (&str, fmt, ap);
238         if (unlikely(res == -1))
239             return -1;
240
241         size_t wlen = 2 * (res + 1);
242         wchar_t *wide = malloc (wlen);
243         if (likely(wide != NULL))
244         {
245             wlen = MultiByteToWideChar (CP_UTF8, 0, str, res + 1, wide, wlen);
246             if (wlen > 0)
247             {
248                 HANDLE h = (HANDLE)(intptr_t)_get_osfhandle (fd);
249                 DWORD out;
250
251                 WriteConsoleW (h, wide, wlen - 1, &out, NULL);
252             }
253             else
254                 res = -1;
255             free (wide);
256         }
257         else
258             res = -1;
259         free (str);
260         return res;
261     }
262 #endif
263
264     res = utf8_vasprintf (&str, fmt, ap);
265     if (unlikely(res == -1))
266         return -1;
267
268     fputs( str, stream );
269     free( str );
270     return res;
271 }
272
273 /**
274  * Formats an UTF-8 string as fprintf(), then print it, with
275  * appropriate conversion to local encoding.
276  */
277 int utf8_fprintf( FILE *stream, const char *fmt, ... )
278 {
279     va_list ap;
280     int res;
281
282     va_start( ap, fmt );
283     res = utf8_vfprintf( stream, fmt, ap );
284     va_end( ap );
285     return res;
286 }
287
288
289 static char *CheckUTF8( char *str, char rep )
290 {
291     uint8_t *ptr = (uint8_t *)str;
292     assert (str != NULL);
293
294     for (;;)
295     {
296         uint8_t c = ptr[0];
297
298         if (c == '\0')
299             break;
300
301         if (c > 0xF4)
302             goto error;
303
304         int charlen = clz8 (c ^ 0xFF);
305         switch (charlen)
306         {
307             case 0: // 7-bit ASCII character -> OK
308                 ptr++;
309                 continue;
310
311             case 1: // continuation byte -> error
312                 goto error;
313         }
314
315         assert (charlen >= 2 && charlen <= 4);
316
317         uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
318         for (int i = 1; i < charlen; i++)
319         {
320             assert (cp < (1 << 26));
321             c = ptr[i];
322
323             if ((c >> 6) != 2) // not a continuation byte
324                 goto error;
325
326             cp = (cp << 6) | (ptr[i] & 0x3f);
327         }
328
329         switch (charlen)
330         {
331             case 4:
332                 if (cp > 0x10FFFF) // beyond Unicode
333                     goto error;
334             case 3:
335                 if (cp >= 0xD800 && cp < 0xC000) // UTF-16 surrogate
336                     goto error;
337             case 2:
338                 if (cp < 128) // ASCII overlong
339                     goto error;
340                 if (cp < (1u << (5 * charlen - 3))) // overlong
341                     goto error;
342         }
343         ptr += charlen;
344         continue;
345
346     error:
347         if (rep == 0)
348             return NULL;
349         *ptr++ = rep;
350         str = NULL;
351     }
352
353     return str;
354 }
355
356 /**
357  * Replaces invalid/overlong UTF-8 sequences with question marks.
358  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
359  * so we don't try that, even though it would be less disruptive.
360  *
361  * @return str if it was valid UTF-8, NULL if not.
362  */
363 char *EnsureUTF8( char *str )
364 {
365     return CheckUTF8( str, '?' );
366 }
367
368
369 /**
370  * Checks whether a string is a valid UTF-8 byte sequence.
371  *
372  * @param str nul-terminated string to be checked
373  *
374  * @return str if it was valid UTF-8, NULL if not.
375  */
376 const char *IsUTF8( const char *str )
377 {
378     return CheckUTF8( (char *)str, 0 );
379 }
380
381 /**
382  * Converts a string from the given character encoding to utf-8.
383  *
384  * @return a nul-terminated utf-8 string, or null in case of error.
385  * The result must be freed using free().
386  */
387 char *FromCharset(const char *charset, const void *data, size_t data_size)
388 {
389     vlc_iconv_t handle = vlc_iconv_open ("UTF-8", charset);
390     if (handle == (vlc_iconv_t)(-1))
391         return NULL;
392
393     char *out = NULL;
394     for(unsigned mul = 4; mul < 8; mul++ )
395     {
396         size_t in_size = data_size;
397         const char *in = data;
398         size_t out_max = mul * data_size;
399         char *tmp = out = malloc (1 + out_max);
400         if (!out)
401             break;
402
403         if (vlc_iconv (handle, &in, &in_size, &tmp, &out_max) != (size_t)(-1)) {
404             *tmp = '\0';
405             break;
406         }
407         free(out);
408         out = NULL;
409
410         if (errno != E2BIG)
411             break;
412     }
413     vlc_iconv_close(handle);
414     return out;
415 }
416