1 /* GLIB - Library of useful routines for C programming
3 * gconvert.c: Convert between character sets using iconv
4 * Copyright Red Hat Inc., 2000
5 * Authors: Havoc Pennington <hp@redhat.com>, Owen Taylor <otaylor@redhat.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
35 #include "gprintfint.h"
36 #include "gthreadprivate.h"
40 #include "win_iconv.c"
43 #ifdef G_PLATFORM_WIN32
51 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
52 #error GNU libiconv in use but included iconv.h not from libiconv
54 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
55 #error GNU libiconv not in use but included iconv.h is from libiconv
59 /* We try to terminate strings in unknown charsets with this many zero bytes
60 * to ensure that multibyte strings really are nul-terminated when we return
61 * them from g_convert() and friends.
63 #define NUL_TERMINATOR_LENGTH 4
66 g_convert_error_quark (void)
68 return g_quark_from_static_string ("g_convert_error");
72 try_conversion (const char *to_codeset,
73 const char *from_codeset,
76 *cd = iconv_open (to_codeset, from_codeset);
78 if (*cd == (iconv_t)-1 && errno == EINVAL)
85 try_to_aliases (const char **to_aliases,
86 const char *from_codeset,
91 const char **p = to_aliases;
94 if (try_conversion (*p, from_codeset, cd))
104 G_GNUC_INTERNAL extern const char **
105 _g_charset_get_aliases (const char *canonical_name);
109 * @to_codeset: destination codeset
110 * @from_codeset: source codeset
112 * Same as the standard UNIX routine iconv_open(), but
113 * may be implemented via libiconv on UNIX flavors that lack
114 * a native implementation.
116 * GLib provides g_convert() and g_locale_to_utf8() which are likely
117 * more convenient than the raw iconv wrappers.
119 * Return value: a "conversion descriptor", or (GIConv)-1 if
120 * opening the converter failed.
123 g_iconv_open (const gchar *to_codeset,
124 const gchar *from_codeset)
128 if (!try_conversion (to_codeset, from_codeset, &cd))
130 const char **to_aliases = _g_charset_get_aliases (to_codeset);
131 const char **from_aliases = _g_charset_get_aliases (from_codeset);
135 const char **p = from_aliases;
138 if (try_conversion (to_codeset, *p, &cd))
141 if (try_to_aliases (to_aliases, *p, &cd))
148 if (try_to_aliases (to_aliases, from_codeset, &cd))
153 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
158 * @converter: conversion descriptor from g_iconv_open()
159 * @inbuf: bytes to convert
160 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
161 * @outbuf: converted output bytes
162 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
164 * Same as the standard UNIX routine iconv(), but
165 * may be implemented via libiconv on UNIX flavors that lack
166 * a native implementation.
168 * GLib provides g_convert() and g_locale_to_utf8() which are likely
169 * more convenient than the raw iconv wrappers.
171 * Return value: count of non-reversible conversions, or -1 on error
174 g_iconv (GIConv converter,
178 gsize *outbytes_left)
180 iconv_t cd = (iconv_t)converter;
182 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
187 * @converter: a conversion descriptor from g_iconv_open()
189 * Same as the standard UNIX routine iconv_close(), but
190 * may be implemented via libiconv on UNIX flavors that lack
191 * a native implementation. Should be called to clean up
192 * the conversion descriptor from g_iconv_open() when
193 * you are done converting things.
195 * GLib provides g_convert() and g_locale_to_utf8() which are likely
196 * more convenient than the raw iconv wrappers.
198 * Return value: -1 on error, 0 on success
201 g_iconv_close (GIConv converter)
203 iconv_t cd = (iconv_t)converter;
205 return iconv_close (cd);
209 #ifdef NEED_ICONV_CACHE
211 #define ICONV_CACHE_SIZE (16)
213 struct _iconv_cache_bucket {
220 static GList *iconv_cache_list;
221 static GHashTable *iconv_cache;
222 static GHashTable *iconv_open_hash;
223 static guint iconv_cache_size = 0;
224 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
226 /* caller *must* hold the iconv_cache_lock */
228 iconv_cache_init (void)
230 static gboolean initialized = FALSE;
235 iconv_cache_list = NULL;
236 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
237 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
244 * iconv_cache_bucket_new:
246 * @cd: iconv descriptor
248 * Creates a new cache bucket, inserts it into the cache and
249 * increments the cache size.
251 * This assumes ownership of @key.
253 * Returns a pointer to the newly allocated cache bucket.
255 static struct _iconv_cache_bucket *
256 iconv_cache_bucket_new (gchar *key, GIConv cd)
258 struct _iconv_cache_bucket *bucket;
260 bucket = g_new (struct _iconv_cache_bucket, 1);
262 bucket->refcount = 1;
266 g_hash_table_insert (iconv_cache, bucket->key, bucket);
268 /* FIXME: if we sorted the list so items with few refcounts were
269 first, then we could expire them faster in iconv_cache_expire_unused () */
270 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
279 * iconv_cache_bucket_expire:
280 * @node: cache bucket's node
281 * @bucket: cache bucket
283 * Expires a single cache bucket @bucket. This should only ever be
284 * called on a bucket that currently has no used iconv descriptors
287 * @node is not a required argument. If @node is not supplied, we
288 * search for it ourselves.
291 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
293 g_hash_table_remove (iconv_cache, bucket->key);
296 node = g_list_find (iconv_cache_list, bucket);
298 g_assert (node != NULL);
302 node->prev->next = node->next;
304 node->next->prev = node->prev;
308 iconv_cache_list = node->next;
310 node->next->prev = NULL;
313 g_list_free_1 (node);
315 g_free (bucket->key);
316 g_iconv_close (bucket->cd);
324 * iconv_cache_expire_unused:
326 * Expires as many unused cache buckets as it needs to in order to get
327 * the total number of buckets < ICONV_CACHE_SIZE.
330 iconv_cache_expire_unused (void)
332 struct _iconv_cache_bucket *bucket;
335 node = iconv_cache_list;
336 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
341 if (bucket->refcount == 0)
342 iconv_cache_bucket_expire (node, bucket);
349 open_converter (const gchar *to_codeset,
350 const gchar *from_codeset,
353 struct _iconv_cache_bucket *bucket;
354 gchar *key, *dyn_key, auto_key[80];
356 gsize len_from_codeset, len_to_codeset;
359 len_from_codeset = strlen (from_codeset);
360 len_to_codeset = strlen (to_codeset);
361 if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
367 key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
368 memcpy (key, from_codeset, len_from_codeset);
369 key[len_from_codeset] = ':';
370 strcpy (key + len_from_codeset + 1, to_codeset);
372 G_LOCK (iconv_cache_lock);
374 /* make sure the cache has been initialized */
377 bucket = g_hash_table_lookup (iconv_cache, key);
384 cd = g_iconv_open (to_codeset, from_codeset);
385 if (cd == (GIConv) -1)
390 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
391 * NULL for anything but inbuf; work around that. (NULL outbuf
392 * or NULL *outbuf is allowed by Unix98.)
394 gsize inbytes_left = 0;
395 gchar *outbuf = NULL;
396 gsize outbytes_left = 0;
401 /* reset the descriptor */
402 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
409 cd = g_iconv_open (to_codeset, from_codeset);
410 if (cd == (GIConv) -1)
416 iconv_cache_expire_unused ();
418 bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
421 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
423 G_UNLOCK (iconv_cache_lock);
429 G_UNLOCK (iconv_cache_lock);
431 /* Something went wrong. */
435 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
436 _("Conversion from character set '%s' to '%s' is not supported"),
437 from_codeset, to_codeset);
439 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
440 _("Could not open converter from '%s' to '%s'"),
441 from_codeset, to_codeset);
448 close_converter (GIConv converter)
450 struct _iconv_cache_bucket *bucket;
456 if (cd == (GIConv) -1)
459 G_LOCK (iconv_cache_lock);
461 key = g_hash_table_lookup (iconv_open_hash, cd);
464 g_hash_table_remove (iconv_open_hash, cd);
466 bucket = g_hash_table_lookup (iconv_cache, key);
471 if (cd == bucket->cd)
472 bucket->used = FALSE;
476 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
478 /* expire this cache bucket */
479 iconv_cache_bucket_expire (NULL, bucket);
484 G_UNLOCK (iconv_cache_lock);
486 g_warning ("This iconv context wasn't opened using open_converter");
488 return g_iconv_close (converter);
491 G_UNLOCK (iconv_cache_lock);
496 #else /* !NEED_ICONV_CACHE */
499 open_converter (const gchar *to_codeset,
500 const gchar *from_codeset,
505 cd = g_iconv_open (to_codeset, from_codeset);
507 if (cd == (GIConv) -1)
509 /* Something went wrong. */
513 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
514 _("Conversion from character set '%s' to '%s' is not supported"),
515 from_codeset, to_codeset);
517 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
518 _("Could not open converter from '%s' to '%s'"),
519 from_codeset, to_codeset);
527 close_converter (GIConv cd)
529 if (cd == (GIConv) -1)
532 return g_iconv_close (cd);
535 #endif /* NEED_ICONV_CACHE */
538 * g_convert_with_iconv:
539 * @str: the string to convert
540 * @len: the length of the string, or -1 if the string is
541 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
542 * @converter: conversion descriptor from g_iconv_open()
543 * @bytes_read: location to store the number of bytes in the
544 * input string that were successfully converted, or %NULL.
545 * Even if the conversion was successful, this may be
546 * less than @len if there were partial characters
547 * at the end of the input. If the error
548 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
549 * stored will the byte offset after the last valid
551 * @bytes_written: the number of bytes stored in the output buffer (not
552 * including the terminating nul).
553 * @error: location to store the error occuring, or %NULL to ignore
554 * errors. Any of the errors in #GConvertError may occur.
556 * Converts a string from one character set to another.
558 * Note that you should use g_iconv() for streaming
559 * conversions<footnote id="streaming-state">
561 * Despite the fact that @byes_read can return information about partial
562 * characters, the <literal>g_convert_...</literal> functions
563 * are not generally suitable for streaming. If the underlying converter
564 * being used maintains internal state, then this won't be preserved
565 * across successive calls to g_convert(), g_convert_with_iconv() or
566 * g_convert_with_fallback(). (An example of this is the GNU C converter
567 * for CP1255 which does not emit a base character until it knows that
568 * the next character is not a mark that could combine with the base
573 * Return value: If the conversion was successful, a newly allocated
574 * nul-terminated string, which must be freed with
575 * g_free(). Otherwise %NULL and @error will be set.
578 g_convert_with_iconv (const gchar *str,
582 gsize *bytes_written,
588 gsize inbytes_remaining;
589 gsize outbytes_remaining;
592 gboolean have_error = FALSE;
593 gboolean done = FALSE;
594 gboolean reset = FALSE;
596 g_return_val_if_fail (converter != (GIConv) -1, NULL);
602 inbytes_remaining = len;
603 outbuf_size = len + NUL_TERMINATOR_LENGTH;
605 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
606 outp = dest = g_malloc (outbuf_size);
608 while (!done && !have_error)
611 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
613 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
615 if (err == (gsize) -1)
620 /* Incomplete text, do not report an error */
625 gsize used = outp - dest;
628 dest = g_realloc (dest, outbuf_size);
631 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
636 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
637 _("Invalid byte sequence in conversion input"));
644 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
645 _("Error during conversion: %s"),
656 /* call g_iconv with NULL inbuf to cleanup shift state */
658 inbytes_remaining = 0;
665 memset (outp, 0, NUL_TERMINATOR_LENGTH);
668 *bytes_read = p - str;
671 if ((p - str) != len)
676 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
677 _("Partial character sequence at end of input"));
684 *bytes_written = outp - dest; /* Doesn't include '\0' */
697 * @str: the string to convert
698 * @len: the length of the string, or -1 if the string is
699 * nul-terminated<footnote id="nul-unsafe">
701 Note that some encodings may allow nul bytes to
702 occur inside strings. In that case, using -1 for
703 the @len parameter is unsafe.
706 * @to_codeset: name of character set into which to convert @str
707 * @from_codeset: character set of @str.
708 * @bytes_read: location to store the number of bytes in the
709 * input string that were successfully converted, or %NULL.
710 * Even if the conversion was successful, this may be
711 * less than @len if there were partial characters
712 * at the end of the input. If the error
713 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
714 * stored will the byte offset after the last valid
716 * @bytes_written: the number of bytes stored in the output buffer (not
717 * including the terminating nul).
718 * @error: location to store the error occuring, or %NULL to ignore
719 * errors. Any of the errors in #GConvertError may occur.
721 * Converts a string from one character set to another.
723 * Note that you should use g_iconv() for streaming
724 * conversions<footnoteref linkend="streaming-state"/>.
726 * Return value: If the conversion was successful, a newly allocated
727 * nul-terminated string, which must be freed with
728 * g_free(). Otherwise %NULL and @error will be set.
731 g_convert (const gchar *str,
733 const gchar *to_codeset,
734 const gchar *from_codeset,
736 gsize *bytes_written,
742 g_return_val_if_fail (str != NULL, NULL);
743 g_return_val_if_fail (to_codeset != NULL, NULL);
744 g_return_val_if_fail (from_codeset != NULL, NULL);
746 cd = open_converter (to_codeset, from_codeset, error);
748 if (cd == (GIConv) -1)
759 res = g_convert_with_iconv (str, len, cd,
760 bytes_read, bytes_written,
763 close_converter (cd);
769 * g_convert_with_fallback:
770 * @str: the string to convert
771 * @len: the length of the string, or -1 if the string is
772 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
773 * @to_codeset: name of character set into which to convert @str
774 * @from_codeset: character set of @str.
775 * @fallback: UTF-8 string to use in place of character not
776 * present in the target encoding. (The string must be
777 * representable in the target encoding).
778 If %NULL, characters not in the target encoding will
779 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
780 * @bytes_read: location to store the number of bytes in the
781 * input string that were successfully converted, or %NULL.
782 * Even if the conversion was successful, this may be
783 * less than @len if there were partial characters
784 * at the end of the input.
785 * @bytes_written: the number of bytes stored in the output buffer (not
786 * including the terminating nul).
787 * @error: location to store the error occuring, or %NULL to ignore
788 * errors. Any of the errors in #GConvertError may occur.
790 * Converts a string from one character set to another, possibly
791 * including fallback sequences for characters not representable
792 * in the output. Note that it is not guaranteed that the specification
793 * for the fallback sequences in @fallback will be honored. Some
794 * systems may do an approximate conversion from @from_codeset
795 * to @to_codeset in their iconv() functions,
796 * in which case GLib will simply return that approximate conversion.
798 * Note that you should use g_iconv() for streaming
799 * conversions<footnoteref linkend="streaming-state"/>.
801 * Return value: If the conversion was successful, a newly allocated
802 * nul-terminated string, which must be freed with
803 * g_free(). Otherwise %NULL and @error will be set.
806 g_convert_with_fallback (const gchar *str,
808 const gchar *to_codeset,
809 const gchar *from_codeset,
810 const gchar *fallback,
812 gsize *bytes_written,
818 const gchar *insert_str = NULL;
820 gsize inbytes_remaining;
821 const gchar *save_p = NULL;
822 gsize save_inbytes = 0;
823 gsize outbytes_remaining;
827 gboolean have_error = FALSE;
828 gboolean done = FALSE;
830 GError *local_error = NULL;
832 g_return_val_if_fail (str != NULL, NULL);
833 g_return_val_if_fail (to_codeset != NULL, NULL);
834 g_return_val_if_fail (from_codeset != NULL, NULL);
839 /* Try an exact conversion; we only proceed if this fails
840 * due to an illegal sequence in the input string.
842 dest = g_convert (str, len, to_codeset, from_codeset,
843 bytes_read, bytes_written, &local_error);
847 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
849 g_propagate_error (error, local_error);
853 g_error_free (local_error);
857 /* No go; to proceed, we need a converter from "UTF-8" to
858 * to_codeset, and the string as UTF-8.
860 cd = open_converter (to_codeset, "UTF-8", error);
861 if (cd == (GIConv) -1)
872 utf8 = g_convert (str, len, "UTF-8", from_codeset,
873 bytes_read, &inbytes_remaining, error);
876 close_converter (cd);
882 /* Now the heart of the code. We loop through the UTF-8 string, and
883 * whenever we hit an offending character, we form fallback, convert
884 * the fallback to the target codeset, and then go back to
885 * converting the original string after finishing with the fallback.
887 * The variables save_p and save_inbytes store the input state
888 * for the original string while we are converting the fallback
892 outbuf_size = len + NUL_TERMINATOR_LENGTH;
893 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
894 outp = dest = g_malloc (outbuf_size);
896 while (!done && !have_error)
898 gsize inbytes_tmp = inbytes_remaining;
899 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
900 inbytes_remaining = inbytes_tmp;
902 if (err == (gsize) -1)
907 g_assert_not_reached();
911 gsize used = outp - dest;
914 dest = g_realloc (dest, outbuf_size);
917 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
924 /* Error converting fallback string - fatal
926 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
927 _("Cannot convert fallback '%s' to codeset '%s'"),
928 insert_str, to_codeset);
936 gunichar ch = g_utf8_get_char (p);
937 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
941 insert_str = fallback;
943 save_p = g_utf8_next_char (p);
944 save_inbytes = inbytes_remaining - (save_p - p);
946 inbytes_remaining = strlen (p);
949 /* fall thru if p is NULL */
954 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
955 _("Error during conversion: %s"),
968 g_free ((gchar *)insert_str);
970 inbytes_remaining = save_inbytes;
975 /* call g_iconv with NULL inbuf to cleanup shift state */
977 inbytes_remaining = 0;
986 memset (outp, 0, NUL_TERMINATOR_LENGTH);
988 close_converter (cd);
991 *bytes_written = outp - dest; /* Doesn't include '\0' */
997 if (save_p && !fallback)
998 g_free ((gchar *)insert_str);
1013 strdup_len (const gchar *string,
1015 gsize *bytes_written,
1022 if (!g_utf8_validate (string, len, NULL))
1029 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1030 _("Invalid byte sequence in conversion input"));
1035 real_len = strlen (string);
1040 while (real_len < len && string[real_len])
1045 *bytes_read = real_len;
1047 *bytes_written = real_len;
1049 return g_strndup (string, real_len);
1054 * @opsysstring: a string in the encoding of the current locale. On Windows
1055 * this means the system codepage.
1056 * @len: the length of the string, or -1 if the string is
1057 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1058 * @bytes_read: location to store the number of bytes in the
1059 * input string that were successfully converted, or %NULL.
1060 * Even if the conversion was successful, this may be
1061 * less than @len if there were partial characters
1062 * at the end of the input. If the error
1063 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1064 * stored will the byte offset after the last valid
1066 * @bytes_written: the number of bytes stored in the output buffer (not
1067 * including the terminating nul).
1068 * @error: location to store the error occuring, or %NULL to ignore
1069 * errors. Any of the errors in #GConvertError may occur.
1071 * Converts a string which is in the encoding used for strings by
1072 * the C runtime (usually the same as that used by the operating
1073 * system) in the <link linkend="setlocale">current locale</link> into a
1076 * Return value: The converted string, or %NULL on an error.
1079 g_locale_to_utf8 (const gchar *opsysstring,
1082 gsize *bytes_written,
1085 const char *charset;
1087 if (g_get_charset (&charset))
1088 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1090 return g_convert (opsysstring, len,
1091 "UTF-8", charset, bytes_read, bytes_written, error);
1095 * g_locale_from_utf8:
1096 * @utf8string: a UTF-8 encoded string
1097 * @len: the length of the string, or -1 if the string is
1098 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1099 * @bytes_read: location to store the number of bytes in the
1100 * input string that were successfully converted, or %NULL.
1101 * Even if the conversion was successful, this may be
1102 * less than @len if there were partial characters
1103 * at the end of the input. If the error
1104 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1105 * stored will the byte offset after the last valid
1107 * @bytes_written: the number of bytes stored in the output buffer (not
1108 * including the terminating nul).
1109 * @error: location to store the error occuring, or %NULL to ignore
1110 * errors. Any of the errors in #GConvertError may occur.
1112 * Converts a string from UTF-8 to the encoding used for strings by
1113 * the C runtime (usually the same as that used by the operating
1114 * system) in the <link linkend="setlocale">current locale</link>. On
1115 * Windows this means the system codepage.
1117 * Return value: The converted string, or %NULL on an error.
1120 g_locale_from_utf8 (const gchar *utf8string,
1123 gsize *bytes_written,
1126 const gchar *charset;
1128 if (g_get_charset (&charset))
1129 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1131 return g_convert (utf8string, len,
1132 charset, "UTF-8", bytes_read, bytes_written, error);
1135 #ifndef G_PLATFORM_WIN32
1137 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1139 struct _GFilenameCharsetCache {
1142 gchar **filename_charsets;
1146 filename_charset_cache_free (gpointer data)
1148 GFilenameCharsetCache *cache = data;
1149 g_free (cache->charset);
1150 g_strfreev (cache->filename_charsets);
1155 * g_get_filename_charsets:
1156 * @charsets: return location for the %NULL-terminated list of encoding names
1158 * Determines the preferred character sets used for filenames.
1159 * The first character set from the @charsets is the filename encoding, the
1160 * subsequent character sets are used when trying to generate a displayable
1161 * representation of a filename, see g_filename_display_name().
1163 * On Unix, the character sets are determined by consulting the
1164 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1165 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1166 * used in the GLib API is always UTF-8 and said environment variables
1169 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1170 * of character set names. The special token "@locale" is taken to
1171 * mean the character set for the <link linkend="setlocale">current
1172 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1173 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1174 * locale is taken as the filename encoding. If neither environment variable
1175 * is set, UTF-8 is taken as the filename encoding, but the character
1176 * set of the current locale is also put in the list of encodings.
1178 * The returned @charsets belong to GLib and must not be freed.
1180 * Note that on Unix, regardless of the locale character set or
1181 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1182 * on a system might be in any random encoding or just gibberish.
1184 * Return value: %TRUE if the filename encoding is UTF-8.
1189 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1191 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1192 GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1193 const gchar *charset;
1197 cache = g_new0 (GFilenameCharsetCache, 1);
1198 g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1201 g_get_charset (&charset);
1203 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1205 const gchar *new_charset;
1209 g_free (cache->charset);
1210 g_strfreev (cache->filename_charsets);
1211 cache->charset = g_strdup (charset);
1213 p = getenv ("G_FILENAME_ENCODING");
1214 if (p != NULL && p[0] != '\0')
1216 cache->filename_charsets = g_strsplit (p, ",", 0);
1217 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1219 for (i = 0; cache->filename_charsets[i]; i++)
1221 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1223 g_get_charset (&new_charset);
1224 g_free (cache->filename_charsets[i]);
1225 cache->filename_charsets[i] = g_strdup (new_charset);
1229 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1231 cache->filename_charsets = g_new0 (gchar *, 2);
1232 cache->is_utf8 = g_get_charset (&new_charset);
1233 cache->filename_charsets[0] = g_strdup (new_charset);
1237 cache->filename_charsets = g_new0 (gchar *, 3);
1238 cache->is_utf8 = TRUE;
1239 cache->filename_charsets[0] = g_strdup ("UTF-8");
1240 if (!g_get_charset (&new_charset))
1241 cache->filename_charsets[1] = g_strdup (new_charset);
1245 if (filename_charsets)
1246 *filename_charsets = (const gchar **)cache->filename_charsets;
1248 return cache->is_utf8;
1251 #else /* G_PLATFORM_WIN32 */
1254 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1256 static const gchar *charsets[] = {
1262 /* On Windows GLib pretends that the filename charset is UTF-8 */
1263 if (filename_charsets)
1264 *filename_charsets = charsets;
1270 /* Cygwin works like before */
1271 result = g_get_charset (&(charsets[0]));
1273 if (filename_charsets)
1274 *filename_charsets = charsets;
1280 #endif /* G_PLATFORM_WIN32 */
1283 get_filename_charset (const gchar **filename_charset)
1285 const gchar **charsets;
1288 is_utf8 = g_get_filename_charsets (&charsets);
1290 if (filename_charset)
1291 *filename_charset = charsets[0];
1296 /* This is called from g_thread_init(). It's used to
1297 * initialize some static data in a threadsafe way.
1300 _g_convert_thread_init (void)
1302 const gchar **dummy;
1303 (void) g_get_filename_charsets (&dummy);
1307 * g_filename_to_utf8:
1308 * @opsysstring: a string in the encoding for filenames
1309 * @len: the length of the string, or -1 if the string is
1310 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1311 * @bytes_read: location to store the number of bytes in the
1312 * input string that were successfully converted, or %NULL.
1313 * Even if the conversion was successful, this may be
1314 * less than @len if there were partial characters
1315 * at the end of the input. If the error
1316 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1317 * stored will the byte offset after the last valid
1319 * @bytes_written: the number of bytes stored in the output buffer (not
1320 * including the terminating nul).
1321 * @error: location to store the error occuring, or %NULL to ignore
1322 * errors. Any of the errors in #GConvertError may occur.
1324 * Converts a string which is in the encoding used by GLib for
1325 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1326 * for filenames; on other platforms, this function indirectly depends on
1327 * the <link linkend="setlocale">current locale</link>.
1329 * Return value: The converted string, or %NULL on an error.
1332 g_filename_to_utf8 (const gchar *opsysstring,
1335 gsize *bytes_written,
1338 const gchar *charset;
1340 if (get_filename_charset (&charset))
1341 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1343 return g_convert (opsysstring, len,
1344 "UTF-8", charset, bytes_read, bytes_written, error);
1347 #if defined (G_OS_WIN32) && !defined (_WIN64)
1349 #undef g_filename_to_utf8
1351 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1352 * 64-bit versions as there should be no old deployed binaries that would use
1357 g_filename_to_utf8 (const gchar *opsysstring,
1360 gsize *bytes_written,
1363 const gchar *charset;
1365 if (g_get_charset (&charset))
1366 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1368 return g_convert (opsysstring, len,
1369 "UTF-8", charset, bytes_read, bytes_written, error);
1375 * g_filename_from_utf8:
1376 * @utf8string: a UTF-8 encoded string.
1377 * @len: the length of the string, or -1 if the string is
1379 * @bytes_read: location to store the number of bytes in the
1380 * input string that were successfully converted, or %NULL.
1381 * Even if the conversion was successful, this may be
1382 * less than @len if there were partial characters
1383 * at the end of the input. If the error
1384 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1385 * stored will the byte offset after the last valid
1387 * @bytes_written: the number of bytes stored in the output buffer (not
1388 * including the terminating nul).
1389 * @error: location to store the error occuring, or %NULL to ignore
1390 * errors. Any of the errors in #GConvertError may occur.
1392 * Converts a string from UTF-8 to the encoding GLib uses for
1393 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1394 * on other platforms, this function indirectly depends on the
1395 * <link linkend="setlocale">current locale</link>.
1397 * Return value: The converted string, or %NULL on an error.
1400 g_filename_from_utf8 (const gchar *utf8string,
1403 gsize *bytes_written,
1406 const gchar *charset;
1408 if (get_filename_charset (&charset))
1409 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1411 return g_convert (utf8string, len,
1412 charset, "UTF-8", bytes_read, bytes_written, error);
1415 #if defined (G_OS_WIN32) && !defined (_WIN64)
1417 #undef g_filename_from_utf8
1419 /* Binary compatibility version. Not for newly compiled code. */
1422 g_filename_from_utf8 (const gchar *utf8string,
1425 gsize *bytes_written,
1428 const gchar *charset;
1430 if (g_get_charset (&charset))
1431 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1433 return g_convert (utf8string, len,
1434 charset, "UTF-8", bytes_read, bytes_written, error);
1439 /* Test of haystack has the needle prefix, comparing case
1440 * insensitive. haystack may be UTF-8, but needle must
1441 * contain only ascii. */
1443 has_case_prefix (const gchar *haystack, const gchar *needle)
1447 /* Eat one character at a time. */
1452 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1462 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1463 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1464 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1465 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1466 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1467 } UnsafeCharacterSet;
1469 static const guchar acceptable[96] = {
1470 /* A table of the ASCII chars from space (32) to DEL (127) */
1471 /* ! " # $ % & ' ( ) * + , - . / */
1472 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1473 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1474 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1475 /* @ A B C D E F G H I J K L M N O */
1476 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1477 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1478 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1479 /* ` a b c d e f g h i j k l m n o */
1480 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1481 /* p q r s t u v w x y z { | } ~ DEL */
1482 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1485 static const gchar hex[16] = "0123456789ABCDEF";
1487 /* Note: This escape function works on file: URIs, but if you want to
1488 * escape something else, please read RFC-2396 */
1490 g_escape_uri_string (const gchar *string,
1491 UnsafeCharacterSet mask)
1493 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1500 UnsafeCharacterSet use_mask;
1502 g_return_val_if_fail (mask == UNSAFE_ALL
1503 || mask == UNSAFE_ALLOW_PLUS
1504 || mask == UNSAFE_PATH
1505 || mask == UNSAFE_HOST
1506 || mask == UNSAFE_SLASHES, NULL);
1510 for (p = string; *p != '\0'; p++)
1513 if (!ACCEPTABLE (c))
1517 result = g_malloc (p - string + unacceptable * 2 + 1);
1520 for (q = result, p = string; *p != '\0'; p++)
1524 if (!ACCEPTABLE (c))
1526 *q++ = '%'; /* means hex coming */
1541 g_escape_file_uri (const gchar *hostname,
1542 const gchar *pathname)
1544 char *escaped_hostname = NULL;
1549 char *p, *backslash;
1551 /* Turn backslashes into forward slashes. That's what Netscape
1552 * does, and they are actually more or less equivalent in Windows.
1555 pathname = g_strdup (pathname);
1556 p = (char *) pathname;
1558 while ((backslash = strchr (p, '\\')) != NULL)
1565 if (hostname && *hostname != '\0')
1567 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1570 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1572 res = g_strconcat ("file://",
1573 (escaped_hostname) ? escaped_hostname : "",
1574 (*escaped_path != '/') ? "/" : "",
1579 g_free ((char *) pathname);
1582 g_free (escaped_hostname);
1583 g_free (escaped_path);
1589 unescape_character (const char *scanner)
1594 first_digit = g_ascii_xdigit_value (scanner[0]);
1595 if (first_digit < 0)
1598 second_digit = g_ascii_xdigit_value (scanner[1]);
1599 if (second_digit < 0)
1602 return (first_digit << 4) | second_digit;
1606 g_unescape_uri_string (const char *escaped,
1608 const char *illegal_escaped_characters,
1609 gboolean ascii_must_not_be_escaped)
1611 const gchar *in, *in_end;
1612 gchar *out, *result;
1615 if (escaped == NULL)
1619 len = strlen (escaped);
1621 result = g_malloc (len + 1);
1624 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1630 /* catch partial escape sequences past the end of the substring */
1631 if (in + 3 > in_end)
1634 c = unescape_character (in + 1);
1636 /* catch bad escape sequences and NUL characters */
1640 /* catch escaped ASCII */
1641 if (ascii_must_not_be_escaped && c <= 0x7F)
1644 /* catch other illegal escaped characters */
1645 if (strchr (illegal_escaped_characters, c) != NULL)
1654 g_assert (out - result <= len);
1667 is_asciialphanum (gunichar c)
1669 return c <= 0x7F && g_ascii_isalnum (c);
1673 is_asciialpha (gunichar c)
1675 return c <= 0x7F && g_ascii_isalpha (c);
1678 /* allows an empty string */
1680 hostname_validate (const char *hostname)
1683 gunichar c, first_char, last_char;
1690 /* read in a label */
1691 c = g_utf8_get_char (p);
1692 p = g_utf8_next_char (p);
1693 if (!is_asciialphanum (c))
1699 c = g_utf8_get_char (p);
1700 p = g_utf8_next_char (p);
1702 while (is_asciialphanum (c) || c == '-');
1703 if (last_char == '-')
1706 /* if that was the last label, check that it was a toplabel */
1707 if (c == '\0' || (c == '.' && *p == '\0'))
1708 return is_asciialpha (first_char);
1715 * g_filename_from_uri:
1716 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1717 * @hostname: Location to store hostname for the URI, or %NULL.
1718 * If there is no hostname in the URI, %NULL will be
1719 * stored in this location.
1720 * @error: location to store the error occuring, or %NULL to ignore
1721 * errors. Any of the errors in #GConvertError may occur.
1723 * Converts an escaped ASCII-encoded URI to a local filename in the
1724 * encoding used for filenames.
1726 * Return value: a newly-allocated string holding the resulting
1727 * filename, or %NULL on an error.
1730 g_filename_from_uri (const gchar *uri,
1734 const char *path_part;
1735 const char *host_part;
1736 char *unescaped_hostname;
1747 if (!has_case_prefix (uri, "file:/"))
1749 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1750 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1755 path_part = uri + strlen ("file:");
1757 if (strchr (path_part, '#') != NULL)
1759 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1760 _("The local file URI '%s' may not include a '#'"),
1765 if (has_case_prefix (path_part, "///"))
1767 else if (has_case_prefix (path_part, "//"))
1770 host_part = path_part;
1772 path_part = strchr (path_part, '/');
1774 if (path_part == NULL)
1776 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1777 _("The URI '%s' is invalid"),
1782 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1784 if (unescaped_hostname == NULL ||
1785 !hostname_validate (unescaped_hostname))
1787 g_free (unescaped_hostname);
1788 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1789 _("The hostname of the URI '%s' is invalid"),
1795 *hostname = unescaped_hostname;
1797 g_free (unescaped_hostname);
1800 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1802 if (filename == NULL)
1804 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1805 _("The URI '%s' contains invalidly escaped characters"),
1812 /* Drop localhost */
1813 if (hostname && *hostname != NULL &&
1814 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1820 /* Turn slashes into backslashes, because that's the canonical spelling */
1822 while ((slash = strchr (p, '/')) != NULL)
1828 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1829 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1830 * the filename from the drive letter.
1832 if (g_ascii_isalpha (filename[1]))
1834 if (filename[2] == ':')
1836 else if (filename[2] == '|')
1844 result = g_strdup (filename + offs);
1850 #if defined (G_OS_WIN32) && !defined (_WIN64)
1852 #undef g_filename_from_uri
1855 g_filename_from_uri (const gchar *uri,
1859 gchar *utf8_filename;
1860 gchar *retval = NULL;
1862 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1865 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1866 g_free (utf8_filename);
1874 * g_filename_to_uri:
1875 * @filename: an absolute filename specified in the GLib file name encoding,
1876 * which is the on-disk file name bytes on Unix, and UTF-8 on
1878 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
1879 * @error: location to store the error occuring, or %NULL to ignore
1880 * errors. Any of the errors in #GConvertError may occur.
1882 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1883 * component following Section 3.3. of RFC 2396.
1885 * Return value: a newly-allocated string holding the resulting
1886 * URI, or %NULL on an error.
1889 g_filename_to_uri (const gchar *filename,
1890 const gchar *hostname,
1895 g_return_val_if_fail (filename != NULL, NULL);
1897 if (!g_path_is_absolute (filename))
1899 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
1900 _("The pathname '%s' is not an absolute path"),
1906 !(g_utf8_validate (hostname, -1, NULL)
1907 && hostname_validate (hostname)))
1909 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1910 _("Invalid hostname"));
1915 /* Don't use localhost unnecessarily */
1916 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
1920 escaped_uri = g_escape_file_uri (hostname, filename);
1925 #if defined (G_OS_WIN32) && !defined (_WIN64)
1927 #undef g_filename_to_uri
1930 g_filename_to_uri (const gchar *filename,
1931 const gchar *hostname,
1934 gchar *utf8_filename;
1935 gchar *retval = NULL;
1937 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
1941 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
1942 g_free (utf8_filename);
1951 * g_uri_list_extract_uris:
1952 * @uri_list: an URI list
1954 * Splits an URI list conforming to the text/uri-list
1955 * mime type defined in RFC 2483 into individual URIs,
1956 * discarding any comments. The URIs are not validated.
1958 * Returns: a newly allocated %NULL-terminated list of
1959 * strings holding the individual URIs. The array should
1960 * be freed with g_strfreev().
1965 g_uri_list_extract_uris (const gchar *uri_list)
1976 /* We don't actually try to validate the URI according to RFC
1977 * 2396, or even check for allowed characters - we just ignore
1978 * comments and trim whitespace off the ends. We also
1979 * allow LF delimination as well as the specified CRLF.
1981 * We do allow comments like specified in RFC 2483.
1987 while (g_ascii_isspace (*p))
1991 while (*q && (*q != '\n') && (*q != '\r'))
1997 while (q > p && g_ascii_isspace (*q))
2002 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2007 p = strchr (p, '\n');
2012 result = g_new (gchar *, n_uris + 1);
2014 result[n_uris--] = NULL;
2015 for (u = uris; u; u = u->next)
2016 result[n_uris--] = u->data;
2018 g_slist_free (uris);
2024 * g_filename_display_basename:
2025 * @filename: an absolute pathname in the GLib file name encoding
2027 * Returns the display basename for the particular filename, guaranteed
2028 * to be valid UTF-8. The display name might not be identical to the filename,
2029 * for instance there might be problems converting it to UTF-8, and some files
2030 * can be translated in the display.
2032 * If GLib can not make sense of the encoding of @filename, as a last resort it
2033 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2034 * You can search the result for the UTF-8 encoding of this character (which is
2035 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2038 * You must pass the whole absolute pathname to this functions so that
2039 * translation of well known locations can be done.
2041 * This function is preferred over g_filename_display_name() if you know the
2042 * whole path, as it allows translation.
2044 * Return value: a newly allocated string containing
2045 * a rendition of the basename of the filename in valid UTF-8
2050 g_filename_display_basename (const gchar *filename)
2055 g_return_val_if_fail (filename != NULL, NULL);
2057 basename = g_path_get_basename (filename);
2058 display_name = g_filename_display_name (basename);
2060 return display_name;
2064 * g_filename_display_name:
2065 * @filename: a pathname hopefully in the GLib file name encoding
2067 * Converts a filename into a valid UTF-8 string. The conversion is
2068 * not necessarily reversible, so you should keep the original around
2069 * and use the return value of this function only for display purposes.
2070 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2071 * even if the filename actually isn't in the GLib file name encoding.
2073 * If GLib can not make sense of the encoding of @filename, as a last resort it
2074 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2075 * You can search the result for the UTF-8 encoding of this character (which is
2076 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2079 * If you know the whole pathname of the file you should use
2080 * g_filename_display_basename(), since that allows location-based
2081 * translation of filenames.
2083 * Return value: a newly allocated string containing
2084 * a rendition of the filename in valid UTF-8
2089 g_filename_display_name (const gchar *filename)
2092 const gchar **charsets;
2093 gchar *display_name = NULL;
2096 is_utf8 = g_get_filename_charsets (&charsets);
2100 if (g_utf8_validate (filename, -1, NULL))
2101 display_name = g_strdup (filename);
2106 /* Try to convert from the filename charsets to UTF-8.
2107 * Skip the first charset if it is UTF-8.
2109 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2111 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
2119 /* if all conversions failed, we replace invalid UTF-8
2120 * by a question mark
2123 display_name = _g_utf8_make_valid (filename);
2125 return display_name;