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 *****************************************************************************/
37 #include <sys/types.h>
44 #ifdef HAVE_SYS_STAT_H
45 # include <sys/stat.h>
57 # define lstat( a, b ) stat(a, b)
61 /* Define this if the OS always use UTF-8 internally */
62 # define ASSUME_UTF8 1
66 # if defined (HAVE_ICONV)
67 /* libiconv is more powerful than Win32 API (it has translit) */
69 # elif defined (WIN32) || defined (UNDER_CE)
72 # error No UTF8 charset conversion implemented on this platform!
76 typedef struct locale_data_t
78 #if defined (USE_ICONV)
81 #elif defined (USE_MB2MB)
87 static locale_data_t from_locale, to_locale;
90 void LocaleInit( vlc_object_t *p_this )
95 if( vlc_current_charset( &psz_charset ) )
97 from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
101 char psz_buf[strlen( psz_charset ) + sizeof( "//translit" )];
102 const char *psz_conv;
105 * Still allow non-ASCII characters when the locale is not set.
106 * Western Europeans are being favored for historical reasons.
108 if( strcmp( psz_charset, "ASCII" ) )
110 sprintf( psz_buf, "%s//translit", psz_charset );
114 psz_conv = "ISO-8859-1//translit";
116 vlc_mutex_init( p_this, &from_locale.lock );
117 vlc_mutex_init( p_this, &to_locale.lock );
118 from_locale.hd = vlc_iconv_open( "UTF-8", psz_conv );
119 to_locale.hd = vlc_iconv_open( psz_conv, "UTF-8" );
124 assert( (from_locale.hd == (vlc_iconv_t)(-1))
125 == (to_locale.hd == (vlc_iconv_t)(-1)) );
127 #elif defined (USE_MB2MB)
128 to_locale.toCP = from_locale.fromCP = CP_ACP;
129 from_locale.toCP = to_locale.fromCP = CP_UTF8;
135 void LocaleDeinit( void )
138 if( to_locale.hd != (vlc_iconv_t)(-1) )
140 vlc_iconv_close( to_locale.hd );
141 vlc_mutex_destroy( &to_locale.lock );
144 if( from_locale.hd != (vlc_iconv_t)(-1) )
146 vlc_iconv_close( from_locale.hd );
147 vlc_mutex_destroy( &from_locale.lock );
152 static char *locale_fast (const char *string, locale_data_t *p)
154 #if defined (USE_ICONV)
155 vlc_iconv_t hd = p->hd;
157 if (hd == (vlc_iconv_t)(-1))
158 return (char *)string;
160 const char *iptr = string;
161 size_t inb = strlen (string);
162 size_t outb = inb * 6 + 1;
163 char output[outb], *optr = output;
168 vlc_mutex_lock (&p->lock);
169 vlc_iconv (hd, NULL, NULL, NULL, NULL);
171 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
177 vlc_iconv (hd, NULL, NULL, NULL, NULL);
179 vlc_mutex_unlock (&p->lock);
183 assert (*iptr == '\0');
184 assert (*optr == '\0');
185 assert (strlen (output) == (size_t)(optr - output));
186 return strdup (output);
187 #elif defined (USE_MB2MB)
195 len = MultiByteToWideChar (p->fromCP, 0, string, -1, NULL, 0);
201 MultiByteToWideChar (p->fromCP, 0, string, -1, wide, len);
202 len = WideCharToMultiByte (p->toCP, 0, wide, -1, NULL, 0, NULL, NULL);
207 WideCharToMultiByte (p->toCP, 0, wide, -1, out, len, NULL, NULL);
210 return (char *)string;
215 static inline char *locale_dup (const char *string, locale_data_t *p)
217 #if defined (USE_ICONV)
218 return (p->hd == (vlc_iconv_t)(-1))
220 : locale_fast (string, p);
221 #elif defined (USE_MB2MB)
222 return locale_fast (string, p);
224 return strdup (string);
229 void LocaleFree (const char *str)
231 #if defined (USE_ICONV)
232 assert ((to_locale.hd == (vlc_iconv_t)(-1))
233 == (from_locale.hd == (vlc_iconv_t)(-1)));
235 if( to_locale.hd != (vlc_iconv_t)(-1) )
237 #elif defined (USE_MB2MB)
244 * FromLocale: converts a locale string to UTF-8
246 * @param locale nul-terminated string to be converted
248 * @return a nul-terminated UTF-8 string, or NULL in case of error.
249 * To avoid memory leak, you have to pass the result to LocaleFree()
250 * when it is no longer needed.
252 char *FromLocale (const char *locale)
254 return locale_fast (locale, &from_locale);
257 char *FromLocaleDup (const char *locale)
259 return locale_dup (locale, &from_locale);
264 * ToLocale: converts a UTF-8 string to local system encoding.
266 * @param utf8 nul-terminated string to be converted
268 * @return a nul-terminated string, or NULL in case of error.
269 * To avoid memory leak, you have to pass the result to LocaleFree()
270 * when it is no longer needed.
272 char *ToLocale (const char *utf8)
274 return locale_fast (utf8, &to_locale);
278 static char *ToLocaleDup (const char *utf8)
280 return locale_dup (utf8, &to_locale);
285 * utf8_open: open() wrapper for UTF-8 filenames
287 int utf8_open (const char *filename, int flags, mode_t mode)
289 #if defined (WIN32) || defined (UNDER_CE)
290 if (GetVersion() < 0x80000000)
292 /* for Windows NT and above */
293 wchar_t wpath[MAX_PATH + 1];
295 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
300 wpath[MAX_PATH] = L'\0';
303 * open() cannot open files with non-“ANSI” characters on Windows.
304 * We use _wopen() instead. Same thing for mkdir() and stat().
306 return _wopen (wpath, flags, mode);
309 const char *local_name = ToLocale (filename);
311 if (local_name == NULL)
317 int fd = open (local_name, flags, mode);
318 LocaleFree (local_name);
323 * utf8_fopen: fopen() wrapper for UTF-8 filenames
325 FILE *utf8_fopen (const char *filename, const char *mode)
327 int rwflags = 0, oflags = 0;
328 vlc_bool_t append = VLC_FALSE;
330 for (const char *ptr = mode; *ptr; ptr++)
346 oflags |= O_CREAT | O_TRUNC;
355 int fd = utf8_open (filename, rwflags | oflags, 0666);
359 if (append && (lseek (fd, 0, SEEK_END) == -1))
365 FILE *stream = fdopen (fd, mode);
373 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
375 int utf8_mkdir( const char *dirname )
377 #if defined (UNDER_CE) || defined (WIN32)
378 wchar_t wname[MAX_PATH + 1];
379 char mod[MAX_PATH + 1];
382 /* Convert '/' into '\' */
383 for( i = 0; *dirname; i++ )
386 return -1; /* overflow */
388 if( *dirname == '/' )
397 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
402 wname[MAX_PATH] = L'\0';
404 if( CreateDirectoryW( wname, NULL ) == 0 )
406 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
414 char *locname = ToLocale( dirname );
417 if( locname == NULL )
422 res = mkdir( locname, 0755 );
424 LocaleFree( locname );
430 void *utf8_opendir( const char *dirname )
432 /* TODO: support for WinNT non-ACP filenames */
433 const char *local_name = ToLocale( dirname );
435 if( local_name != NULL )
437 DIR *dir = vlc_opendir_wrapper( local_name );
438 LocaleFree( local_name );
447 char *utf8_readdir( void *dir )
451 ent = vlc_readdir_wrapper( (DIR *)dir );
455 return vlc_fix_readdir( ent->d_name );
458 static int dummy_select( const char *str )
464 int utf8_scandir( const char *dirname, char ***namelist,
465 int (*select)( const char * ),
466 int (*compar)( const char **, const char ** ) )
468 DIR *dir = utf8_opendir( dirname );
471 select = dummy_select;
481 while( ( entry = utf8_readdir( dir ) ) != NULL )
485 if( !select( entry ) )
491 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
500 vlc_closedir_wrapper( dir );
503 qsort( tab, num, sizeof( tab[0] ),
504 (int (*)( const void *, const void *))compar );
512 for( i = 0; i < num; i++ )
521 static int utf8_statEx( const char *filename, struct stat *buf,
524 #if defined (WIN32) || defined (UNDER_CE)
525 /* retrieve Windows OS version */
526 if( GetVersion() < 0x80000000 )
528 /* for Windows NT and above */
529 wchar_t wpath[MAX_PATH + 1];
531 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
536 wpath[MAX_PATH] = L'\0';
538 return _wstati64( wpath, buf );
541 #ifdef HAVE_SYS_STAT_H
542 const char *local_name = ToLocale( filename );
544 if( local_name != NULL )
546 int res = deref ? stat( local_name, buf )
547 : lstat( local_name, buf );
548 LocaleFree( local_name );
557 int utf8_stat( const char *filename, struct stat *buf)
559 return utf8_statEx( filename, buf, VLC_TRUE );
562 int utf8_lstat( const char *filename, struct stat *buf)
564 return utf8_statEx( filename, buf, VLC_FALSE );
568 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
570 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
573 int res = vasprintf( &utf8, fmt, ap );
577 *str = ToLocaleDup( utf8 );
582 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
585 int res = utf8_vasprintf( &str, fmt, ap );
589 fputs( str, stream );
594 int utf8_fprintf( FILE *stream, const char *fmt, ... )
600 res = utf8_vfprintf( stream, fmt, ap );
606 static char *CheckUTF8( char *str, char rep )
607 #define isutf8cont( c ) (((c) >= 0x80) && ((c) <= 0xBF))
609 unsigned char *ptr, c;
611 assert (str != NULL);
613 ptr = (unsigned char *)str;
614 while( (c = *ptr) != '\0' )
616 /* US-ASCII, 1 byte */
621 if( ( c >= 0xC2 ) && ( c <= 0xDF ) )
624 if( isutf8cont( c ) )
634 if( ( c >= 0xA0 ) && ( c <= 0xBF ) )
637 if( isutf8cont( c ) )
646 if( ( ( c >= 0xE1 ) && ( c <= 0xEC ) ) || ( c == 0xEC )
647 || ( c == 0xEE ) || ( c == 0xEF ) )
650 if( isutf8cont( c ) )
653 if( isutf8cont( c ) )
665 if( ( c >= 0x80 ) && ( c <= 0x9F ) )
668 if( isutf8cont( c ) )
681 if( ( c >= 0x90 ) && ( c <= 0xBF ) )
684 if( isutf8cont( c ) )
687 if( isutf8cont( c ) )
699 if( ( c >= 0xF1 ) && ( c <= 0xF3 ) )
702 if( isutf8cont( c ) )
705 if( isutf8cont( c ) )
708 if( isutf8cont( c ) )
722 if( ( c >= 0x80 ) && ( c <= 0x8F ) )
725 if( isutf8cont( c ) )
728 if( isutf8cont( c ) )
755 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
756 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
757 * so we don't try that, even though it would be less disruptive.
759 * @return str if it was valid UTF-8, NULL if not.
761 char *EnsureUTF8( char *str )
763 return CheckUTF8( str, '?' );
768 * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
770 * @param str nul-terminated string to be checked
772 * @return str if it was valid UTF-8, NULL if not.
774 const char *IsUTF8( const char *str )
776 return CheckUTF8( (char *)str, 0 );