1 /*****************************************************************************
2 * unicode.c: Unicode <-> locale functions
3 *****************************************************************************
4 * Copyright (C) 2005-2006 the VideoLAN team
7 * Authors: Rémi Denis-Courmont <rem # videolan.org>
9 * UTF16toUTF8() adapted from Perl 5 (also GPL'd)
10 * Copyright (C) 1998-2002, Larry Wall
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25 *****************************************************************************/
27 /*****************************************************************************
29 *****************************************************************************/
39 #include <sys/types.h>
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
51 # define lstat( a, b ) stat(a, b)
55 /* Define this if the OS always use UTF-8 internally */
56 # define ASSUME_UTF8 1
60 # if defined (HAVE_ICONV)
61 /* libiconv is more powerful than Win32 API (it has translit) */
63 # elif defined (WIN32) || defined (UNDER_CE)
66 # error No UTF8 charset conversion implemented on this platform!
74 } from_locale, to_locale;
77 void LocaleInit( vlc_object_t *p_this )
82 if( vlc_current_charset( &psz_charset ) )
84 from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
88 char psz_buf[strlen( psz_charset ) + sizeof( "//translit" )];
92 * Still allow non-ASCII characters when the locale is not set.
93 * Western Europeans are being favored for historical reasons.
95 if( strcmp( psz_charset, "ASCII" ) )
97 sprintf( psz_buf, "%s//translit", psz_charset );
101 psz_conv = "ISO-8859-1//translit";
103 vlc_mutex_init( p_this, &from_locale.lock );
104 vlc_mutex_init( p_this, &to_locale.lock );
105 from_locale.hd = vlc_iconv_open( "UTF-8", psz_conv );
106 to_locale.hd = vlc_iconv_open( psz_conv, "UTF-8" );
111 assert( (from_locale.hd == (vlc_iconv_t)(-1))
112 == (to_locale.hd == (vlc_iconv_t)(-1)) );
118 void LocaleDeinit( void )
121 if( to_locale.hd != (vlc_iconv_t)(-1) )
123 vlc_iconv_close( to_locale.hd );
124 vlc_mutex_destroy( &to_locale.lock );
127 if( from_locale.hd != (vlc_iconv_t)(-1) )
129 vlc_iconv_close( from_locale.hd );
130 vlc_mutex_destroy( &from_locale.lock );
136 static char *MB2MB( const char *string, UINT fromCP, UINT toCP )
142 len = MultiByteToWideChar( fromCP, 0, string, -1, NULL, 0 );
148 MultiByteToWideChar( fromCP, 0, string, -1, wide, len );
149 len = WideCharToMultiByte( toCP, 0, wide, -1, NULL, 0, NULL, NULL );
154 WideCharToMultiByte( toCP, 0, wide, -1, out, len, NULL, NULL );
160 * FromLocale: converts a locale string to UTF-8
162 * @param locale nul-terminated string to be converted
164 * @return a nul-terminated UTF-8 string, or NULL in case of error.
165 * To avoid memory leak, you have to pass the result to LocaleFree()
166 * when it is no longer needed.
168 char *FromLocale( const char *locale )
175 if( from_locale.hd != (vlc_iconv_t)(-1) )
177 const char *iptr = locale;
178 size_t inb = strlen( locale );
179 size_t outb = inb * 6 + 1;
180 char output[outb], *optr = output;
182 vlc_mutex_lock( &from_locale.lock );
183 vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
185 while( vlc_iconv( from_locale.hd, &iptr, &inb, &optr, &outb )
192 vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
194 vlc_mutex_unlock( &from_locale.lock );
198 assert (*iptr == '\0');
199 assert (*optr == '\0');
200 assert (strlen( output ) == (size_t)(optr - output));
201 return strdup( output );
203 # endif /* USE_ICONV */
204 return (char *)locale;
206 return MB2MB( locale, CP_ACP, CP_UTF8 );
210 char *FromLocaleDup( const char *locale )
212 #if defined (ASSUME_UTF8)
213 return strdup( locale );
216 if (from_locale.hd == (vlc_iconv_t)(-1))
217 return strdup( locale );
219 return FromLocale( locale );
225 * ToLocale: converts a UTF-8 string to local system encoding.
227 * @param utf8 nul-terminated string to be converted
229 * @return a nul-terminated string, or NULL in case of error.
230 * To avoid memory leak, you have to pass the result to LocaleFree()
231 * when it is no longer needed.
233 char *ToLocale( const char *utf8 )
240 if( to_locale.hd != (vlc_iconv_t)(-1) )
242 const char *iptr = utf8;
243 size_t inb = strlen( utf8 );
244 /* FIXME: I'm not sure about the value for the multiplication
245 * (for western people, multiplication is not needed) */
246 size_t outb = inb * 2 + 1;
248 char output[outb], *optr = output;
250 vlc_mutex_lock( &to_locale.lock );
251 vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
253 while( vlc_iconv( to_locale.hd, &iptr, &inb, &optr, &outb )
256 *optr++ = '?'; /* should not happen, and yes, it sucks */
260 vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
262 vlc_mutex_unlock( &to_locale.lock );
266 assert (*iptr == '\0');
267 assert (*optr == '\0');
268 assert (strlen( output ) == (size_t)(optr - output));
269 return strdup( output );
271 # endif /* USE_ICONV */
274 return MB2MB( utf8, CP_UTF8, CP_ACP );
278 char *ToLocaleDup( const char *utf8 )
280 #if defined (ASSUME_UTF8)
281 return strdup( utf8 );
284 if (to_locale.hd == (vlc_iconv_t)(-1))
285 return strdup( utf8 );
287 return ToLocale( utf8 );
291 void LocaleFree( const char *str )
294 if( to_locale.hd == (vlc_iconv_t)(-1) )
305 * utf8_fopen: Calls fopen() after conversion of file name to OS locale
307 FILE *utf8_fopen( const char *filename, const char *mode )
309 #if defined (WIN32) || defined (UNDER_CE)
310 if( GetVersion() < 0x80000000 )
312 /* for Windows NT and above */
313 wchar_t wpath[MAX_PATH + 1];
314 size_t len = strlen( mode ) + 1;
317 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH )
318 || !MultiByteToWideChar( CP_ACP, 0, mode, len, wmode, len ) )
323 wpath[MAX_PATH] = L'\0';
326 * fopen() cannot open files with non-“ANSI” characters on Windows.
327 * We use _wfopen() instead. Same thing for mkdir() and stat().
329 return _wfopen( wpath, wmode );
332 const char *local_name = ToLocale( filename );
334 if( local_name != NULL )
336 FILE *stream = fopen( local_name, mode );
337 LocaleFree( local_name );
347 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
349 int utf8_mkdir( const char *dirname )
351 #if defined (UNDER_CE) || defined (WIN32)
352 wchar_t wname[MAX_PATH + 1];
353 char mod[MAX_PATH + 1];
356 /* Convert '/' into '\' */
357 for( i = 0; *dirname; i++ )
360 return -1; /* overflow */
362 if( *dirname == '/' )
371 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
376 wname[MAX_PATH] = L'\0';
378 if( CreateDirectoryW( wname, NULL ) == 0 )
380 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
388 char *locname = ToLocale( dirname );
391 if( locname == NULL )
396 res = mkdir( locname, 0755 );
398 LocaleFree( locname );
404 void *utf8_opendir( const char *dirname )
406 /* TODO: support for WinNT non-ACP filenames */
407 const char *local_name = ToLocale( dirname );
409 if( local_name != NULL )
411 DIR *dir = vlc_opendir_wrapper( local_name );
412 LocaleFree( local_name );
420 const char *utf8_readdir( void *dir )
424 ent = vlc_readdir_wrapper( (DIR *)dir );
428 return FromLocale( ent->d_name );
431 static int dummy_select( const char *str )
437 int utf8_scandir( const char *dirname, char ***namelist,
438 int (*select)( const char * ),
439 int (*compar)( const char **, const char ** ) )
441 DIR *dir = utf8_opendir( dirname );
444 select = dummy_select;
454 while( ( entry = utf8_readdir( dir ) ) != NULL )
457 char *utf_entry = strdup( entry );
459 if( utf_entry == NULL )
462 if( !select( utf_entry ) )
468 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
475 tab[num++] = utf_entry;
477 vlc_closedir_wrapper( dir );
480 qsort( tab, num, sizeof( tab[0] ),
481 (int (*)( const void *, const void *))compar );
489 for( i = 0; i < num; i++ )
498 static int utf8_statEx( const char *filename, void *buf,
501 #if defined (WIN32) || defined (UNDER_CE)
502 /* retrieve Windows OS version */
503 if( GetVersion() < 0x80000000 )
505 /* for Windows NT and above */
506 wchar_t wpath[MAX_PATH + 1];
508 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
513 wpath[MAX_PATH] = L'\0';
515 return _wstati64( wpath, (struct _stati64 *)buf );
518 #ifdef HAVE_SYS_STAT_H
519 const char *local_name = ToLocale( filename );
521 if( local_name != NULL )
523 int res = deref ? stat( local_name, (struct stat *)buf )
524 : lstat( local_name, (struct stat *)buf );
525 LocaleFree( local_name );
534 int utf8_stat( const char *filename, void *buf)
536 return utf8_statEx( filename, buf, VLC_TRUE );
539 int utf8_lstat( const char *filename, void *buf)
541 return utf8_statEx( filename, buf, VLC_FALSE );
545 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
547 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
550 int res = vasprintf( &utf8, fmt, ap );
554 *str = ToLocaleDup( utf8 );
559 static int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
562 int res = utf8_vasprintf( &str, fmt, ap );
566 fputs( str, stream );
571 int utf8_fprintf( FILE *stream, const char *fmt, ... )
577 res = utf8_vfprintf( stream, fmt, ap );
583 static char *CheckUTF8( char *str, char rep )
584 #define isutf8cont( c ) (((c) >= 0x80) && ((c) <= 0xBF))
586 unsigned char *ptr, c;
588 ptr = (unsigned char *)str;
589 while( (c = *ptr) != '\0' )
591 /* US-ASCII, 1 byte */
596 if( ( c >= 0xC2 ) && ( c <= 0xDF ) )
599 if( isutf8cont( c ) )
609 if( ( c >= 0xA0 ) && ( c <= 0xBF ) )
612 if( isutf8cont( c ) )
621 if( ( ( c >= 0xE1 ) && ( c <= 0xEC ) ) || ( c == 0xEC )
622 || ( c == 0xEE ) || ( c == 0xEF ) )
625 if( isutf8cont( c ) )
628 if( isutf8cont( c ) )
640 if( ( c >= 0x80 ) && ( c <= 0x9F ) )
643 if( isutf8cont( c ) )
656 if( ( c >= 0x90 ) && ( c <= 0xBF ) )
659 if( isutf8cont( c ) )
662 if( isutf8cont( c ) )
674 if( ( c >= 0xF1 ) && ( c <= 0xF3 ) )
677 if( isutf8cont( c ) )
680 if( isutf8cont( c ) )
683 if( isutf8cont( c ) )
697 if( ( c >= 0x80 ) && ( c <= 0x8F ) )
700 if( isutf8cont( c ) )
703 if( isutf8cont( c ) )
730 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
731 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
732 * so we don't try that, even though it would be less disruptive.
734 * @return str if it was valid UTF-8, NULL if not.
736 char *EnsureUTF8( char *str )
738 return CheckUTF8( str, '?' );
743 * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
745 * @param str nul-terminated string to be checked
747 * @return str if it was valid UTF-8, NULL if not.
749 const char *IsUTF8( const char *str )
751 return CheckUTF8( (char *)str, 0 );
756 * UTF32toUTF8(): converts an array from UTF-32 (host byte order)
759 * @param src the UTF-32 table to be converted
760 * @param len the number of code points to be converted from src
761 * (ie. the number of uint32_t in the table pointed to by src)
762 * @param newlen an optional pointer. If not NULL, *newlen will
763 * contain the total number of bytes written.
765 * @return the result of the conversion (must be free'd())
766 * or NULL on error (in that case, *newlen is undefined).
769 UTF32toUTF8( const uint32_t *src, size_t len, size_t *newlen )
773 /* allocate memory */
774 out = res = (char *)malloc( 6 * len );
780 uint32_t uv = *src++;
791 *out++ = (( uv >> 6) | 0xc0);
792 *out++ = (( uv & 0x3f) | 0x80);
798 *out++ = (( uv >> 12) | 0xe0);
799 *out++ = (((uv >> 6) & 0x3f) | 0x80);
800 *out++ = (( uv & 0x3f) | 0x80);
806 *out++ = (( uv >> 18) | 0xf0);
807 *out++ = (((uv >> 12) & 0x3f) | 0x80);
808 *out++ = (((uv >> 6) & 0x3f) | 0x80);
809 *out++ = (( uv & 0x3f) | 0x80);
819 res = realloc( res, len );
826 * FromUTF32(): converts an UTF-32 string to UTF-8.
828 * @param src UTF-32 bytes sequence, aligned on a 32-bits boundary.
830 * @return the result of the conversion (must be free()'d),
831 * or NULL in case of error.
833 char *FromUTF32( const uint32_t *src )
838 /* determine the size of the string */
839 for( len = 1, in = src; *in; len++ )
842 return UTF32toUTF8( src, len, NULL );
846 * UTF16toUTF8: converts UTF-16 (host byte order) to UTF-8
848 * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary
849 * @param len number of uint16_t to convert
852 UTF16toUTF8( const uint16_t *in, size_t len, size_t *newlen )
856 /* allocate memory */
857 out = res = (char *)malloc( 3 * len );
875 *out++ = (( uv >> 6) | 0xc0);
876 *out++ = (( uv & 0x3f) | 0x80);
879 if( (uv >= 0xd800) && (uv < 0xdbff) )
881 uint16_t low = GetWBE( in );
885 if( (low < 0xdc00) || (low >= 0xdfff) )
887 *out++ = '?'; /* Malformed surrogate */
891 uv = ((uv - 0xd800) << 10) + (low - 0xdc00) + 0x10000;
895 *out++ = (( uv >> 12) | 0xe0);
896 *out++ = (((uv >> 6) & 0x3f) | 0x80);
897 *out++ = (( uv & 0x3f) | 0x80);
902 *out++ = (( uv >> 18) | 0xf0);
903 *out++ = (((uv >> 12) & 0x3f) | 0x80);
904 *out++ = (((uv >> 6) & 0x3f) | 0x80);
905 *out++ = (( uv & 0x3f) | 0x80);
910 res = realloc( res, len );
918 * FromUTF16(): converts an UTF-16 string to UTF-8.
920 * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary.
922 * @return the result of the conversion (must be free()'d),
923 * or NULL in case of error.
925 char *FromUTF16( const uint16_t *src )
930 /* determine the size of the string */
931 for( len = 1, in = src; *in; len++ )
934 return UTF16toUTF8( src, len, NULL );