]> git.sesse.net Git - vlc/blob - src/text/unicode.c
Remove WinCE
[vlc] / src / text / unicode.c
1 /*****************************************************************************
2  * unicode.c: Unicode <-> locale functions
3  *****************************************************************************
4  * Copyright (C) 2005-2006 VLC authors and VideoLAN
5  * Copyright © 2005-2010 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 it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * 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
33 #include "libvlc.h"
34 #include <vlc_charset.h>
35
36 #include <assert.h>
37
38 #include <stdio.h>
39 #include <stdarg.h>
40 #include <stdlib.h>
41 #include <sys/types.h>
42 #if defined(WIN32)
43 #  include <io.h>
44 #endif
45 #include <errno.h>
46 #include <wctype.h>
47
48 /**
49  * Formats an UTF-8 string as vfprintf(), then print it, with
50  * appropriate conversion to local encoding.
51  */
52 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
53 {
54 #ifndef WIN32
55     return vfprintf (stream, fmt, ap);
56 #else
57     char *str;
58     int res = vasprintf (&str, fmt, ap);
59     if (unlikely(res == -1))
60         return -1;
61
62     /* Writing to the console is a lot of fun on Microsoft Windows.
63      * If you use the standard I/O functions, you must use the OEM code page,
64      * which is different from the usual ANSI code page. Or maybe not, if the
65      * user called "chcp". Anyway, we prefer Unicode. */
66     int fd = _fileno (stream);
67     if (likely(fd != -1) && _isatty (fd))
68     {
69         wchar_t *wide = ToWide (str);
70         if (likely(wide != NULL))
71         {
72             HANDLE h = (HANDLE)((uintptr_t)_get_osfhandle (fd));
73             DWORD out;
74             /* XXX: It is not clear whether WriteConsole() wants the number of
75              * Unicode characters or the size of the wchar_t array. */
76             BOOL ok = WriteConsoleW (h, wide, wcslen (wide), &out, NULL);
77             free (wide);
78             if (ok)
79                 goto out;
80         }
81     }
82
83     char *ansi = ToANSI (str);
84     if (ansi != NULL)
85     {
86         fputs (ansi, stream);
87         free (ansi);
88     }
89     else
90         res = -1;
91 out:
92     free (str);
93     return res;
94 #endif
95 }
96
97 /**
98  * Formats an UTF-8 string as fprintf(), then print it, with
99  * appropriate conversion to local encoding.
100  */
101 int utf8_fprintf( FILE *stream, const char *fmt, ... )
102 {
103     va_list ap;
104     int res;
105
106     va_start( ap, fmt );
107     res = utf8_vfprintf( stream, fmt, ap );
108     va_end( ap );
109     return res;
110 }
111
112
113 /**
114  * Converts the first character from a UTF-8 sequence into a code point.
115  *
116  * @param str an UTF-8 bytes sequence
117  * @return 0 if str points to an empty string, i.e. the first character is NUL;
118  * number of bytes that the first character occupies (from 1 to 4) otherwise;
119  * -1 if the byte sequence was not a valid UTF-8 sequence.
120  */
121 size_t vlc_towc (const char *str, uint32_t *restrict pwc)
122 {
123     uint8_t *ptr = (uint8_t *)str, c;
124     uint32_t cp;
125
126     assert (str != NULL);
127
128     c = *ptr;
129     if (unlikely(c > 0xF4))
130         return -1;
131
132     int charlen = clz8 (c ^ 0xFF);
133     switch (charlen)
134     {
135         case 0: // 7-bit ASCII character -> short cut
136             *pwc = c;
137             return c != '\0';
138
139         case 1: // continuation byte -> error
140             return -1;
141
142         case 2:
143             if (unlikely(c < 0xC2)) // ASCII overlong
144                 return -1;
145             cp = (c & 0x1F) << 6;
146             break;
147
148         case 3:
149             cp = (c & 0x0F) << 12;
150             break;
151
152         case 4:
153             cp = (c & 0x07) << 16;
154             break;
155
156         default:
157             assert (0);
158     }
159
160     /* Unrolled continuation bytes decoding */
161     switch (charlen)
162     {
163         case 4:
164             c = *++ptr;
165             if (unlikely((c >> 6) != 2)) // not a continuation byte
166                 return -1;
167             cp |= (c & 0x3f) << 12;
168
169             if (unlikely(cp >= 0x110000)) // beyond Unicode range
170                 return -1;
171             /* fall through */
172         case 3:
173             c = *++ptr;
174             if (unlikely((c >> 6) != 2)) // not a continuation byte
175                 return -1;
176             cp |= (c & 0x3f) << 6;
177
178             if (unlikely(cp >= 0xD800 && cp < 0xE000)) // UTF-16 surrogate
179                 return -1;
180             if (unlikely(cp < (1u << (5 * charlen - 4)))) // non-ASCII overlong
181                 return -1;
182             /* fall through */
183         case 2:
184             c = *++ptr;
185             if (unlikely((c >> 6) != 2)) // not a continuation byte
186                 return -1;
187             cp |= (c & 0x3f);
188             break;
189     }
190
191     *pwc = cp;
192     return charlen;
193 }
194
195 /**
196  * Look for an UTF-8 string within another one in a case-insensitive fashion.
197  * Beware that this is quite slow. Contrary to strcasestr(), this function
198  * works regardless of the system character encoding, and handles multibyte
199  * code points correctly.
200
201  * @param haystack string to look into
202  * @param needle string to look for
203  * @return a pointer to the first occurence of the needle within the haystack,
204  * or NULL if no occurence were found.
205  */
206 char *vlc_strcasestr (const char *haystack, const char *needle)
207 {
208     ssize_t s;
209
210     do
211     {
212         const char *h = haystack, *n = needle;
213
214         for (;;)
215         {
216             uint32_t cph, cpn;
217
218             s = vlc_towc (n, &cpn);
219             if (s == 0)
220                 return (char *)haystack;
221             if (unlikely(s < 0))
222                 return NULL;
223             n += s;
224
225             s = vlc_towc (h, &cph);
226             if (s <= 0 || towlower (cph) != towlower (cpn))
227                 break;
228             h += s;
229         }
230
231         s = vlc_towc (haystack, &(uint32_t) { 0 });
232         haystack += s;
233     }
234     while (s > 0);
235
236     return NULL;
237 }
238
239 /**
240  * Replaces invalid/overlong UTF-8 sequences with question marks.
241  * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
242  * so we don't try that, even though it would be less disruptive.
243  *
244  * @return str if it was valid UTF-8, NULL if not.
245  */
246 char *EnsureUTF8( char *str )
247 {
248     char *ret = str;
249     size_t n;
250     uint32_t cp;
251
252     while ((n = vlc_towc (str, &cp)) != 0)
253         if (likely(n != (size_t)-1))
254             str += n;
255         else
256         {
257             *str++ = '?';
258             ret = NULL;
259         }
260     return ret;
261 }
262
263
264 /**
265  * Checks whether a string is a valid UTF-8 byte sequence.
266  *
267  * @param str nul-terminated string to be checked
268  *
269  * @return str if it was valid UTF-8, NULL if not.
270  */
271 const char *IsUTF8( const char *str )
272 {
273     size_t n;
274     uint32_t cp;
275
276     while ((n = vlc_towc (str, &cp)) != 0)
277         if (likely(n != (size_t)-1))
278             str += n;
279         else
280             return NULL;
281     return str;
282 }
283
284 /**
285  * Converts a string from the given character encoding to utf-8.
286  *
287  * @return a nul-terminated utf-8 string, or null in case of error.
288  * The result must be freed using free().
289  */
290 char *FromCharset(const char *charset, const void *data, size_t data_size)
291 {
292     vlc_iconv_t handle = vlc_iconv_open ("UTF-8", charset);
293     if (handle == (vlc_iconv_t)(-1))
294         return NULL;
295
296     char *out = NULL;
297     for(unsigned mul = 4; mul < 8; mul++ )
298     {
299         size_t in_size = data_size;
300         const char *in = data;
301         size_t out_max = mul * data_size;
302         char *tmp = out = malloc (1 + out_max);
303         if (!out)
304             break;
305
306         if (vlc_iconv (handle, &in, &in_size, &tmp, &out_max) != (size_t)(-1)) {
307             *tmp = '\0';
308             break;
309         }
310         free(out);
311         out = NULL;
312
313         if (errno != E2BIG)
314             break;
315     }
316     vlc_iconv_close(handle);
317     return out;
318 }
319
320 /**
321  * Converts a nul-terminated UTF-8 string to a given character encoding.
322  * @param charset iconv name of the character set
323  * @param in nul-terminated UTF-8 string
324  * @param outsize pointer to hold the byte size of result
325  *
326  * @return A pointer to the result, which must be released using free().
327  * The UTF-8 nul terminator is included in the conversion if the target
328  * character encoding supports it. However it is not included in the returned
329  * byte size.
330  * In case of error, NULL is returned and the byte size is undefined.
331  */
332 void *ToCharset(const char *charset, const char *in, size_t *outsize)
333 {
334     vlc_iconv_t hd = vlc_iconv_open (charset, "UTF-8");
335     if (hd == (vlc_iconv_t)(-1))
336         return NULL;
337
338     const size_t inlen = strlen (in);
339     void *res;
340
341     for (unsigned mul = 4; mul < 16; mul++)
342     {
343         size_t outlen = mul * (inlen + 1);
344         res = malloc (outlen);
345         if (unlikely(res == NULL))
346             break;
347
348         const char *inp = in;
349         char *outp = res;
350         size_t inb = inlen;
351         size_t outb = outlen - mul;
352
353         if (vlc_iconv (hd, &inp, &inb, &outp, &outb) != (size_t)(-1))
354         {
355             *outsize = outlen - mul - outb;
356             outb += mul;
357             inb = 1; /* append nul terminator if possible */
358             if (vlc_iconv (hd, &inp, &inb, &outp, &outb) != (size_t)(-1))
359                 break;
360             if (errno == EILSEQ) /* cannot translate nul terminator!? */
361                 break;
362         }
363
364         free (res);
365         res = NULL;
366         if (errno != E2BIG) /* conversion failure */
367             break;
368     }
369     vlc_iconv_close (hd);
370     return res;
371 }
372