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.
24 #include "glibconfig.h"
35 #include "win_iconv.c"
38 #ifdef G_PLATFORM_WIN32
46 #include "gprintfint.h"
48 #include "gstrfuncs.h"
49 #include "gtestutils.h"
51 #include "gthreadprivate.h"
54 #ifdef NEED_ICONV_CACHE
61 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
62 #error GNU libiconv in use but included iconv.h not from libiconv
64 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
65 #error GNU libiconv not in use but included iconv.h is from libiconv
71 * @title: Character Set Conversion
72 * @short_description: Convert strings between different character sets
74 * The g_convert() family of function wraps the functionality of iconv(). In
75 * addition to pure character set conversions, GLib has functions to deal
76 * with the extra complications of encodings for file names.
78 * <refsect2 id="file-name-encodings">
79 * <title>File Name Encodings</title>
81 * Historically, Unix has not had a defined encoding for file
82 * names: a file name is valid as long as it does not have path
83 * separators in it ("/"). However, displaying file names may
84 * require conversion: from the character set in which they were
85 * created, to the character set in which the application
86 * operates. Consider the Spanish file name
87 * "<filename>Presentación.sxi</filename>". If the
88 * application which created it uses ISO-8859-1 for its encoding,
90 * <programlisting id="filename-iso8859-1">
91 * Character: P r e s e n t a c i ó n . s x i
92 * Hex code: 50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
95 * However, if the application use UTF-8, the actual file name on
96 * disk would look like this:
98 * <programlisting id="filename-utf-8">
99 * Character: P r e s e n t a c i ó n . s x i
100 * Hex code: 50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
103 * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+
104 * that use Glib do the same thing. If you get a file name from
105 * the file system, for example, from readdir(3) or from g_dir_read_name(),
106 * and you wish to display the file name to the user, you
107 * <emphasis>will</emphasis> need to convert it into UTF-8. The
108 * opposite case is when the user types the name of a file he
109 * wishes to save: the toolkit will give you that string in
110 * UTF-8 encoding, and you will need to convert it to the
111 * character set used for file names before you can create the
112 * file with open(2) or fopen(3).
115 * By default, Glib assumes that file names on disk are in UTF-8
116 * encoding. This is a valid assumption for file systems which
117 * were created relatively recently: most applications use UTF-8
118 * encoding for their strings, and that is also what they use for
119 * the file names they create. However, older file systems may
120 * still contain file names created in "older" encodings, such as
121 * ISO-8859-1. In this case, for compatibility reasons, you may
122 * want to instruct Glib to use that particular encoding for file
123 * names rather than UTF-8. You can do this by specifying the
124 * encoding for file names in the <link
125 * linkend="G_FILENAME_ENCODING"><envar>G_FILENAME_ENCODING</envar></link>
126 * environment variable. For example, if your installation uses
127 * ISO-8859-1 for file names, you can put this in your
128 * <filename>~/.profile</filename>:
131 * export G_FILENAME_ENCODING=ISO-8859-1
134 * Glib provides the functions g_filename_to_utf8() and
135 * g_filename_from_utf8() to perform the necessary conversions. These
136 * functions convert file names from the encoding specified in
137 * <envar>G_FILENAME_ENCODING</envar> to UTF-8 and vice-versa.
138 * <xref linkend="file-name-encodings-diagram"/> illustrates how
139 * these functions are used to convert between UTF-8 and the
140 * encoding for file names in the file system.
142 * <figure id="file-name-encodings-diagram">
143 * <title>Conversion between File Name Encodings</title>
144 * <graphic fileref="file-name-encodings.png" format="PNG"/>
146 * <refsect3 id="file-name-encodings-checklist">
147 * <title>Checklist for Application Writers</title>
149 * This section is a practical summary of the detailed
150 * description above. You can use this as a checklist of
151 * things to do to make sure your applications process file
152 * name encodings correctly.
156 * If you get a file name from the file system from a function
157 * such as readdir(3) or gtk_file_chooser_get_filename(),
158 * you do not need to do any conversion to pass that
159 * file name to functions like open(2), rename(2), or
160 * fopen(3) — those are "raw" file names which the file
161 * system understands.
164 * If you need to display a file name, convert it to UTF-8 first by
165 * using g_filename_to_utf8(). If conversion fails, display a string like
166 * "<literal>Unknown file name</literal>". <emphasis>Do not</emphasis>
167 * convert this string back into the encoding used for file names if you
168 * wish to pass it to the file system; use the original file name instead.
169 * For example, the document window of a word processor could display
170 * "Unknown file name" in its title bar but still let the user save the
171 * file, as it would keep the raw file name internally. This can happen
172 * if the user has not set the <envar>G_FILENAME_ENCODING</envar>
173 * environment variable even though he has files whose names are not
177 * If your user interface lets the user type a file name for saving or
178 * renaming, convert it to the encoding used for file names in the file
179 * system by using g_filename_from_utf8(). Pass the converted file name
180 * to functions like fopen(3). If conversion fails, ask the user to enter
181 * a different file name. This can happen if the user types Japanese
182 * characters when <envar>G_FILENAME_ENCODING</envar> is set to
183 * <literal>ISO-8859-1</literal>, for example.
190 /* We try to terminate strings in unknown charsets with this many zero bytes
191 * to ensure that multibyte strings really are nul-terminated when we return
192 * them from g_convert() and friends.
194 #define NUL_TERMINATOR_LENGTH 4
197 g_convert_error_quark (void)
199 return g_quark_from_static_string ("g_convert_error");
203 try_conversion (const char *to_codeset,
204 const char *from_codeset,
207 *cd = iconv_open (to_codeset, from_codeset);
209 if (*cd == (iconv_t)-1 && errno == EINVAL)
216 try_to_aliases (const char **to_aliases,
217 const char *from_codeset,
222 const char **p = to_aliases;
225 if (try_conversion (*p, from_codeset, cd))
235 G_GNUC_INTERNAL extern const char **
236 _g_charset_get_aliases (const char *canonical_name);
240 * @to_codeset: destination codeset
241 * @from_codeset: source codeset
243 * Same as the standard UNIX routine iconv_open(), but
244 * may be implemented via libiconv on UNIX flavors that lack
245 * a native implementation.
247 * GLib provides g_convert() and g_locale_to_utf8() which are likely
248 * more convenient than the raw iconv wrappers.
250 * Return value: a "conversion descriptor", or (GIConv)-1 if
251 * opening the converter failed.
254 g_iconv_open (const gchar *to_codeset,
255 const gchar *from_codeset)
259 if (!try_conversion (to_codeset, from_codeset, &cd))
261 const char **to_aliases = _g_charset_get_aliases (to_codeset);
262 const char **from_aliases = _g_charset_get_aliases (from_codeset);
266 const char **p = from_aliases;
269 if (try_conversion (to_codeset, *p, &cd))
272 if (try_to_aliases (to_aliases, *p, &cd))
279 if (try_to_aliases (to_aliases, from_codeset, &cd))
284 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
289 * @converter: conversion descriptor from g_iconv_open()
290 * @inbuf: bytes to convert
291 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
292 * @outbuf: converted output bytes
293 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
295 * Same as the standard UNIX routine iconv(), but
296 * may be implemented via libiconv on UNIX flavors that lack
297 * a native implementation.
299 * GLib provides g_convert() and g_locale_to_utf8() which are likely
300 * more convenient than the raw iconv wrappers.
302 * Return value: count of non-reversible conversions, or -1 on error
305 g_iconv (GIConv converter,
309 gsize *outbytes_left)
311 iconv_t cd = (iconv_t)converter;
313 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
318 * @converter: a conversion descriptor from g_iconv_open()
320 * Same as the standard UNIX routine iconv_close(), but
321 * may be implemented via libiconv on UNIX flavors that lack
322 * a native implementation. Should be called to clean up
323 * the conversion descriptor from g_iconv_open() when
324 * you are done converting things.
326 * GLib provides g_convert() and g_locale_to_utf8() which are likely
327 * more convenient than the raw iconv wrappers.
329 * Return value: -1 on error, 0 on success
332 g_iconv_close (GIConv converter)
334 iconv_t cd = (iconv_t)converter;
336 return iconv_close (cd);
340 #ifdef NEED_ICONV_CACHE
342 #define ICONV_CACHE_SIZE (16)
344 struct _iconv_cache_bucket {
351 static GList *iconv_cache_list;
352 static GHashTable *iconv_cache;
353 static GHashTable *iconv_open_hash;
354 static guint iconv_cache_size = 0;
355 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
357 /* caller *must* hold the iconv_cache_lock */
359 iconv_cache_init (void)
361 static gboolean initialized = FALSE;
366 iconv_cache_list = NULL;
367 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
368 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
375 * iconv_cache_bucket_new:
377 * @cd: iconv descriptor
379 * Creates a new cache bucket, inserts it into the cache and
380 * increments the cache size.
382 * This assumes ownership of @key.
384 * Returns a pointer to the newly allocated cache bucket.
386 static struct _iconv_cache_bucket *
387 iconv_cache_bucket_new (gchar *key, GIConv cd)
389 struct _iconv_cache_bucket *bucket;
391 bucket = g_new (struct _iconv_cache_bucket, 1);
393 bucket->refcount = 1;
397 g_hash_table_insert (iconv_cache, bucket->key, bucket);
399 /* FIXME: if we sorted the list so items with few refcounts were
400 first, then we could expire them faster in iconv_cache_expire_unused () */
401 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
410 * iconv_cache_bucket_expire:
411 * @node: cache bucket's node
412 * @bucket: cache bucket
414 * Expires a single cache bucket @bucket. This should only ever be
415 * called on a bucket that currently has no used iconv descriptors
418 * @node is not a required argument. If @node is not supplied, we
419 * search for it ourselves.
422 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
424 g_hash_table_remove (iconv_cache, bucket->key);
427 node = g_list_find (iconv_cache_list, bucket);
429 g_assert (node != NULL);
433 node->prev->next = node->next;
435 node->next->prev = node->prev;
439 iconv_cache_list = node->next;
441 node->next->prev = NULL;
444 g_list_free_1 (node);
446 g_free (bucket->key);
447 g_iconv_close (bucket->cd);
455 * iconv_cache_expire_unused:
457 * Expires as many unused cache buckets as it needs to in order to get
458 * the total number of buckets < ICONV_CACHE_SIZE.
461 iconv_cache_expire_unused (void)
463 struct _iconv_cache_bucket *bucket;
466 node = iconv_cache_list;
467 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
472 if (bucket->refcount == 0)
473 iconv_cache_bucket_expire (node, bucket);
480 open_converter (const gchar *to_codeset,
481 const gchar *from_codeset,
484 struct _iconv_cache_bucket *bucket;
485 gchar *key, *dyn_key, auto_key[80];
487 gsize len_from_codeset, len_to_codeset;
490 len_from_codeset = strlen (from_codeset);
491 len_to_codeset = strlen (to_codeset);
492 if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
498 key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
499 memcpy (key, from_codeset, len_from_codeset);
500 key[len_from_codeset] = ':';
501 strcpy (key + len_from_codeset + 1, to_codeset);
503 G_LOCK (iconv_cache_lock);
505 /* make sure the cache has been initialized */
508 bucket = g_hash_table_lookup (iconv_cache, key);
515 cd = g_iconv_open (to_codeset, from_codeset);
516 if (cd == (GIConv) -1)
521 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
522 * NULL for anything but inbuf; work around that. (NULL outbuf
523 * or NULL *outbuf is allowed by Unix98.)
525 gsize inbytes_left = 0;
526 gchar *outbuf = NULL;
527 gsize outbytes_left = 0;
532 /* reset the descriptor */
533 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
540 cd = g_iconv_open (to_codeset, from_codeset);
541 if (cd == (GIConv) -1)
547 iconv_cache_expire_unused ();
549 bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
552 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
554 G_UNLOCK (iconv_cache_lock);
560 G_UNLOCK (iconv_cache_lock);
562 /* Something went wrong. */
566 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
567 _("Conversion from character set '%s' to '%s' is not supported"),
568 from_codeset, to_codeset);
570 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
571 _("Could not open converter from '%s' to '%s'"),
572 from_codeset, to_codeset);
579 close_converter (GIConv converter)
581 struct _iconv_cache_bucket *bucket;
587 if (cd == (GIConv) -1)
590 G_LOCK (iconv_cache_lock);
592 key = g_hash_table_lookup (iconv_open_hash, cd);
595 g_hash_table_remove (iconv_open_hash, cd);
597 bucket = g_hash_table_lookup (iconv_cache, key);
602 if (cd == bucket->cd)
603 bucket->used = FALSE;
607 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
609 /* expire this cache bucket */
610 iconv_cache_bucket_expire (NULL, bucket);
615 G_UNLOCK (iconv_cache_lock);
617 g_warning ("This iconv context wasn't opened using open_converter");
619 return g_iconv_close (converter);
622 G_UNLOCK (iconv_cache_lock);
627 #else /* !NEED_ICONV_CACHE */
630 open_converter (const gchar *to_codeset,
631 const gchar *from_codeset,
636 cd = g_iconv_open (to_codeset, from_codeset);
638 if (cd == (GIConv) -1)
640 /* Something went wrong. */
644 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
645 _("Conversion from character set '%s' to '%s' is not supported"),
646 from_codeset, to_codeset);
648 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
649 _("Could not open converter from '%s' to '%s'"),
650 from_codeset, to_codeset);
658 close_converter (GIConv cd)
660 if (cd == (GIConv) -1)
663 return g_iconv_close (cd);
666 #endif /* NEED_ICONV_CACHE */
669 * g_convert_with_iconv:
670 * @str: the string to convert
671 * @len: the length of the string, or -1 if the string is
672 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
673 * @converter: conversion descriptor from g_iconv_open()
674 * @bytes_read: location to store the number of bytes in the
675 * input string that were successfully converted, or %NULL.
676 * Even if the conversion was successful, this may be
677 * less than @len if there were partial characters
678 * at the end of the input. If the error
679 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
680 * stored will the byte offset after the last valid
682 * @bytes_written: the number of bytes stored in the output buffer (not
683 * including the terminating nul).
684 * @error: location to store the error occurring, or %NULL to ignore
685 * errors. Any of the errors in #GConvertError may occur.
687 * Converts a string from one character set to another.
689 * Note that you should use g_iconv() for streaming
690 * conversions<footnote id="streaming-state">
692 * Despite the fact that @byes_read can return information about partial
693 * characters, the <literal>g_convert_...</literal> functions
694 * are not generally suitable for streaming. If the underlying converter
695 * being used maintains internal state, then this won't be preserved
696 * across successive calls to g_convert(), g_convert_with_iconv() or
697 * g_convert_with_fallback(). (An example of this is the GNU C converter
698 * for CP1255 which does not emit a base character until it knows that
699 * the next character is not a mark that could combine with the base
704 * Return value: If the conversion was successful, a newly allocated
705 * nul-terminated string, which must be freed with
706 * g_free(). Otherwise %NULL and @error will be set.
709 g_convert_with_iconv (const gchar *str,
713 gsize *bytes_written,
719 gsize inbytes_remaining;
720 gsize outbytes_remaining;
723 gboolean have_error = FALSE;
724 gboolean done = FALSE;
725 gboolean reset = FALSE;
727 g_return_val_if_fail (converter != (GIConv) -1, NULL);
733 inbytes_remaining = len;
734 outbuf_size = len + NUL_TERMINATOR_LENGTH;
736 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
737 outp = dest = g_malloc (outbuf_size);
739 while (!done && !have_error)
742 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
744 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
746 if (err == (gsize) -1)
751 /* Incomplete text, do not report an error */
756 gsize used = outp - dest;
759 dest = g_realloc (dest, outbuf_size);
762 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
767 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
768 _("Invalid byte sequence in conversion input"));
776 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
777 _("Error during conversion: %s"),
788 /* call g_iconv with NULL inbuf to cleanup shift state */
790 inbytes_remaining = 0;
797 memset (outp, 0, NUL_TERMINATOR_LENGTH);
800 *bytes_read = p - str;
803 if ((p - str) != len)
808 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
809 _("Partial character sequence at end of input"));
816 *bytes_written = outp - dest; /* Doesn't include '\0' */
829 * @str: the string to convert
830 * @len: the length of the string, or -1 if the string is
831 * nul-terminated<footnote id="nul-unsafe">
833 Note that some encodings may allow nul bytes to
834 occur inside strings. In that case, using -1 for
835 the @len parameter is unsafe.
838 * @to_codeset: name of character set into which to convert @str
839 * @from_codeset: character set of @str.
840 * @bytes_read: (out): location to store the number of bytes in the
841 * input string that were successfully converted, or %NULL.
842 * Even if the conversion was successful, this may be
843 * less than @len if there were partial characters
844 * at the end of the input. If the error
845 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
846 * stored will the byte offset after the last valid
848 * @bytes_written: (out): the number of bytes stored in the output buffer (not
849 * including the terminating nul).
850 * @error: location to store the error occurring, or %NULL to ignore
851 * errors. Any of the errors in #GConvertError may occur.
853 * Converts a string from one character set to another.
855 * Note that you should use g_iconv() for streaming
856 * conversions<footnoteref linkend="streaming-state"/>.
858 * Return value: If the conversion was successful, a newly allocated
859 * nul-terminated string, which must be freed with
860 * g_free(). Otherwise %NULL and @error will be set.
863 g_convert (const gchar *str,
865 const gchar *to_codeset,
866 const gchar *from_codeset,
868 gsize *bytes_written,
874 g_return_val_if_fail (str != NULL, NULL);
875 g_return_val_if_fail (to_codeset != NULL, NULL);
876 g_return_val_if_fail (from_codeset != NULL, NULL);
878 cd = open_converter (to_codeset, from_codeset, error);
880 if (cd == (GIConv) -1)
891 res = g_convert_with_iconv (str, len, cd,
892 bytes_read, bytes_written,
895 close_converter (cd);
901 * g_convert_with_fallback:
902 * @str: the string to convert
903 * @len: the length of the string, or -1 if the string is
904 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
905 * @to_codeset: name of character set into which to convert @str
906 * @from_codeset: character set of @str.
907 * @fallback: UTF-8 string to use in place of character not
908 * present in the target encoding. (The string must be
909 * representable in the target encoding).
910 If %NULL, characters not in the target encoding will
911 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
912 * @bytes_read: location to store the number of bytes in the
913 * input string that were successfully converted, or %NULL.
914 * Even if the conversion was successful, this may be
915 * less than @len if there were partial characters
916 * at the end of the input.
917 * @bytes_written: the number of bytes stored in the output buffer (not
918 * including the terminating nul).
919 * @error: location to store the error occurring, or %NULL to ignore
920 * errors. Any of the errors in #GConvertError may occur.
922 * Converts a string from one character set to another, possibly
923 * including fallback sequences for characters not representable
924 * in the output. Note that it is not guaranteed that the specification
925 * for the fallback sequences in @fallback will be honored. Some
926 * systems may do an approximate conversion from @from_codeset
927 * to @to_codeset in their iconv() functions,
928 * in which case GLib will simply return that approximate conversion.
930 * Note that you should use g_iconv() for streaming
931 * conversions<footnoteref linkend="streaming-state"/>.
933 * Return value: If the conversion was successful, a newly allocated
934 * nul-terminated string, which must be freed with
935 * g_free(). Otherwise %NULL and @error will be set.
938 g_convert_with_fallback (const gchar *str,
940 const gchar *to_codeset,
941 const gchar *from_codeset,
942 const gchar *fallback,
944 gsize *bytes_written,
950 const gchar *insert_str = NULL;
952 gsize inbytes_remaining;
953 const gchar *save_p = NULL;
954 gsize save_inbytes = 0;
955 gsize outbytes_remaining;
959 gboolean have_error = FALSE;
960 gboolean done = FALSE;
962 GError *local_error = NULL;
964 g_return_val_if_fail (str != NULL, NULL);
965 g_return_val_if_fail (to_codeset != NULL, NULL);
966 g_return_val_if_fail (from_codeset != NULL, NULL);
971 /* Try an exact conversion; we only proceed if this fails
972 * due to an illegal sequence in the input string.
974 dest = g_convert (str, len, to_codeset, from_codeset,
975 bytes_read, bytes_written, &local_error);
979 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
981 g_propagate_error (error, local_error);
985 g_error_free (local_error);
989 /* No go; to proceed, we need a converter from "UTF-8" to
990 * to_codeset, and the string as UTF-8.
992 cd = open_converter (to_codeset, "UTF-8", error);
993 if (cd == (GIConv) -1)
1004 utf8 = g_convert (str, len, "UTF-8", from_codeset,
1005 bytes_read, &inbytes_remaining, error);
1008 close_converter (cd);
1014 /* Now the heart of the code. We loop through the UTF-8 string, and
1015 * whenever we hit an offending character, we form fallback, convert
1016 * the fallback to the target codeset, and then go back to
1017 * converting the original string after finishing with the fallback.
1019 * The variables save_p and save_inbytes store the input state
1020 * for the original string while we are converting the fallback
1024 outbuf_size = len + NUL_TERMINATOR_LENGTH;
1025 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
1026 outp = dest = g_malloc (outbuf_size);
1028 while (!done && !have_error)
1030 gsize inbytes_tmp = inbytes_remaining;
1031 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
1032 inbytes_remaining = inbytes_tmp;
1034 if (err == (gsize) -1)
1039 g_assert_not_reached();
1043 gsize used = outp - dest;
1046 dest = g_realloc (dest, outbuf_size);
1049 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
1056 /* Error converting fallback string - fatal
1058 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1059 _("Cannot convert fallback '%s' to codeset '%s'"),
1060 insert_str, to_codeset);
1068 gunichar ch = g_utf8_get_char (p);
1069 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
1073 insert_str = fallback;
1075 save_p = g_utf8_next_char (p);
1076 save_inbytes = inbytes_remaining - (save_p - p);
1078 inbytes_remaining = strlen (p);
1081 /* fall thru if p is NULL */
1086 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1087 _("Error during conversion: %s"),
1088 g_strerror (errsv));
1100 g_free ((gchar *)insert_str);
1102 inbytes_remaining = save_inbytes;
1107 /* call g_iconv with NULL inbuf to cleanup shift state */
1109 inbytes_remaining = 0;
1118 memset (outp, 0, NUL_TERMINATOR_LENGTH);
1120 close_converter (cd);
1123 *bytes_written = outp - dest; /* Doesn't include '\0' */
1129 if (save_p && !fallback)
1130 g_free ((gchar *)insert_str);
1145 strdup_len (const gchar *string,
1147 gsize *bytes_written,
1154 if (!g_utf8_validate (string, len, NULL))
1161 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1162 _("Invalid byte sequence in conversion input"));
1167 real_len = strlen (string);
1172 while (real_len < len && string[real_len])
1177 *bytes_read = real_len;
1179 *bytes_written = real_len;
1181 return g_strndup (string, real_len);
1186 * @opsysstring: a string in the encoding of the current locale. On Windows
1187 * this means the system codepage.
1188 * @len: the length of the string, or -1 if the string is
1189 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1190 * @bytes_read: location to store the number of bytes in the
1191 * input string that were successfully converted, or %NULL.
1192 * Even if the conversion was successful, this may be
1193 * less than @len if there were partial characters
1194 * at the end of the input. If the error
1195 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1196 * stored will the byte offset after the last valid
1198 * @bytes_written: the number of bytes stored in the output buffer (not
1199 * including the terminating nul).
1200 * @error: location to store the error occurring, or %NULL to ignore
1201 * errors. Any of the errors in #GConvertError may occur.
1203 * Converts a string which is in the encoding used for strings by
1204 * the C runtime (usually the same as that used by the operating
1205 * system) in the <link linkend="setlocale">current locale</link> into a
1208 * Return value: The converted string, or %NULL on an error.
1211 g_locale_to_utf8 (const gchar *opsysstring,
1214 gsize *bytes_written,
1217 const char *charset;
1219 if (g_get_charset (&charset))
1220 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1222 return g_convert (opsysstring, len,
1223 "UTF-8", charset, bytes_read, bytes_written, error);
1227 * g_locale_from_utf8:
1228 * @utf8string: a UTF-8 encoded string
1229 * @len: the length of the string, or -1 if the string is
1230 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1231 * @bytes_read: location to store the number of bytes in the
1232 * input string that were successfully converted, or %NULL.
1233 * Even if the conversion was successful, this may be
1234 * less than @len if there were partial characters
1235 * at the end of the input. If the error
1236 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1237 * stored will the byte offset after the last valid
1239 * @bytes_written: the number of bytes stored in the output buffer (not
1240 * including the terminating nul).
1241 * @error: location to store the error occurring, or %NULL to ignore
1242 * errors. Any of the errors in #GConvertError may occur.
1244 * Converts a string from UTF-8 to the encoding used for strings by
1245 * the C runtime (usually the same as that used by the operating
1246 * system) in the <link linkend="setlocale">current locale</link>. On
1247 * Windows this means the system codepage.
1249 * Return value: The converted string, or %NULL on an error.
1252 g_locale_from_utf8 (const gchar *utf8string,
1255 gsize *bytes_written,
1258 const gchar *charset;
1260 if (g_get_charset (&charset))
1261 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1263 return g_convert (utf8string, len,
1264 charset, "UTF-8", bytes_read, bytes_written, error);
1267 #ifndef G_PLATFORM_WIN32
1269 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1271 struct _GFilenameCharsetCache {
1274 gchar **filename_charsets;
1278 filename_charset_cache_free (gpointer data)
1280 GFilenameCharsetCache *cache = data;
1281 g_free (cache->charset);
1282 g_strfreev (cache->filename_charsets);
1287 * g_get_filename_charsets:
1288 * @charsets: return location for the %NULL-terminated list of encoding names
1290 * Determines the preferred character sets used for filenames.
1291 * The first character set from the @charsets is the filename encoding, the
1292 * subsequent character sets are used when trying to generate a displayable
1293 * representation of a filename, see g_filename_display_name().
1295 * On Unix, the character sets are determined by consulting the
1296 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1297 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1298 * used in the GLib API is always UTF-8 and said environment variables
1301 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1302 * of character set names. The special token "@locale" is taken to
1303 * mean the character set for the <link linkend="setlocale">current
1304 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1305 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1306 * locale is taken as the filename encoding. If neither environment variable
1307 * is set, UTF-8 is taken as the filename encoding, but the character
1308 * set of the current locale is also put in the list of encodings.
1310 * The returned @charsets belong to GLib and must not be freed.
1312 * Note that on Unix, regardless of the locale character set or
1313 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1314 * on a system might be in any random encoding or just gibberish.
1316 * Return value: %TRUE if the filename encoding is UTF-8.
1321 g_get_filename_charsets (const gchar ***filename_charsets)
1323 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1324 GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1325 const gchar *charset;
1329 cache = g_new0 (GFilenameCharsetCache, 1);
1330 g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1333 g_get_charset (&charset);
1335 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1337 const gchar *new_charset;
1341 g_free (cache->charset);
1342 g_strfreev (cache->filename_charsets);
1343 cache->charset = g_strdup (charset);
1345 p = getenv ("G_FILENAME_ENCODING");
1346 if (p != NULL && p[0] != '\0')
1348 cache->filename_charsets = g_strsplit (p, ",", 0);
1349 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1351 for (i = 0; cache->filename_charsets[i]; i++)
1353 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1355 g_get_charset (&new_charset);
1356 g_free (cache->filename_charsets[i]);
1357 cache->filename_charsets[i] = g_strdup (new_charset);
1361 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1363 cache->filename_charsets = g_new0 (gchar *, 2);
1364 cache->is_utf8 = g_get_charset (&new_charset);
1365 cache->filename_charsets[0] = g_strdup (new_charset);
1369 cache->filename_charsets = g_new0 (gchar *, 3);
1370 cache->is_utf8 = TRUE;
1371 cache->filename_charsets[0] = g_strdup ("UTF-8");
1372 if (!g_get_charset (&new_charset))
1373 cache->filename_charsets[1] = g_strdup (new_charset);
1377 if (filename_charsets)
1378 *filename_charsets = (const gchar **)cache->filename_charsets;
1380 return cache->is_utf8;
1383 #else /* G_PLATFORM_WIN32 */
1386 g_get_filename_charsets (const gchar ***filename_charsets)
1388 static const gchar *charsets[] = {
1394 /* On Windows GLib pretends that the filename charset is UTF-8 */
1395 if (filename_charsets)
1396 *filename_charsets = charsets;
1402 /* Cygwin works like before */
1403 result = g_get_charset (&(charsets[0]));
1405 if (filename_charsets)
1406 *filename_charsets = charsets;
1412 #endif /* G_PLATFORM_WIN32 */
1415 get_filename_charset (const gchar **filename_charset)
1417 const gchar **charsets;
1420 is_utf8 = g_get_filename_charsets (&charsets);
1422 if (filename_charset)
1423 *filename_charset = charsets[0];
1428 /* This is called from g_thread_init(). It's used to
1429 * initialize some static data in a threadsafe way.
1432 _g_convert_thread_init (void)
1434 const gchar **dummy;
1435 (void) g_get_filename_charsets (&dummy);
1439 * g_filename_to_utf8:
1440 * @opsysstring: a string in the encoding for filenames
1441 * @len: the length of the string, or -1 if the string is
1442 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1443 * @bytes_read: location to store the number of bytes in the
1444 * input string that were successfully converted, or %NULL.
1445 * Even if the conversion was successful, this may be
1446 * less than @len if there were partial characters
1447 * at the end of the input. If the error
1448 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1449 * stored will the byte offset after the last valid
1451 * @bytes_written: the number of bytes stored in the output buffer (not
1452 * including the terminating nul).
1453 * @error: location to store the error occurring, or %NULL to ignore
1454 * errors. Any of the errors in #GConvertError may occur.
1456 * Converts a string which is in the encoding used by GLib for
1457 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1458 * for filenames; on other platforms, this function indirectly depends on
1459 * the <link linkend="setlocale">current locale</link>.
1461 * Return value: The converted string, or %NULL on an error.
1464 g_filename_to_utf8 (const gchar *opsysstring,
1467 gsize *bytes_written,
1470 const gchar *charset;
1472 g_return_val_if_fail (opsysstring != NULL, NULL);
1474 if (get_filename_charset (&charset))
1475 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1477 return g_convert (opsysstring, len,
1478 "UTF-8", charset, bytes_read, bytes_written, error);
1481 #if defined (G_OS_WIN32) && !defined (_WIN64)
1483 #undef g_filename_to_utf8
1485 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1486 * 64-bit versions as there should be no old deployed binaries that would use
1491 g_filename_to_utf8 (const gchar *opsysstring,
1494 gsize *bytes_written,
1497 const gchar *charset;
1499 g_return_val_if_fail (opsysstring != NULL, NULL);
1501 if (g_get_charset (&charset))
1502 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1504 return g_convert (opsysstring, len,
1505 "UTF-8", charset, bytes_read, bytes_written, error);
1511 * g_filename_from_utf8:
1512 * @utf8string: a UTF-8 encoded string.
1513 * @len: the length of the string, or -1 if the string is
1515 * @bytes_read: location to store the number of bytes in the
1516 * input string that were successfully converted, or %NULL.
1517 * Even if the conversion was successful, this may be
1518 * less than @len if there were partial characters
1519 * at the end of the input. If the error
1520 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1521 * stored will the byte offset after the last valid
1523 * @bytes_written: the number of bytes stored in the output buffer (not
1524 * including the terminating nul).
1525 * @error: location to store the error occurring, or %NULL to ignore
1526 * errors. Any of the errors in #GConvertError may occur.
1528 * Converts a string from UTF-8 to the encoding GLib uses for
1529 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1530 * on other platforms, this function indirectly depends on the
1531 * <link linkend="setlocale">current locale</link>.
1533 * Return value: The converted string, or %NULL on an error.
1536 g_filename_from_utf8 (const gchar *utf8string,
1539 gsize *bytes_written,
1542 const gchar *charset;
1544 if (get_filename_charset (&charset))
1545 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1547 return g_convert (utf8string, len,
1548 charset, "UTF-8", bytes_read, bytes_written, error);
1551 #if defined (G_OS_WIN32) && !defined (_WIN64)
1553 #undef g_filename_from_utf8
1555 /* Binary compatibility version. Not for newly compiled code. */
1558 g_filename_from_utf8 (const gchar *utf8string,
1561 gsize *bytes_written,
1564 const gchar *charset;
1566 if (g_get_charset (&charset))
1567 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1569 return g_convert (utf8string, len,
1570 charset, "UTF-8", bytes_read, bytes_written, error);
1575 /* Test of haystack has the needle prefix, comparing case
1576 * insensitive. haystack may be UTF-8, but needle must
1577 * contain only ascii. */
1579 has_case_prefix (const gchar *haystack, const gchar *needle)
1583 /* Eat one character at a time. */
1588 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1598 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1599 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1600 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1601 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1602 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1603 } UnsafeCharacterSet;
1605 static const guchar acceptable[96] = {
1606 /* A table of the ASCII chars from space (32) to DEL (127) */
1607 /* ! " # $ % & ' ( ) * + , - . / */
1608 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1609 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1610 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1611 /* @ A B C D E F G H I J K L M N O */
1612 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1613 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1614 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1615 /* ` a b c d e f g h i j k l m n o */
1616 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1617 /* p q r s t u v w x y z { | } ~ DEL */
1618 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1621 static const gchar hex[16] = "0123456789ABCDEF";
1623 /* Note: This escape function works on file: URIs, but if you want to
1624 * escape something else, please read RFC-2396 */
1626 g_escape_uri_string (const gchar *string,
1627 UnsafeCharacterSet mask)
1629 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1636 UnsafeCharacterSet use_mask;
1638 g_return_val_if_fail (mask == UNSAFE_ALL
1639 || mask == UNSAFE_ALLOW_PLUS
1640 || mask == UNSAFE_PATH
1641 || mask == UNSAFE_HOST
1642 || mask == UNSAFE_SLASHES, NULL);
1646 for (p = string; *p != '\0'; p++)
1649 if (!ACCEPTABLE (c))
1653 result = g_malloc (p - string + unacceptable * 2 + 1);
1656 for (q = result, p = string; *p != '\0'; p++)
1660 if (!ACCEPTABLE (c))
1662 *q++ = '%'; /* means hex coming */
1677 g_escape_file_uri (const gchar *hostname,
1678 const gchar *pathname)
1680 char *escaped_hostname = NULL;
1685 char *p, *backslash;
1687 /* Turn backslashes into forward slashes. That's what Netscape
1688 * does, and they are actually more or less equivalent in Windows.
1691 pathname = g_strdup (pathname);
1692 p = (char *) pathname;
1694 while ((backslash = strchr (p, '\\')) != NULL)
1701 if (hostname && *hostname != '\0')
1703 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1706 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1708 res = g_strconcat ("file://",
1709 (escaped_hostname) ? escaped_hostname : "",
1710 (*escaped_path != '/') ? "/" : "",
1715 g_free ((char *) pathname);
1718 g_free (escaped_hostname);
1719 g_free (escaped_path);
1725 unescape_character (const char *scanner)
1730 first_digit = g_ascii_xdigit_value (scanner[0]);
1731 if (first_digit < 0)
1734 second_digit = g_ascii_xdigit_value (scanner[1]);
1735 if (second_digit < 0)
1738 return (first_digit << 4) | second_digit;
1742 g_unescape_uri_string (const char *escaped,
1744 const char *illegal_escaped_characters,
1745 gboolean ascii_must_not_be_escaped)
1747 const gchar *in, *in_end;
1748 gchar *out, *result;
1751 if (escaped == NULL)
1755 len = strlen (escaped);
1757 result = g_malloc (len + 1);
1760 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1766 /* catch partial escape sequences past the end of the substring */
1767 if (in + 3 > in_end)
1770 c = unescape_character (in + 1);
1772 /* catch bad escape sequences and NUL characters */
1776 /* catch escaped ASCII */
1777 if (ascii_must_not_be_escaped && c <= 0x7F)
1780 /* catch other illegal escaped characters */
1781 if (strchr (illegal_escaped_characters, c) != NULL)
1790 g_assert (out - result <= len);
1803 is_asciialphanum (gunichar c)
1805 return c <= 0x7F && g_ascii_isalnum (c);
1809 is_asciialpha (gunichar c)
1811 return c <= 0x7F && g_ascii_isalpha (c);
1814 /* allows an empty string */
1816 hostname_validate (const char *hostname)
1819 gunichar c, first_char, last_char;
1826 /* read in a label */
1827 c = g_utf8_get_char (p);
1828 p = g_utf8_next_char (p);
1829 if (!is_asciialphanum (c))
1835 c = g_utf8_get_char (p);
1836 p = g_utf8_next_char (p);
1838 while (is_asciialphanum (c) || c == '-');
1839 if (last_char == '-')
1842 /* if that was the last label, check that it was a toplabel */
1843 if (c == '\0' || (c == '.' && *p == '\0'))
1844 return is_asciialpha (first_char);
1851 * g_filename_from_uri:
1852 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1853 * @hostname: Location to store hostname for the URI, or %NULL.
1854 * If there is no hostname in the URI, %NULL will be
1855 * stored in this location.
1856 * @error: location to store the error occurring, or %NULL to ignore
1857 * errors. Any of the errors in #GConvertError may occur.
1859 * Converts an escaped ASCII-encoded URI to a local filename in the
1860 * encoding used for filenames.
1862 * Return value: a newly-allocated string holding the resulting
1863 * filename, or %NULL on an error.
1866 g_filename_from_uri (const gchar *uri,
1870 const char *path_part;
1871 const char *host_part;
1872 char *unescaped_hostname;
1883 if (!has_case_prefix (uri, "file:/"))
1885 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1886 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1891 path_part = uri + strlen ("file:");
1893 if (strchr (path_part, '#') != NULL)
1895 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1896 _("The local file URI '%s' may not include a '#'"),
1901 if (has_case_prefix (path_part, "///"))
1903 else if (has_case_prefix (path_part, "//"))
1906 host_part = path_part;
1908 path_part = strchr (path_part, '/');
1910 if (path_part == NULL)
1912 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1913 _("The URI '%s' is invalid"),
1918 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1920 if (unescaped_hostname == NULL ||
1921 !hostname_validate (unescaped_hostname))
1923 g_free (unescaped_hostname);
1924 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1925 _("The hostname of the URI '%s' is invalid"),
1931 *hostname = unescaped_hostname;
1933 g_free (unescaped_hostname);
1936 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1938 if (filename == NULL)
1940 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1941 _("The URI '%s' contains invalidly escaped characters"),
1948 /* Drop localhost */
1949 if (hostname && *hostname != NULL &&
1950 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1956 /* Turn slashes into backslashes, because that's the canonical spelling */
1958 while ((slash = strchr (p, '/')) != NULL)
1964 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1965 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1966 * the filename from the drive letter.
1968 if (g_ascii_isalpha (filename[1]))
1970 if (filename[2] == ':')
1972 else if (filename[2] == '|')
1980 result = g_strdup (filename + offs);
1986 #if defined (G_OS_WIN32) && !defined (_WIN64)
1988 #undef g_filename_from_uri
1991 g_filename_from_uri (const gchar *uri,
1995 gchar *utf8_filename;
1996 gchar *retval = NULL;
1998 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
2001 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
2002 g_free (utf8_filename);
2010 * g_filename_to_uri:
2011 * @filename: an absolute filename specified in the GLib file name encoding,
2012 * which is the on-disk file name bytes on Unix, and UTF-8 on
2014 * @hostname: (allow-none): A UTF-8 encoded hostname, or %NULL for none.
2015 * @error: location to store the error occurring, or %NULL to ignore
2016 * errors. Any of the errors in #GConvertError may occur.
2018 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
2019 * component following Section 3.3. of RFC 2396.
2021 * Return value: a newly-allocated string holding the resulting
2022 * URI, or %NULL on an error.
2025 g_filename_to_uri (const gchar *filename,
2026 const gchar *hostname,
2031 g_return_val_if_fail (filename != NULL, NULL);
2033 if (!g_path_is_absolute (filename))
2035 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
2036 _("The pathname '%s' is not an absolute path"),
2042 !(g_utf8_validate (hostname, -1, NULL)
2043 && hostname_validate (hostname)))
2045 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2046 _("Invalid hostname"));
2051 /* Don't use localhost unnecessarily */
2052 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
2056 escaped_uri = g_escape_file_uri (hostname, filename);
2061 #if defined (G_OS_WIN32) && !defined (_WIN64)
2063 #undef g_filename_to_uri
2066 g_filename_to_uri (const gchar *filename,
2067 const gchar *hostname,
2070 gchar *utf8_filename;
2071 gchar *retval = NULL;
2073 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2077 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
2078 g_free (utf8_filename);
2087 * g_uri_list_extract_uris:
2088 * @uri_list: an URI list
2090 * Splits an URI list conforming to the text/uri-list
2091 * mime type defined in RFC 2483 into individual URIs,
2092 * discarding any comments. The URIs are not validated.
2094 * Returns: a newly allocated %NULL-terminated list of
2095 * strings holding the individual URIs. The array should
2096 * be freed with g_strfreev().
2101 g_uri_list_extract_uris (const gchar *uri_list)
2112 /* We don't actually try to validate the URI according to RFC
2113 * 2396, or even check for allowed characters - we just ignore
2114 * comments and trim whitespace off the ends. We also
2115 * allow LF delimination as well as the specified CRLF.
2117 * We do allow comments like specified in RFC 2483.
2123 while (g_ascii_isspace (*p))
2127 while (*q && (*q != '\n') && (*q != '\r'))
2133 while (q > p && g_ascii_isspace (*q))
2138 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2143 p = strchr (p, '\n');
2148 result = g_new (gchar *, n_uris + 1);
2150 result[n_uris--] = NULL;
2151 for (u = uris; u; u = u->next)
2152 result[n_uris--] = u->data;
2154 g_slist_free (uris);
2160 * g_filename_display_basename:
2161 * @filename: an absolute pathname in the GLib file name encoding
2163 * Returns the display basename for the particular filename, guaranteed
2164 * to be valid UTF-8. The display name might not be identical to the filename,
2165 * for instance there might be problems converting it to UTF-8, and some files
2166 * can be translated in the display.
2168 * If GLib cannot make sense of the encoding of @filename, as a last resort it
2169 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2170 * You can search the result for the UTF-8 encoding of this character (which is
2171 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2174 * You must pass the whole absolute pathname to this functions so that
2175 * translation of well known locations can be done.
2177 * This function is preferred over g_filename_display_name() if you know the
2178 * whole path, as it allows translation.
2180 * Return value: a newly allocated string containing
2181 * a rendition of the basename of the filename in valid UTF-8
2186 g_filename_display_basename (const gchar *filename)
2191 g_return_val_if_fail (filename != NULL, NULL);
2193 basename = g_path_get_basename (filename);
2194 display_name = g_filename_display_name (basename);
2196 return display_name;
2200 * g_filename_display_name:
2201 * @filename: a pathname hopefully in the GLib file name encoding
2203 * Converts a filename into a valid UTF-8 string. The conversion is
2204 * not necessarily reversible, so you should keep the original around
2205 * and use the return value of this function only for display purposes.
2206 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2207 * even if the filename actually isn't in the GLib file name encoding.
2209 * If GLib cannot make sense of the encoding of @filename, as a last resort it
2210 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2211 * You can search the result for the UTF-8 encoding of this character (which is
2212 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2215 * If you know the whole pathname of the file you should use
2216 * g_filename_display_basename(), since that allows location-based
2217 * translation of filenames.
2219 * Return value: a newly allocated string containing
2220 * a rendition of the filename in valid UTF-8
2225 g_filename_display_name (const gchar *filename)
2228 const gchar **charsets;
2229 gchar *display_name = NULL;
2232 is_utf8 = g_get_filename_charsets (&charsets);
2236 if (g_utf8_validate (filename, -1, NULL))
2237 display_name = g_strdup (filename);
2242 /* Try to convert from the filename charsets to UTF-8.
2243 * Skip the first charset if it is UTF-8.
2245 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2247 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
2255 /* if all conversions failed, we replace invalid UTF-8
2256 * by a question mark
2259 display_name = _g_utf8_make_valid (filename);
2261 return display_name;