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>
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
65 #if defined (ASSUME_UTF8)
67 #elif defined (WIN32) || defined (UNDER_CE)
69 #elif defined (HAVE_ICONV)
72 # error No UTF8 charset conversion implemented on this platform!
75 typedef struct locale_data_t
77 #if defined (USE_ICONV)
80 #elif defined (USE_MB2MB)
86 static locale_data_t from_locale, to_locale;
89 void LocaleInit( vlc_object_t *p_this )
94 if( vlc_current_charset( &psz_charset ) )
96 from_locale.hd = to_locale.hd = (vlc_iconv_t)(-1);
100 char psz_buf[strlen( psz_charset ) + sizeof( "//translit" )];
101 const char *psz_conv;
104 * Still allow non-ASCII characters when the locale is not set.
105 * Western Europeans are being favored for historical reasons.
107 if( strcmp( psz_charset, "ASCII" ) )
109 sprintf( psz_buf, "%s//translit", psz_charset );
113 psz_conv = "ISO-8859-1//translit";
115 vlc_mutex_init( p_this, &from_locale.lock );
116 vlc_mutex_init( p_this, &to_locale.lock );
117 from_locale.hd = vlc_iconv_open( "UTF-8", psz_conv );
118 to_locale.hd = vlc_iconv_open( psz_conv, "UTF-8" );
123 assert( (from_locale.hd == (vlc_iconv_t)(-1))
124 == (to_locale.hd == (vlc_iconv_t)(-1)) );
126 #elif defined (USE_MB2MB)
127 to_locale.toCP = from_locale.fromCP = CP_ACP;
128 from_locale.toCP = to_locale.fromCP = CP_UTF8;
134 void LocaleDeinit( void )
137 if( to_locale.hd != (vlc_iconv_t)(-1) )
139 vlc_iconv_close( to_locale.hd );
140 vlc_mutex_destroy( &to_locale.lock );
143 if( from_locale.hd != (vlc_iconv_t)(-1) )
145 vlc_iconv_close( from_locale.hd );
146 vlc_mutex_destroy( &from_locale.lock );
151 static char *locale_fast (const char *string, locale_data_t *p)
153 #if defined (USE_ICONV)
154 vlc_iconv_t hd = p->hd;
156 if (hd == (vlc_iconv_t)(-1))
157 return (char *)string;
159 const char *iptr = string;
160 size_t inb = strlen (string);
161 size_t outb = inb * 6 + 1;
162 char output[outb], *optr = output;
167 vlc_mutex_lock (&p->lock);
168 vlc_iconv (hd, NULL, NULL, NULL, NULL);
170 while (vlc_iconv (hd, &iptr, &inb, &optr, &outb) == (size_t)(-1))
176 vlc_iconv (hd, NULL, NULL, NULL, NULL);
178 vlc_mutex_unlock (&p->lock);
182 assert (*iptr == '\0');
183 assert (*optr == '\0');
184 assert (strlen (output) == (size_t)(optr - output));
185 return strdup (output);
186 #elif defined (USE_MB2MB)
194 len = 1 + MultiByteToWideChar (p->fromCP, 0, string, -1, NULL, 0);
197 MultiByteToWideChar (p->fromCP, 0, string, -1, wide, len);
198 len = 1 + WideCharToMultiByte (p->toCP, 0, wide, -1, NULL, 0, NULL, NULL);
203 WideCharToMultiByte (p->toCP, 0, wide, -1, out, len, NULL, NULL);
206 return (char *)string;
211 static inline char *locale_dup (const char *string, locale_data_t *p)
213 #if defined (USE_ICONV)
214 return (p->hd == (vlc_iconv_t)(-1))
216 : locale_fast (string, p);
217 #elif defined (USE_MB2MB)
218 return locale_fast (string, p);
220 return strdup (string);
225 void LocaleFree (const char *str)
227 #if defined (USE_ICONV)
228 assert ((to_locale.hd == (vlc_iconv_t)(-1))
229 == (from_locale.hd == (vlc_iconv_t)(-1)));
231 if( to_locale.hd != (vlc_iconv_t)(-1) )
233 #elif defined (USE_MB2MB)
240 * FromLocale: converts a locale string to UTF-8
242 * @param locale nul-terminated string to be converted
244 * @return a nul-terminated UTF-8 string, or NULL in case of error.
245 * To avoid memory leak, you have to pass the result to LocaleFree()
246 * when it is no longer needed.
248 char *FromLocale (const char *locale)
250 return locale_fast (locale, &from_locale);
253 char *FromLocaleDup (const char *locale)
255 return locale_dup (locale, &from_locale);
260 * ToLocale: converts a UTF-8 string to local system encoding.
262 * @param utf8 nul-terminated string to be converted
264 * @return a nul-terminated string, or NULL in case of error.
265 * To avoid memory leak, you have to pass the result to LocaleFree()
266 * when it is no longer needed.
268 char *ToLocale (const char *utf8)
270 return locale_fast (utf8, &to_locale);
274 static char *ToLocaleDup (const char *utf8)
276 return locale_dup (utf8, &to_locale);
281 * utf8_open: open() wrapper for UTF-8 filenames
283 int utf8_open (const char *filename, int flags, mode_t mode)
285 #if defined (WIN32) || defined (UNDER_CE)
286 if (GetVersion() < 0x80000000)
288 /* for Windows NT and above */
289 wchar_t wpath[MAX_PATH + 1];
291 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
296 wpath[MAX_PATH] = L'\0';
299 * open() cannot open files with non-“ANSI” characters on Windows.
300 * We use _wopen() instead. Same thing for mkdir() and stat().
302 return _wopen (wpath, flags, mode);
305 const char *local_name = ToLocale (filename);
307 if (local_name == NULL)
313 int fd = open (local_name, flags, mode);
314 LocaleFree (local_name);
319 * utf8_fopen: fopen() wrapper for UTF-8 filenames
321 FILE *utf8_fopen (const char *filename, const char *mode)
323 int rwflags = 0, oflags = 0;
324 vlc_bool_t append = VLC_FALSE;
326 for (const char *ptr = mode; *ptr; ptr++)
342 oflags |= O_CREAT | O_TRUNC;
357 int fd = utf8_open (filename, rwflags | oflags, 0666);
361 if (append && (lseek (fd, 0, SEEK_END) == -1))
367 FILE *stream = fdopen (fd, mode);
375 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
377 * @param dirname a UTF-8 string with the name of the directory that you
379 * @return A 0 return value indicates success. A -1 return value indicates an
380 * error, and an error code is stored in errno
382 int utf8_mkdir( const char *dirname )
384 #if defined (UNDER_CE) || defined (WIN32)
385 wchar_t wname[MAX_PATH + 1];
386 char mod[MAX_PATH + 1];
389 /* Convert '/' into '\' */
390 for( i = 0; *dirname; i++ )
393 return -1; /* overflow */
395 if( *dirname == '/' )
404 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
409 wname[MAX_PATH] = L'\0';
411 if( CreateDirectoryW( wname, NULL ) == 0 )
413 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
421 char *locname = ToLocale( dirname );
424 if( locname == NULL )
429 res = mkdir( locname, 0755 );
431 LocaleFree( locname );
437 * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
439 * @param dirname UTF-8 representation of the directory name
441 * @return a pointer to the DIR struct. Release with closedir().
443 DIR *utf8_opendir( const char *dirname )
446 wchar_t wname[MAX_PATH + 1];
448 if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
450 wname[MAX_PATH] = L'\0';
451 return (DIR *)vlc_wopendir (wname);
454 const char *local_name = ToLocale( dirname );
456 if( local_name != NULL )
458 DIR *dir = opendir( local_name );
459 LocaleFree( local_name );
469 * utf8_readdir: a readdir wrapper that returns the name of the next entry
470 * in the directory as a UTF-8 string.
472 * @param dir The directory that is being read
474 * @return a UTF-8 string of the directory entry. Use LocaleFree() to free this memory
476 char *utf8_readdir( DIR *dir )
479 struct _wdirent *ent = vlc_wreaddir (dir);
483 return FromWide (ent->d_name);
487 ent = readdir( (DIR *)dir );
491 return vlc_fix_readdir( ent->d_name );
495 static int dummy_select( const char *str )
501 int utf8_loaddir( DIR *dir, char ***namelist,
502 int (*select)( const char * ),
503 int (*compar)( const char **, const char ** ) )
506 select = dummy_select;
518 while( ( entry = utf8_readdir( dir ) ) != NULL )
522 if( !select( entry ) )
528 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
539 qsort( tab, num, sizeof( tab[0] ),
540 (int (*)( const void *, const void *))compar );
548 for( i = 0; i < num; i++ )
557 int utf8_scandir( const char *dirname, char ***namelist,
558 int (*select)( const char * ),
559 int (*compar)( const char **, const char ** ) )
561 DIR *dir = utf8_opendir (dirname);
566 val = utf8_loaddir (dir, namelist, select, compar);
572 static int utf8_statEx( const char *filename, struct stat *buf,
575 #if defined (WIN32) || defined (UNDER_CE)
576 /* retrieve Windows OS version */
577 if( GetVersion() < 0x80000000 )
579 /* for Windows NT and above */
580 wchar_t wpath[MAX_PATH + 1];
582 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
587 wpath[MAX_PATH] = L'\0';
589 return _wstati64( wpath, buf );
592 #ifdef HAVE_SYS_STAT_H
593 const char *local_name = ToLocale( filename );
595 if( local_name != NULL )
597 int res = deref ? stat( local_name, buf )
598 : lstat( local_name, buf );
599 LocaleFree( local_name );
608 int utf8_stat( const char *filename, struct stat *buf)
610 return utf8_statEx( filename, buf, VLC_TRUE );
613 int utf8_lstat( const char *filename, struct stat *buf)
615 return utf8_statEx( filename, buf, VLC_FALSE );
619 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
621 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
624 int res = vasprintf( &utf8, fmt, ap );
628 *str = ToLocaleDup( utf8 );
633 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
636 int res = utf8_vasprintf( &str, fmt, ap );
640 fputs( str, stream );
645 int utf8_fprintf( FILE *stream, const char *fmt, ... )
651 res = utf8_vfprintf( stream, fmt, ap );
657 static char *CheckUTF8( char *str, char rep )
659 uint8_t *ptr = (uint8_t *)str;
660 assert (str != NULL);
670 for (int i = 0; i < 7; i++)
671 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
679 case 0: // 7-bit ASCII character -> OK
683 case -1: // 1111111x -> error
684 case 1: // continuation byte -> error
688 assert (charlen >= 2);
690 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
691 for (int i = 1; i < charlen; i++)
693 assert (cp < (1 << 26));
696 if ((c == '\0') // unexpected end of string
697 || ((c >> 6) != 2)) // not a continuation byte
700 cp = (cp << 6) | (ptr[i] & 0x3f);
703 if (cp < 128) // overlong (special case for ASCII)
705 if (cp < (1u << (5 * charlen - 3))) // overlong
722 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
723 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
724 * so we don't try that, even though it would be less disruptive.
726 * @return str if it was valid UTF-8, NULL if not.
728 char *EnsureUTF8( char *str )
730 return CheckUTF8( str, '?' );
735 * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
737 * @param str nul-terminated string to be checked
739 * @return str if it was valid UTF-8, NULL if not.
741 const char *IsUTF8( const char *str )
743 return CheckUTF8( (char *)str, 0 );