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>
50 # define lstat( a, b ) stat(a, b)
54 /* Define this if the OS always use UTF-8 internally */
55 # define ASSUME_UTF8 1
59 # if defined (HAVE_ICONV)
60 /* libiconv is more powerful than Win32 API (it has translit) */
62 # elif defined (WIN32) || defined (UNDER_CE)
65 # error No UTF8 charset conversion implemented on this platform!
73 } from_locale, to_locale;
76 void LocaleInit( vlc_object_t *p_this )
81 if( vlc_current_charset( &psz_charset ) )
83 from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
87 char psz_buf[strlen( psz_charset ) + sizeof( "//translit" )];
91 * Still allow non-ASCII characters when the locale is not set.
92 * Western Europeans are being favored for historical reasons.
94 if( strcmp( psz_charset, "ASCII" ) )
96 sprintf( psz_buf, "%s//translit", psz_charset );
100 psz_conv = "ISO-8859-1//translit";
102 vlc_mutex_init( p_this, &from_locale.lock );
103 vlc_mutex_init( p_this, &to_locale.lock );
104 from_locale.hd = vlc_iconv_open( "UTF-8", psz_conv );
105 to_locale.hd = vlc_iconv_open( psz_conv, "UTF-8" );
110 assert( (from_locale.hd == (vlc_iconv_t)(-1))
111 == (to_locale.hd == (vlc_iconv_t)(-1)) );
117 void LocaleDeinit( void )
120 if( to_locale.hd != (vlc_iconv_t)(-1) )
122 vlc_iconv_close( to_locale.hd );
123 vlc_mutex_destroy( &to_locale.lock );
126 if( from_locale.hd != (vlc_iconv_t)(-1) )
128 vlc_iconv_close( from_locale.hd );
129 vlc_mutex_destroy( &from_locale.lock );
135 static char *MB2MB( const char *string, UINT fromCP, UINT toCP )
141 len = MultiByteToWideChar( fromCP, 0, string, -1, NULL, 0 );
143 wide = (wchar_t *)malloc (len * sizeof (wchar_t));
147 MultiByteToWideChar( fromCP, 0, string, -1, wide, len );
148 len = WideCharToMultiByte( toCP, 0, wide, -1, NULL, 0, NULL, NULL );
152 WideCharToMultiByte( toCP, 0, wide, -1, out, len, NULL, NULL );
159 * FromLocale: converts a locale string to UTF-8
161 * @param locale nul-terminated string to be converted
163 * @return a nul-terminated UTF-8 string, or NULL in case of error.
164 * To avoid memory leak, you have to pass the result to LocaleFree()
165 * when it is no longer needed.
167 char *FromLocale( const char *locale )
174 if( from_locale.hd != (vlc_iconv_t)(-1) )
176 const char *iptr = locale;
177 size_t inb = strlen( locale );
178 size_t outb = inb * 6 + 1;
179 char output[outb], *optr = output;
181 vlc_mutex_lock( &from_locale.lock );
182 vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
184 while( vlc_iconv( from_locale.hd, &iptr, &inb, &optr, &outb )
191 vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
193 vlc_mutex_unlock( &from_locale.lock );
197 assert (*iptr == '\0');
198 assert (*optr == '\0');
199 assert (strlen( output ) == (size_t)(optr - output));
200 return strdup( output );
202 # endif /* USE_ICONV */
203 return (char *)locale;
205 return MB2MB( locale, CP_ACP, CP_UTF8 );
209 char *FromLocaleDup( const char *locale )
211 #if defined (ASSUME_UTF8)
212 return strdup( locale );
215 if (from_locale.hd == (vlc_iconv_t)(-1))
216 return strdup( locale );
218 return FromLocale( locale );
224 * ToLocale: converts a UTF-8 string to local system encoding.
226 * @param utf8 nul-terminated string to be converted
228 * @return a nul-terminated string, or NULL in case of error.
229 * To avoid memory leak, you have to pass the result to LocaleFree()
230 * when it is no longer needed.
232 char *ToLocale( const char *utf8 )
239 if( to_locale.hd != (vlc_iconv_t)(-1) )
241 const char *iptr = utf8;
242 size_t inb = strlen( utf8 );
243 /* FIXME: I'm not sure about the value for the multiplication
244 * (for western people, multiplication is not needed) */
245 size_t outb = inb * 2 + 1;
247 char output[outb], *optr = output;
249 vlc_mutex_lock( &to_locale.lock );
250 vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
252 while( vlc_iconv( to_locale.hd, &iptr, &inb, &optr, &outb )
255 *optr++ = '?'; /* should not happen, and yes, it sucks */
259 vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
261 vlc_mutex_unlock( &to_locale.lock );
265 assert (*iptr == '\0');
266 assert (*optr == '\0');
267 assert (strlen( output ) == (size_t)(optr - output));
268 return strdup( output );
270 # endif /* USE_ICONV */
273 return MB2MB( utf8, CP_UTF8, CP_ACP );
277 char *ToLocaleDup( const char *utf8 )
279 #if defined (ASSUME_UTF8)
280 return strdup( utf8 );
283 if (to_locale.hd == (vlc_iconv_t)(-1))
284 return strdup( utf8 );
286 return ToLocale( utf8 );
290 void LocaleFree( const char *str )
293 if( to_locale.hd == (vlc_iconv_t)(-1) )
304 * utf8_fopen: Calls fopen() after conversion of file name to OS locale
306 FILE *utf8_fopen( const char *filename, const char *mode )
308 #if !(defined (WIN32) || defined (UNDER_CE))
309 const char *local_name = ToLocale( filename );
311 if( local_name != NULL )
313 FILE *stream = fopen( local_name, mode );
314 LocaleFree( local_name );
321 wchar_t wpath[MAX_PATH + 1];
322 size_t len = strlen( mode ) + 1;
325 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH )
326 || !MultiByteToWideChar( CP_ACP, 0, mode, len, wmode, len ) )
331 wpath[MAX_PATH] = L'\0';
334 * fopen() cannot open files with non-“ANSI” characters on Windows.
335 * We use _wfopen() instead. Same thing for mkdir() and stat().
337 return _wfopen( wpath, wmode );
342 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
344 int utf8_mkdir( const char *dirname )
346 #if defined (UNDER_CE) || defined (WIN32)
347 wchar_t wname[MAX_PATH + 1];
348 char mod[MAX_PATH + 1];
351 /* Convert '/' into '\' */
352 for( i = 0; *dirname; i++ )
355 return -1; /* overflow */
357 if( *dirname == '/' )
366 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
371 wname[MAX_PATH] = L'\0';
373 if( CreateDirectoryW( wname, NULL ) == 0 )
375 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
382 char *locname = ToLocale( dirname );
385 if( locname == NULL )
390 res = mkdir( locname, 0755 );
392 LocaleFree( locname );
398 void *utf8_opendir( const char *dirname )
400 const char *local_name = ToLocale( dirname );
402 if( local_name != NULL )
404 DIR *dir = opendir( local_name );
405 LocaleFree( local_name );
413 const char *utf8_readdir( void *dir )
417 ent = readdir( (DIR *)dir );
421 return FromLocale( ent->d_name );
424 static int dummy_select( const char *str )
430 int utf8_scandir( const char *dirname, char ***namelist,
431 int (*select)( const char * ),
432 int (*compar)( const char **, const char ** ) )
434 DIR *dir = utf8_opendir( dirname );
437 select = dummy_select;
447 while( ( entry = utf8_readdir( dir ) ) != NULL )
450 char *utf_entry = strdup( entry );
452 if( utf_entry == NULL )
455 if( !select( utf_entry ) )
458 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
462 tab[num++] = utf_entry;
467 qsort( tab, num, sizeof( tab[0] ),
468 (int (*)( const void *, const void *))compar );
476 for( i = 0; i < num; i++ )
485 static int utf8_statEx( const char *filename, void *buf,
488 #if !(defined (WIN32) || defined (UNDER_CE))
489 # ifdef HAVE_SYS_STAT_H
490 const char *local_name = ToLocale( filename );
492 if( local_name != NULL )
494 int res = deref ? stat( local_name, (struct stat *)buf )
495 : lstat( local_name, (struct stat *)buf );
496 LocaleFree( local_name );
503 wchar_t wpath[MAX_PATH + 1];
505 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
510 wpath[MAX_PATH] = L'\0';
512 /* struct _stat is just a silly Microsoft alias for struct stat */
513 return _wstat( wpath, (struct _stat *)buf );
518 int utf8_stat( const char *filename, void *buf)
520 return utf8_statEx( filename, buf, VLC_TRUE );
523 int utf8_lstat( const char *filename, void *buf)
525 return utf8_statEx( filename, buf, VLC_FALSE );
529 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
531 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
534 int res = vasprintf( &utf8, fmt, ap );
538 *str = ToLocaleDup( utf8 );
543 static int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
546 int res = utf8_vasprintf( &str, fmt, ap );
550 fputs( str, stream );
555 int utf8_fprintf( FILE *stream, const char *fmt, ... )
561 res = utf8_vfprintf( stream, fmt, ap );
567 static char *CheckUTF8( char *str, char rep )
568 #define isutf8cont( c ) (((c) >= 0x80) && ((c) <= 0xBF))
570 unsigned char *ptr, c;
572 ptr = (unsigned char *)str;
573 while( (c = *ptr) != '\0' )
575 /* US-ASCII, 1 byte */
580 if( ( c >= 0xC2 ) && ( c <= 0xDF ) )
583 if( isutf8cont( c ) )
593 if( ( c >= 0xA0 ) && ( c <= 0xBF ) )
596 if( isutf8cont( c ) )
605 if( ( ( c >= 0xE1 ) && ( c <= 0xEC ) ) || ( c == 0xEC )
606 || ( c == 0xEE ) || ( c == 0xEF ) )
609 if( isutf8cont( c ) )
612 if( isutf8cont( c ) )
624 if( ( c >= 0x80 ) && ( c <= 0x9F ) )
627 if( isutf8cont( c ) )
640 if( ( c >= 0x90 ) && ( c <= 0xBF ) )
643 if( isutf8cont( c ) )
646 if( isutf8cont( c ) )
658 if( ( c >= 0xF1 ) && ( c <= 0xF3 ) )
661 if( isutf8cont( c ) )
664 if( isutf8cont( c ) )
667 if( isutf8cont( c ) )
681 if( ( c >= 0x80 ) && ( c <= 0x8F ) )
684 if( isutf8cont( c ) )
687 if( isutf8cont( c ) )
714 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
715 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
716 * so we don't try that, even though it would be less disruptive.
718 * @return str if it was valid UTF-8, NULL if not.
720 char *EnsureUTF8( char *str )
722 return CheckUTF8( str, '?' );
727 * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
729 * @param str nul-terminated string to be checked
731 * @return str if it was valid UTF-8, NULL if not.
733 const char *IsUTF8( const char *str )
735 return CheckUTF8( (char *)str, 0 );
740 * UTF32toUTF8(): converts an array from UTF-32 (host byte order)
743 * @param src the UTF-32 table to be converted
744 * @param len the number of code points to be converted from src
745 * (ie. the number of uint32_t in the table pointed to by src)
746 * @param newlen an optional pointer. If not NULL, *newlen will
747 * contain the total number of bytes written.
749 * @return the result of the conversion (must be free'd())
750 * or NULL on error (in that case, *newlen is undefined).
753 UTF32toUTF8( const uint32_t *src, size_t len, size_t *newlen )
757 /* allocate memory */
758 out = res = (char *)malloc( 6 * len );
764 uint32_t uv = *src++;
775 *out++ = (( uv >> 6) | 0xc0);
776 *out++ = (( uv & 0x3f) | 0x80);
782 *out++ = (( uv >> 12) | 0xe0);
783 *out++ = (((uv >> 6) & 0x3f) | 0x80);
784 *out++ = (( uv & 0x3f) | 0x80);
790 *out++ = (( uv >> 18) | 0xf0);
791 *out++ = (((uv >> 12) & 0x3f) | 0x80);
792 *out++ = (((uv >> 6) & 0x3f) | 0x80);
793 *out++ = (( uv & 0x3f) | 0x80);
803 res = realloc( res, len );
810 * FromUTF32(): converts an UTF-32 string to UTF-8.
812 * @param src UTF-32 bytes sequence, aligned on a 32-bits boundary.
814 * @return the result of the conversion (must be free()'d),
815 * or NULL in case of error.
817 char *FromUTF32( const uint32_t *src )
822 /* determine the size of the string */
823 for( len = 1, in = src; *in; len++ )
826 return UTF32toUTF8( src, len, NULL );
830 * UTF16toUTF8: converts UTF-16 (host byte order) to UTF-8
832 * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary
833 * @param len number of uint16_t to convert
836 UTF16toUTF8( const uint16_t *in, size_t len, size_t *newlen )
840 /* allocate memory */
841 out = res = (char *)malloc( 3 * len );
859 *out++ = (( uv >> 6) | 0xc0);
860 *out++ = (( uv & 0x3f) | 0x80);
863 if( (uv >= 0xd800) && (uv < 0xdbff) )
865 uint16_t low = GetWBE( in );
869 if( (low < 0xdc00) || (low >= 0xdfff) )
871 *out++ = '?'; /* Malformed surrogate */
875 uv = ((uv - 0xd800) << 10) + (low - 0xdc00) + 0x10000;
879 *out++ = (( uv >> 12) | 0xe0);
880 *out++ = (((uv >> 6) & 0x3f) | 0x80);
881 *out++ = (( uv & 0x3f) | 0x80);
886 *out++ = (( uv >> 18) | 0xf0);
887 *out++ = (((uv >> 12) & 0x3f) | 0x80);
888 *out++ = (((uv >> 6) & 0x3f) | 0x80);
889 *out++ = (( uv & 0x3f) | 0x80);
894 res = realloc( res, len );
902 * FromUTF16(): converts an UTF-16 string to UTF-8.
904 * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary.
906 * @return the result of the conversion (must be free()'d),
907 * or NULL in case of error.
909 char *FromUTF16( const uint16_t *src )
914 /* determine the size of the string */
915 for( len = 1, in = src; *in; len++ )
918 return UTF16toUTF8( src, len, NULL );