1 /*****************************************************************************
2 * unicode.c: Unicode <-> locale functions
3 *****************************************************************************
4 * Copyright (C) 2005-2006 the VideoLAN team
5 * Copyright © 2005-2006 Rémi Denis-Courmont
8 * Authors: Rémi Denis-Courmont <rem # videolan.org>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
29 #include <vlc_charset.h>
30 #include "libvlc.h" /* utf8_mkdir */
38 #include <sys/types.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
58 # define lstat( a, b ) stat(a, b)
62 /* Define this if the OS always use UTF-8 internally */
63 # define ASSUME_UTF8 1
66 #if defined (ASSUME_UTF8)
68 #elif defined (WIN32) || defined (UNDER_CE)
70 #elif defined (HAVE_ICONV)
73 # error No UTF8 charset conversion implemented on this platform!
76 #if defined (USE_ICONV)
77 static char charset[sizeof ("CSISO11SWEDISHFORNAMES//translit")] = "";
79 static void find_charset_once (void)
82 if (vlc_current_charset (&psz_charset)
83 || (psz_charset == NULL)
84 || ((size_t)snprintf (charset, sizeof (charset), "%s//translit",
85 psz_charset) >= sizeof (charset)))
86 strcpy (charset, "UTF-8");
91 static int find_charset (void)
93 static pthread_once_t once = PTHREAD_ONCE_INIT;
94 pthread_once (&once, find_charset_once);
95 return !strcmp (charset, "UTF-8");
100 static char *locale_fast (const char *string, vlc_bool_t from)
102 #if defined (USE_ICONV)
104 return (char *)string;
106 vlc_iconv_t hd = vlc_iconv_open (from ? "UTF-8" : charset,
107 from ? charset : "UTF-8");
108 if (hd == (vlc_iconv_t)(-1))
109 return strdup (string); /* Uho! */
111 const char *iptr = string;
112 size_t inb = strlen (string);
113 size_t outb = inb * 6 + 1;
114 char output[outb], *optr = output;
119 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
125 vlc_iconv (hd, NULL, NULL, NULL, NULL);
128 vlc_iconv_close (hd);
131 assert (*iptr == '\0');
132 assert (*optr == '\0');
133 assert (strlen (output) == (size_t)(optr - output));
134 return strdup (output);
135 #elif defined (USE_MB2MB)
142 len = 1 + MultiByteToWideChar (from ? CP_ACP : CP_UTF8,
143 0, string, -1, NULL, 0);
146 MultiByteToWideChar (from ? CP_ACP : CP_UTF8, 0, string, -1, wide, len);
147 len = 1 + WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, NULL, 0, NULL, NULL);
152 WideCharToMultiByte (from ? CP_UTF8 : CP_ACP, 0, wide, -1, out, len, NULL, NULL);
155 return (char *)string;
160 static inline char *locale_dup (const char *string, vlc_bool_t from)
162 #if defined (USE_ICONV)
164 return strdup (string);
165 return locale_fast (string, from);
166 #elif defined (USE_MB2MB)
167 return locale_fast (string, from);
169 return strdup (string);
174 void LocaleFree (const char *str)
176 #if defined (USE_ICONV)
177 if (!find_charset ())
179 #elif defined (USE_MB2MB)
186 * FromLocale: converts a locale string to UTF-8
188 * @param locale nul-terminated string to be converted
190 * @return a nul-terminated UTF-8 string, or NULL in case of error.
191 * To avoid memory leak, you have to pass the result to LocaleFree()
192 * when it is no longer needed.
194 char *FromLocale (const char *locale)
196 return locale_fast (locale, VLC_TRUE);
199 char *FromLocaleDup (const char *locale)
201 return locale_dup (locale, VLC_TRUE);
206 * ToLocale: converts a UTF-8 string to local system encoding.
208 * @param utf8 nul-terminated string to be converted
210 * @return a nul-terminated string, or NULL in case of error.
211 * To avoid memory leak, you have to pass the result to LocaleFree()
212 * when it is no longer needed.
214 char *ToLocale (const char *utf8)
216 return locale_fast (utf8, VLC_FALSE);
220 static char *ToLocaleDup (const char *utf8)
222 return locale_dup (utf8, VLC_FALSE);
227 * utf8_open: open() wrapper for UTF-8 filenames
229 int utf8_open (const char *filename, int flags, mode_t mode)
231 #if defined (WIN32) || defined (UNDER_CE)
232 if (GetVersion() < 0x80000000)
234 /* for Windows NT and above */
235 wchar_t wpath[MAX_PATH + 1];
237 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
242 wpath[MAX_PATH] = L'\0';
245 * open() cannot open files with non-“ANSI” characters on Windows.
246 * We use _wopen() instead. Same thing for mkdir() and stat().
248 return _wopen (wpath, flags, mode);
251 const char *local_name = ToLocale (filename);
253 if (local_name == NULL)
259 int fd = open (local_name, flags, mode);
260 LocaleFree (local_name);
265 * utf8_fopen: fopen() wrapper for UTF-8 filenames
267 FILE *utf8_fopen (const char *filename, const char *mode)
269 int rwflags = 0, oflags = 0;
270 vlc_bool_t append = VLC_FALSE;
272 for (const char *ptr = mode; *ptr; ptr++)
288 oflags |= O_CREAT | O_TRUNC;
303 int fd = utf8_open (filename, rwflags | oflags, 0666);
307 if (append && (lseek (fd, 0, SEEK_END) == -1))
313 FILE *stream = fdopen (fd, mode);
321 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
323 * @param dirname a UTF-8 string with the name of the directory that you
325 * @return A 0 return value indicates success. A -1 return value indicates an
326 * error, and an error code is stored in errno
328 int utf8_mkdir( const char *dirname )
330 #if defined (UNDER_CE) || defined (WIN32)
331 wchar_t wname[MAX_PATH + 1];
332 char mod[MAX_PATH + 1];
335 /* Convert '/' into '\' */
336 for( i = 0; *dirname; i++ )
339 return -1; /* overflow */
341 if( *dirname == '/' )
350 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
355 wname[MAX_PATH] = L'\0';
357 if( CreateDirectoryW( wname, NULL ) == 0 )
359 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
367 char *locname = ToLocale( dirname );
370 if( locname == NULL )
375 res = mkdir( locname, 0755 );
377 LocaleFree( locname );
383 * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
385 * @param dirname UTF-8 representation of the directory name
387 * @return a pointer to the DIR struct. Release with closedir().
389 DIR *utf8_opendir( const char *dirname )
392 wchar_t wname[MAX_PATH + 1];
394 if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
396 wname[MAX_PATH] = L'\0';
397 return (DIR *)vlc_wopendir (wname);
400 const char *local_name = ToLocale( dirname );
402 if( local_name != NULL )
404 DIR *dir = opendir( local_name );
405 LocaleFree( local_name );
415 * utf8_readdir: a readdir wrapper that returns the name of the next entry
416 * in the directory as a UTF-8 string.
418 * @param dir The directory that is being read
420 * @return a UTF-8 string of the directory entry. Use free() to free this memory.
422 char *utf8_readdir( DIR *dir )
425 struct _wdirent *ent = vlc_wreaddir (dir);
429 return FromWide (ent->d_name);
433 ent = readdir( (DIR *)dir );
437 return vlc_fix_readdir( ent->d_name );
441 static int dummy_select( const char *str )
447 int utf8_loaddir( DIR *dir, char ***namelist,
448 int (*select)( const char * ),
449 int (*compar)( const char **, const char ** ) )
452 select = dummy_select;
464 while( ( entry = utf8_readdir( dir ) ) != NULL )
468 if( !select( entry ) )
474 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
485 qsort( tab, num, sizeof( tab[0] ),
486 (int (*)( const void *, const void *))compar );
494 for( i = 0; i < num; i++ )
503 int utf8_scandir( const char *dirname, char ***namelist,
504 int (*select)( const char * ),
505 int (*compar)( const char **, const char ** ) )
507 DIR *dir = utf8_opendir (dirname);
512 val = utf8_loaddir (dir, namelist, select, compar);
518 static int utf8_statEx( const char *filename, struct stat *buf,
521 #if defined (WIN32) || defined (UNDER_CE)
522 /* retrieve Windows OS version */
523 if( GetVersion() < 0x80000000 )
525 /* for Windows NT and above */
526 wchar_t wpath[MAX_PATH + 1];
528 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
533 wpath[MAX_PATH] = L'\0';
535 return _wstati64( wpath, buf );
538 #ifdef HAVE_SYS_STAT_H
539 const char *local_name = ToLocale( filename );
541 if( local_name != NULL )
543 int res = deref ? stat( local_name, buf )
544 : lstat( local_name, buf );
545 LocaleFree( local_name );
554 int utf8_stat( const char *filename, struct stat *buf)
556 return utf8_statEx( filename, buf, VLC_TRUE );
559 int utf8_lstat( const char *filename, struct stat *buf)
561 return utf8_statEx( filename, buf, VLC_FALSE );
565 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
567 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
570 int res = vasprintf( &utf8, fmt, ap );
574 *str = ToLocaleDup( utf8 );
579 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
582 int res = utf8_vasprintf( &str, fmt, ap );
586 fputs( str, stream );
591 int utf8_fprintf( FILE *stream, const char *fmt, ... )
597 res = utf8_vfprintf( stream, fmt, ap );
603 static char *CheckUTF8( char *str, char rep )
605 uint8_t *ptr = (uint8_t *)str;
606 assert (str != NULL);
616 for (int i = 0; i < 7; i++)
617 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
625 case 0: // 7-bit ASCII character -> OK
629 case -1: // 1111111x -> error
630 case 1: // continuation byte -> error
634 assert (charlen >= 2);
636 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
637 for (int i = 1; i < charlen; i++)
639 assert (cp < (1 << 26));
642 if ((c == '\0') // unexpected end of string
643 || ((c >> 6) != 2)) // not a continuation byte
646 cp = (cp << 6) | (ptr[i] & 0x3f);
649 if (cp < 128) // overlong (special case for ASCII)
651 if (cp < (1u << (5 * charlen - 3))) // overlong
668 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
669 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
670 * so we don't try that, even though it would be less disruptive.
672 * @return str if it was valid UTF-8, NULL if not.
674 char *EnsureUTF8( char *str )
676 return CheckUTF8( str, '?' );
681 * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
683 * @param str nul-terminated string to be checked
685 * @return str if it was valid UTF-8, NULL if not.
687 const char *IsUTF8( const char *str )
689 return CheckUTF8( (char *)str, 0 );