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 *****************************************************************************/
38 #include <sys/types.h>
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
49 # define lstat( a, b ) stat(a, b)
53 /* Define this if the OS always use UTF-8 internally */
54 # define ASSUME_UTF8 1
58 # if defined (HAVE_ICONV)
59 /* libiconv is more powerful than Win32 API (it has translit) */
61 # elif defined (WIN32) || defined (UNDER_CE)
64 # error No UTF8 charset conversion implemented on this platform!
72 } from_locale, to_locale;
75 void LocaleInit( vlc_object_t *p_this )
80 if( vlc_current_charset( &psz_charset ) )
82 from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
86 char psz_buf[strlen( psz_charset ) + sizeof( "//translit" )];
90 * Still allow non-ASCII characters when the locale is not set.
91 * Western Europeans are being favored for historical reasons.
93 if( strcmp( psz_charset, "ASCII" ) )
95 sprintf( psz_buf, "%s//translit", psz_charset );
99 psz_conv = "ISO-8859-1//translit";
101 vlc_mutex_init( p_this, &from_locale.lock );
102 vlc_mutex_init( p_this, &to_locale.lock );
103 from_locale.hd = vlc_iconv_open( "UTF-8", psz_conv );
104 to_locale.hd = vlc_iconv_open( psz_conv, "UTF-8" );
109 assert( (from_locale.hd == (vlc_iconv_t)(-1))
110 == (to_locale.hd == (vlc_iconv_t)(-1)) );
116 void LocaleDeinit( void )
119 if( to_locale.hd != (vlc_iconv_t)(-1) )
121 vlc_iconv_close( to_locale.hd );
122 vlc_mutex_destroy( &to_locale.lock );
125 if( from_locale.hd != (vlc_iconv_t)(-1) )
127 vlc_iconv_close( from_locale.hd );
128 vlc_mutex_destroy( &from_locale.lock );
134 static char *MB2MB( const char *string, UINT fromCP, UINT toCP )
140 len = MultiByteToWideChar( fromCP, 0, string, -1, NULL, 0 );
142 wide = (wchar_t *)malloc (len * sizeof (wchar_t));
146 MultiByteToWideChar( fromCP, 0, string, -1, wide, len );
147 len = WideCharToMultiByte( toCP, 0, wide, -1, NULL, 0, NULL, NULL );
151 WideCharToMultiByte( toCP, 0, wide, -1, out, len, NULL, NULL );
158 * FromLocale: converts a locale string to UTF-8
160 * @param locale nul-terminated string to be converted
162 * @return a nul-terminated UTF-8 string, or NULL in case of error.
163 * To avoid memory leak, you have to pass the result to LocaleFree()
164 * when it is no longer needed.
166 char *FromLocale( const char *locale )
173 if( from_locale.hd != (vlc_iconv_t)(-1) )
175 const char *iptr = locale;
176 size_t inb = strlen( locale );
177 size_t outb = inb * 6 + 1;
178 char output[outb], *optr = output;
180 vlc_mutex_lock( &from_locale.lock );
181 vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
183 while( vlc_iconv( from_locale.hd, &iptr, &inb, &optr, &outb )
190 vlc_iconv( from_locale.hd, NULL, NULL, NULL, NULL );
192 vlc_mutex_unlock( &from_locale.lock );
196 assert (*iptr == '\0');
197 assert (*optr == '\0');
198 assert (strlen( output ) == (size_t)(optr - output));
199 return strdup( output );
201 # endif /* USE_ICONV */
202 return (char *)locale;
204 return MB2MB( locale, CP_ACP, CP_UTF8 );
208 char *FromLocaleDup( const char *locale )
210 #if defined (ASSUME_UTF8)
211 return strdup( locale );
214 if (from_locale.hd == (vlc_iconv_t)(-1))
215 return strdup( locale );
217 return FromLocale( locale );
223 * ToLocale: converts a UTF-8 string to local system encoding.
225 * @param utf8 nul-terminated string to be converted
227 * @return a nul-terminated string, or NULL in case of error.
228 * To avoid memory leak, you have to pass the result to LocaleFree()
229 * when it is no longer needed.
231 char *ToLocale( const char *utf8 )
238 if( to_locale.hd != (vlc_iconv_t)(-1) )
240 const char *iptr = utf8;
241 size_t inb = strlen( utf8 );
242 /* FIXME: I'm not sure about the value for the multiplication
243 * (for western people, multiplication is not needed) */
244 size_t outb = inb * 2 + 1;
246 char output[outb], *optr = output;
248 vlc_mutex_lock( &to_locale.lock );
249 vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
251 while( vlc_iconv( to_locale.hd, &iptr, &inb, &optr, &outb )
254 *optr++ = '?'; /* should not happen, and yes, it sucks */
258 vlc_iconv( to_locale.hd, NULL, NULL, NULL, NULL );
260 vlc_mutex_unlock( &to_locale.lock );
264 assert (*iptr == '\0');
265 assert (*optr == '\0');
266 assert (strlen( output ) == (size_t)(optr - output));
267 return strdup( output );
269 # endif /* USE_ICONV */
272 return MB2MB( utf8, CP_UTF8, CP_ACP );
276 char *ToLocaleDup( const char *utf8 )
278 #if defined (ASSUME_UTF8)
279 return strdup( utf8 );
282 if (to_locale.hd == (vlc_iconv_t)(-1))
283 return strdup( utf8 );
285 return ToLocale( utf8 );
289 void LocaleFree( const char *str )
292 if( to_locale.hd == (vlc_iconv_t)(-1) )
302 /*****************************************************************************
303 * utf8_fopen: Calls fopen() after conversion of file name to OS locale
304 *****************************************************************************/
305 FILE *utf8_fopen( const char *filename, const char *mode )
307 #if !(defined (WIN32) || defined (UNDER_CE))
308 const char *local_name = ToLocale( filename );
310 if( local_name != NULL )
312 FILE *stream = fopen( local_name, mode );
313 LocaleFree( local_name );
320 wchar_t wpath[MAX_PATH + 1];
321 size_t len = strlen( mode ) + 1;
324 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH )
325 || !MultiByteToWideChar( CP_ACP, 0, mode, len, wmode, len ) )
330 wpath[MAX_PATH] = L'\0';
333 * fopen() cannot open files with non-“ANSI” characters on Windows.
334 * We use _wfopen() instead. Same thing for mkdir() and stat().
336 return _wfopen( wpath, wmode );
340 /*****************************************************************************
341 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
342 *****************************************************************************/
343 int utf8_mkdir( const char *dirname )
345 #if defined (UNDER_CE) || defined (WIN32)
346 wchar_t wname[MAX_PATH + 1];
347 char mod[MAX_PATH + 1];
350 /* Convert '/' into '\' */
351 for( i = 0; *dirname; i++ )
354 return -1; /* overflow */
356 if( *dirname == '/' )
365 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
370 wname[MAX_PATH] = L'\0';
372 if( CreateDirectoryW( wname, NULL ) == 0 )
374 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
381 char *locname = ToLocale( dirname );
384 if( locname == NULL )
389 res = mkdir( locname, 0755 );
391 LocaleFree( locname );
397 void *utf8_opendir( const char *dirname )
399 const char *local_name = ToLocale( dirname );
401 if( local_name != NULL )
403 DIR *dir = opendir( local_name );
404 LocaleFree( local_name );
412 const char *utf8_readdir( void *dir )
416 ent = readdir( (DIR *)dir );
420 return FromLocale( ent->d_name );
424 static int utf8_statEx( const char *filename, void *buf,
427 #if !(defined (WIN32) || defined (UNDER_CE))
428 # ifdef HAVE_SYS_STAT_H
429 const char *local_name = ToLocale( filename );
431 if( local_name != NULL )
433 int res = deref ? stat( local_name, (struct stat *)buf )
434 : lstat( local_name, (struct stat *)buf );
435 LocaleFree( local_name );
442 wchar_t wpath[MAX_PATH + 1];
444 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
449 wpath[MAX_PATH] = L'\0';
451 /* struct _stat is just a silly Microsoft alias for struct stat */
452 return _wstat( wpath, (struct _stat *)buf );
457 int utf8_stat( const char *filename, void *buf)
459 return utf8_statEx( filename, buf, VLC_TRUE );
462 int utf8_lstat( const char *filename, void *buf)
464 return utf8_statEx( filename, buf, VLC_FALSE );
467 /*****************************************************************************
468 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
469 *****************************************************************************/
470 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
473 int res = vasprintf( &utf8, fmt, ap );
477 *str = ToLocaleDup( utf8 );
482 static int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
485 int res = utf8_vasprintf( &str, fmt, ap );
489 fputs( str, stream );
494 int utf8_fprintf( FILE *stream, const char *fmt, ... )
500 res = utf8_vfprintf( stream, fmt, ap );
505 /*****************************************************************************
506 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
507 *****************************************************************************
508 * Not Todo : convert Latin1 to UTF-8 on the fly
509 * It is not possible given UTF-8 needs more space
510 * Returns str if it was valid UTF-8, NULL if not.
511 *****************************************************************************/
512 #define isutf8cont( c ) (((c) >= 0x80) && ((c) <= 0xBF))
513 char *EnsureUTF8( char *str )
515 unsigned char *ptr, c;
517 ptr = (unsigned char *)str;
518 while( (c = *ptr) != '\0' )
520 /* US-ASCII, 1 byte */
525 if( ( c >= 0xC2 ) && ( c <= 0xDF ) )
528 if( isutf8cont( c ) )
538 if( ( c >= 0xA0 ) && ( c <= 0xBF ) )
541 if( isutf8cont( c ) )
550 if( ( ( c >= 0xE1 ) && ( c <= 0xEC ) ) || ( c == 0xEC )
551 || ( c == 0xEE ) || ( c == 0xEF ) )
554 if( isutf8cont( c ) )
557 if( isutf8cont( c ) )
569 if( ( c >= 0x80 ) && ( c <= 0x9F ) )
572 if( isutf8cont( c ) )
585 if( ( c >= 0x90 ) && ( c <= 0xBF ) )
588 if( isutf8cont( c ) )
591 if( isutf8cont( c ) )
603 if( ( c >= 0xF1 ) && ( c <= 0xF3 ) )
606 if( isutf8cont( c ) )
609 if( isutf8cont( c ) )
612 if( isutf8cont( c ) )
626 if( ( c >= 0x80 ) && ( c <= 0x8F ) )
629 if( isutf8cont( c ) )
632 if( isutf8cont( c ) )
657 * UTF32toUTF8(): converts an array from UTF-32 (host byte order)
660 * @param src the UTF-32 table to be converted
661 * @param len the number of code points to be converted from src
662 * (ie. the number of uint32_t in the table pointed to by src)
663 * @param newlen an optional pointer. If not NULL, *newlen will
664 * contain the total number of bytes written.
666 * @return the result of the conversion (must be free'd())
667 * or NULL on error (in that case, *newlen is undefined).
670 UTF32toUTF8( const uint32_t *src, size_t len, size_t *newlen )
674 /* allocate memory */
675 out = res = (char *)malloc( 6 * len );
681 uint32_t uv = *src++;
692 *out++ = (( uv >> 6) | 0xc0);
693 *out++ = (( uv & 0x3f) | 0x80);
699 *out++ = (( uv >> 12) | 0xe0);
700 *out++ = (((uv >> 6) & 0x3f) | 0x80);
701 *out++ = (( uv & 0x3f) | 0x80);
707 *out++ = (( uv >> 18) | 0xf0);
708 *out++ = (((uv >> 12) & 0x3f) | 0x80);
709 *out++ = (((uv >> 6) & 0x3f) | 0x80);
710 *out++ = (( uv & 0x3f) | 0x80);
720 res = realloc( res, len );
727 * FromUTF32(): converts an UTF-32 string to UTF-8.
729 * @param src UTF-32 bytes sequence, aligned on a 32-bits boundary.
731 * @return the result of the conversion (must be free()'d),
732 * or NULL in case of error.
734 char *FromUTF32( const uint32_t *src )
739 /* determine the size of the string */
740 for( len = 1, in = src; *in; len++ )
743 return UTF32toUTF8( src, len, NULL );
747 * UTF16toUTF8: converts UTF-16 (host byte order) to UTF-8
749 * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary
750 * @param len number of uint16_t to convert
753 UTF16toUTF8( const uint16_t *in, size_t len, size_t *newlen )
757 /* allocate memory */
758 out = res = (char *)malloc( 3 * len );
776 *out++ = (( uv >> 6) | 0xc0);
777 *out++ = (( uv & 0x3f) | 0x80);
780 if( (uv >= 0xd800) && (uv < 0xdbff) )
782 uint16_t low = GetWBE( in );
786 if( (low < 0xdc00) || (low >= 0xdfff) )
788 *out++ = '?'; /* Malformed surrogate */
792 uv = ((uv - 0xd800) << 10) + (low - 0xdc00) + 0x10000;
796 *out++ = (( uv >> 12) | 0xe0);
797 *out++ = (((uv >> 6) & 0x3f) | 0x80);
798 *out++ = (( uv & 0x3f) | 0x80);
803 *out++ = (( uv >> 18) | 0xf0);
804 *out++ = (((uv >> 12) & 0x3f) | 0x80);
805 *out++ = (((uv >> 6) & 0x3f) | 0x80);
806 *out++ = (( uv & 0x3f) | 0x80);
811 res = realloc( res, len );
819 * FromUTF16(): converts an UTF-16 string to UTF-8.
821 * @param src UTF-16 bytes sequence, aligned on a 16-bits boundary.
823 * @return the result of the conversion (must be free()'d),
824 * or NULL in case of error.
826 char *FromUTF16( const uint16_t *src )
831 /* determine the size of the string */
832 for( len = 1, in = src; *in; len++ )
835 return UTF16toUTF8( src, len, NULL );