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)
193 len = 1 + MultiByteToWideChar (p->fromCP, 0, string, -1, NULL, 0);
196 MultiByteToWideChar (p->fromCP, 0, string, -1, wide, len);
197 len = 1 + WideCharToMultiByte (p->toCP, 0, wide, -1, NULL, 0, NULL, NULL);
202 WideCharToMultiByte (p->toCP, 0, wide, -1, out, len, NULL, NULL);
205 return (char *)string;
210 static inline char *locale_dup (const char *string, locale_data_t *p)
212 #if defined (USE_ICONV)
213 return (p->hd == (vlc_iconv_t)(-1))
215 : locale_fast (string, p);
216 #elif defined (USE_MB2MB)
217 return locale_fast (string, p);
219 return strdup (string);
224 void LocaleFree (const char *str)
226 #if defined (USE_ICONV)
227 assert ((to_locale.hd == (vlc_iconv_t)(-1))
228 == (from_locale.hd == (vlc_iconv_t)(-1)));
230 if( to_locale.hd != (vlc_iconv_t)(-1) )
232 #elif defined (USE_MB2MB)
239 * FromLocale: converts a locale string to UTF-8
241 * @param locale nul-terminated string to be converted
243 * @return a nul-terminated UTF-8 string, or NULL in case of error.
244 * To avoid memory leak, you have to pass the result to LocaleFree()
245 * when it is no longer needed.
247 char *FromLocale (const char *locale)
249 return locale_fast (locale, &from_locale);
252 char *FromLocaleDup (const char *locale)
254 return locale_dup (locale, &from_locale);
259 * ToLocale: converts a UTF-8 string to local system encoding.
261 * @param utf8 nul-terminated string to be converted
263 * @return a nul-terminated string, or NULL in case of error.
264 * To avoid memory leak, you have to pass the result to LocaleFree()
265 * when it is no longer needed.
267 char *ToLocale (const char *utf8)
269 return locale_fast (utf8, &to_locale);
273 static char *ToLocaleDup (const char *utf8)
275 return locale_dup (utf8, &to_locale);
280 * utf8_open: open() wrapper for UTF-8 filenames
282 int utf8_open (const char *filename, int flags, mode_t mode)
284 #if defined (WIN32) || defined (UNDER_CE)
285 if (GetVersion() < 0x80000000)
287 /* for Windows NT and above */
288 wchar_t wpath[MAX_PATH + 1];
290 if (!MultiByteToWideChar (CP_UTF8, 0, filename, -1, wpath, MAX_PATH))
295 wpath[MAX_PATH] = L'\0';
298 * open() cannot open files with non-“ANSI” characters on Windows.
299 * We use _wopen() instead. Same thing for mkdir() and stat().
301 return _wopen (wpath, flags, mode);
304 const char *local_name = ToLocale (filename);
306 if (local_name == NULL)
312 int fd = open (local_name, flags, mode);
313 LocaleFree (local_name);
318 * utf8_fopen: fopen() wrapper for UTF-8 filenames
320 FILE *utf8_fopen (const char *filename, const char *mode)
322 int rwflags = 0, oflags = 0;
323 vlc_bool_t append = VLC_FALSE;
325 for (const char *ptr = mode; *ptr; ptr++)
341 oflags |= O_CREAT | O_TRUNC;
356 int fd = utf8_open (filename, rwflags | oflags, 0666);
360 if (append && (lseek (fd, 0, SEEK_END) == -1))
366 FILE *stream = fdopen (fd, mode);
374 * utf8_mkdir: Calls mkdir() after conversion of file name to OS locale
376 * @param dirname a UTF-8 string with the name of the directory that you
378 * @return A 0 return value indicates success. A -1 return value indicates an
379 * error, and an error code is stored in errno
381 int utf8_mkdir( const char *dirname )
383 #if defined (UNDER_CE) || defined (WIN32)
384 wchar_t wname[MAX_PATH + 1];
385 char mod[MAX_PATH + 1];
388 /* Convert '/' into '\' */
389 for( i = 0; *dirname; i++ )
392 return -1; /* overflow */
394 if( *dirname == '/' )
403 if( MultiByteToWideChar( CP_UTF8, 0, mod, -1, wname, MAX_PATH ) == 0 )
408 wname[MAX_PATH] = L'\0';
410 if( CreateDirectoryW( wname, NULL ) == 0 )
412 if( GetLastError( ) == ERROR_ALREADY_EXISTS )
420 char *locname = ToLocale( dirname );
423 if( locname == NULL )
428 res = mkdir( locname, 0755 );
430 LocaleFree( locname );
436 * utf8_opendir: wrapper that converts dirname to the locale in use by the OS
438 * @param dirname UTF-8 representation of the directory name
440 * @return a pointer to the DIR struct. Release with closedir().
442 DIR *utf8_opendir( const char *dirname )
445 wchar_t wname[MAX_PATH + 1];
447 if (MultiByteToWideChar (CP_UTF8, 0, dirname, -1, wname, MAX_PATH))
449 wname[MAX_PATH] = L'\0';
450 return (DIR *)vlc_wopendir (wname);
453 const char *local_name = ToLocale( dirname );
455 if( local_name != NULL )
457 DIR *dir = opendir( local_name );
458 LocaleFree( local_name );
468 * utf8_readdir: a readdir wrapper that returns the name of the next entry
469 * in the directory as a UTF-8 string.
471 * @param dir The directory that is being read
473 * @return a UTF-8 string of the directory entry. Use LocaleFree() to free this memory
475 char *utf8_readdir( DIR *dir )
478 struct _wdirent *ent = vlc_wreaddir (dir);
482 return FromWide (ent->d_name);
486 ent = readdir( (DIR *)dir );
490 return vlc_fix_readdir( ent->d_name );
494 static int dummy_select( const char *str )
500 int utf8_loaddir( DIR *dir, char ***namelist,
501 int (*select)( const char * ),
502 int (*compar)( const char **, const char ** ) )
505 select = dummy_select;
517 while( ( entry = utf8_readdir( dir ) ) != NULL )
521 if( !select( entry ) )
527 newtab = realloc( tab, sizeof( char * ) * (num + 1) );
538 qsort( tab, num, sizeof( tab[0] ),
539 (int (*)( const void *, const void *))compar );
547 for( i = 0; i < num; i++ )
556 int utf8_scandir( const char *dirname, char ***namelist,
557 int (*select)( const char * ),
558 int (*compar)( const char **, const char ** ) )
560 DIR *dir = utf8_opendir (dirname);
565 val = utf8_loaddir (dir, namelist, select, compar);
571 static int utf8_statEx( const char *filename, struct stat *buf,
574 #if defined (WIN32) || defined (UNDER_CE)
575 /* retrieve Windows OS version */
576 if( GetVersion() < 0x80000000 )
578 /* for Windows NT and above */
579 wchar_t wpath[MAX_PATH + 1];
581 if( !MultiByteToWideChar( CP_UTF8, 0, filename, -1, wpath, MAX_PATH ) )
586 wpath[MAX_PATH] = L'\0';
588 return _wstati64( wpath, buf );
591 #ifdef HAVE_SYS_STAT_H
592 const char *local_name = ToLocale( filename );
594 if( local_name != NULL )
596 int res = deref ? stat( local_name, buf )
597 : lstat( local_name, buf );
598 LocaleFree( local_name );
607 int utf8_stat( const char *filename, struct stat *buf)
609 return utf8_statEx( filename, buf, VLC_TRUE );
612 int utf8_lstat( const char *filename, struct stat *buf)
614 return utf8_statEx( filename, buf, VLC_FALSE );
618 * utf8_*printf: *printf with conversion from UTF-8 to local encoding
620 static int utf8_vasprintf( char **str, const char *fmt, va_list ap )
623 int res = vasprintf( &utf8, fmt, ap );
627 *str = ToLocaleDup( utf8 );
632 int utf8_vfprintf( FILE *stream, const char *fmt, va_list ap )
635 int res = utf8_vasprintf( &str, fmt, ap );
639 fputs( str, stream );
644 int utf8_fprintf( FILE *stream, const char *fmt, ... )
650 res = utf8_vfprintf( stream, fmt, ap );
656 static char *CheckUTF8( char *str, char rep )
658 uint8_t *ptr = (uint8_t *)str;
659 assert (str != NULL);
669 for (int i = 0; i < 7; i++)
670 if ((c >> (7 - i)) == ((0xff >> (7 - i)) ^ 1))
678 case 0: // 7-bit ASCII character -> OK
682 case -1: // 1111111x -> error
683 case 1: // continuation byte -> error
687 assert (charlen >= 2);
689 uint32_t cp = c & ~((0xff >> (7 - charlen)) << (7 - charlen));
690 for (int i = 1; i < charlen; i++)
692 assert (cp < (1 << 26));
695 if ((c == '\0') // unexpected end of string
696 || ((c >> 6) != 2)) // not a continuation byte
699 cp = (cp << 6) | (ptr[i] & 0x3f);
702 if (cp < 128) // overlong (special case for ASCII)
704 if (cp < (1u << (5 * charlen - 3))) // overlong
721 * EnsureUTF8: replaces invalid/overlong UTF-8 sequences with question marks
722 * Note that it is not possible to convert from Latin-1 to UTF-8 on the fly,
723 * so we don't try that, even though it would be less disruptive.
725 * @return str if it was valid UTF-8, NULL if not.
727 char *EnsureUTF8( char *str )
729 return CheckUTF8( str, '?' );
734 * IsUTF8: checks whether a string is a valid UTF-8 byte sequence.
736 * @param str nul-terminated string to be checked
738 * @return str if it was valid UTF-8, NULL if not.
740 const char *IsUTF8( const char *str )
742 return CheckUTF8( (char *)str, 0 );