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.
34 #include "win_iconv.c"
37 #ifdef G_PLATFORM_WIN32
45 #include "gprintfint.h"
47 #include "gstrfuncs.h"
48 #include "gtestutils.h"
50 #include "gthreadprivate.h"
55 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
56 #error GNU libiconv in use but included iconv.h not from libiconv
58 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
59 #error GNU libiconv not in use but included iconv.h is from libiconv
65 * @title: Character Set Conversion
66 * @short_description: Convert strings between different character sets
68 * The g_convert() family of function wraps the functionality of iconv(). In
69 * addition to pure character set conversions, GLib has functions to deal
70 * with the extra complications of encodings for file names.
72 * <refsect2 id="file-name-encodings">
73 * <title>File Name Encodings</title>
75 * Historically, Unix has not had a defined encoding for file
76 * names: a file name is valid as long as it does not have path
77 * separators in it ("/"). However, displaying file names may
78 * require conversion: from the character set in which they were
79 * created, to the character set in which the application
80 * operates. Consider the Spanish file name
81 * "<filename>Presentación.sxi</filename>". If the
82 * application which created it uses ISO-8859-1 for its encoding,
84 * <programlisting id="filename-iso8859-1">
85 * Character: P r e s e n t a c i ó n . s x i
86 * Hex code: 50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
89 * However, if the application use UTF-8, the actual file name on
90 * disk would look like this:
92 * <programlisting id="filename-utf-8">
93 * Character: P r e s e n t a c i ó n . s x i
94 * Hex code: 50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
97 * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+
98 * that use Glib do the same thing. If you get a file name from
99 * the file system, for example, from readdir(3) or from g_dir_read_name(),
100 * and you wish to display the file name to the user, you
101 * <emphasis>will</emphasis> need to convert it into UTF-8. The
102 * opposite case is when the user types the name of a file he
103 * wishes to save: the toolkit will give you that string in
104 * UTF-8 encoding, and you will need to convert it to the
105 * character set used for file names before you can create the
106 * file with open(2) or fopen(3).
109 * By default, Glib assumes that file names on disk are in UTF-8
110 * encoding. This is a valid assumption for file systems which
111 * were created relatively recently: most applications use UTF-8
112 * encoding for their strings, and that is also what they use for
113 * the file names they create. However, older file systems may
114 * still contain file names created in "older" encodings, such as
115 * ISO-8859-1. In this case, for compatibility reasons, you may
116 * want to instruct Glib to use that particular encoding for file
117 * names rather than UTF-8. You can do this by specifying the
118 * encoding for file names in the <link
119 * linkend="G_FILENAME_ENCODING"><envar>G_FILENAME_ENCODING</envar></link>
120 * environment variable. For example, if your installation uses
121 * ISO-8859-1 for file names, you can put this in your
122 * <filename>~/.profile</filename>:
125 * export G_FILENAME_ENCODING=ISO-8859-1
128 * Glib provides the functions g_filename_to_utf8() and
129 * g_filename_from_utf8() to perform the necessary conversions. These
130 * functions convert file names from the encoding specified in
131 * <envar>G_FILENAME_ENCODING</envar> to UTF-8 and vice-versa.
132 * <xref linkend="file-name-encodings-diagram"/> illustrates how
133 * these functions are used to convert between UTF-8 and the
134 * encoding for file names in the file system.
136 * <figure id="file-name-encodings-diagram">
137 * <title>Conversion between File Name Encodings</title>
138 * <graphic fileref="file-name-encodings.png" format="PNG"/>
140 * <refsect3 id="file-name-encodings-checklist">
141 * <title>Checklist for Application Writers</title>
143 * This section is a practical summary of the detailed
144 * description above. You can use this as a checklist of
145 * things to do to make sure your applications process file
146 * name encodings correctly.
150 * If you get a file name from the file system from a function
151 * such as readdir(3) or gtk_file_chooser_get_filename(),
152 * you do not need to do any conversion to pass that
153 * file name to functions like open(2), rename(2), or
154 * fopen(3) — those are "raw" file names which the file
155 * system understands.
158 * If you need to display a file name, convert it to UTF-8 first by
159 * using g_filename_to_utf8(). If conversion fails, display a string like
160 * "<literal>Unknown file name</literal>". <emphasis>Do not</emphasis>
161 * convert this string back into the encoding used for file names if you
162 * wish to pass it to the file system; use the original file name instead.
163 * For example, the document window of a word processor could display
164 * "Unknown file name" in its title bar but still let the user save the
165 * file, as it would keep the raw file name internally. This can happen
166 * if the user has not set the <envar>G_FILENAME_ENCODING</envar>
167 * environment variable even though he has files whose names are not
171 * If your user interface lets the user type a file name for saving or
172 * renaming, convert it to the encoding used for file names in the file
173 * system by using g_filename_from_utf8(). Pass the converted file name
174 * to functions like fopen(3). If conversion fails, ask the user to enter
175 * a different file name. This can happen if the user types Japanese
176 * characters when <envar>G_FILENAME_ENCODING</envar> is set to
177 * <literal>ISO-8859-1</literal>, for example.
184 /* We try to terminate strings in unknown charsets with this many zero bytes
185 * to ensure that multibyte strings really are nul-terminated when we return
186 * them from g_convert() and friends.
188 #define NUL_TERMINATOR_LENGTH 4
191 g_convert_error_quark (void)
193 return g_quark_from_static_string ("g_convert_error");
197 try_conversion (const char *to_codeset,
198 const char *from_codeset,
201 *cd = iconv_open (to_codeset, from_codeset);
203 if (*cd == (iconv_t)-1 && errno == EINVAL)
210 try_to_aliases (const char **to_aliases,
211 const char *from_codeset,
216 const char **p = to_aliases;
219 if (try_conversion (*p, from_codeset, cd))
229 G_GNUC_INTERNAL extern const char **
230 _g_charset_get_aliases (const char *canonical_name);
234 * @to_codeset: destination codeset
235 * @from_codeset: source codeset
237 * Same as the standard UNIX routine iconv_open(), but
238 * may be implemented via libiconv on UNIX flavors that lack
239 * a native implementation.
241 * GLib provides g_convert() and g_locale_to_utf8() which are likely
242 * more convenient than the raw iconv wrappers.
244 * Return value: a "conversion descriptor", or (GIConv)-1 if
245 * opening the converter failed.
248 g_iconv_open (const gchar *to_codeset,
249 const gchar *from_codeset)
253 if (!try_conversion (to_codeset, from_codeset, &cd))
255 const char **to_aliases = _g_charset_get_aliases (to_codeset);
256 const char **from_aliases = _g_charset_get_aliases (from_codeset);
260 const char **p = from_aliases;
263 if (try_conversion (to_codeset, *p, &cd))
266 if (try_to_aliases (to_aliases, *p, &cd))
273 if (try_to_aliases (to_aliases, from_codeset, &cd))
278 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
283 * @converter: conversion descriptor from g_iconv_open()
284 * @inbuf: bytes to convert
285 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
286 * @outbuf: converted output bytes
287 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
289 * Same as the standard UNIX routine iconv(), but
290 * may be implemented via libiconv on UNIX flavors that lack
291 * a native implementation.
293 * GLib provides g_convert() and g_locale_to_utf8() which are likely
294 * more convenient than the raw iconv wrappers.
296 * Return value: count of non-reversible conversions, or -1 on error
299 g_iconv (GIConv converter,
303 gsize *outbytes_left)
305 iconv_t cd = (iconv_t)converter;
307 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
312 * @converter: a conversion descriptor from g_iconv_open()
314 * Same as the standard UNIX routine iconv_close(), but
315 * may be implemented via libiconv on UNIX flavors that lack
316 * a native implementation. Should be called to clean up
317 * the conversion descriptor from g_iconv_open() when
318 * you are done converting things.
320 * GLib provides g_convert() and g_locale_to_utf8() which are likely
321 * more convenient than the raw iconv wrappers.
323 * Return value: -1 on error, 0 on success
326 g_iconv_close (GIConv converter)
328 iconv_t cd = (iconv_t)converter;
330 return iconv_close (cd);
334 #ifdef NEED_ICONV_CACHE
336 #define ICONV_CACHE_SIZE (16)
338 struct _iconv_cache_bucket {
345 static GList *iconv_cache_list;
346 static GHashTable *iconv_cache;
347 static GHashTable *iconv_open_hash;
348 static guint iconv_cache_size = 0;
349 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
351 /* caller *must* hold the iconv_cache_lock */
353 iconv_cache_init (void)
355 static gboolean initialized = FALSE;
360 iconv_cache_list = NULL;
361 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
362 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
369 * iconv_cache_bucket_new:
371 * @cd: iconv descriptor
373 * Creates a new cache bucket, inserts it into the cache and
374 * increments the cache size.
376 * This assumes ownership of @key.
378 * Returns a pointer to the newly allocated cache bucket.
380 static struct _iconv_cache_bucket *
381 iconv_cache_bucket_new (gchar *key, GIConv cd)
383 struct _iconv_cache_bucket *bucket;
385 bucket = g_new (struct _iconv_cache_bucket, 1);
387 bucket->refcount = 1;
391 g_hash_table_insert (iconv_cache, bucket->key, bucket);
393 /* FIXME: if we sorted the list so items with few refcounts were
394 first, then we could expire them faster in iconv_cache_expire_unused () */
395 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
404 * iconv_cache_bucket_expire:
405 * @node: cache bucket's node
406 * @bucket: cache bucket
408 * Expires a single cache bucket @bucket. This should only ever be
409 * called on a bucket that currently has no used iconv descriptors
412 * @node is not a required argument. If @node is not supplied, we
413 * search for it ourselves.
416 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
418 g_hash_table_remove (iconv_cache, bucket->key);
421 node = g_list_find (iconv_cache_list, bucket);
423 g_assert (node != NULL);
427 node->prev->next = node->next;
429 node->next->prev = node->prev;
433 iconv_cache_list = node->next;
435 node->next->prev = NULL;
438 g_list_free_1 (node);
440 g_free (bucket->key);
441 g_iconv_close (bucket->cd);
449 * iconv_cache_expire_unused:
451 * Expires as many unused cache buckets as it needs to in order to get
452 * the total number of buckets < ICONV_CACHE_SIZE.
455 iconv_cache_expire_unused (void)
457 struct _iconv_cache_bucket *bucket;
460 node = iconv_cache_list;
461 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
466 if (bucket->refcount == 0)
467 iconv_cache_bucket_expire (node, bucket);
474 open_converter (const gchar *to_codeset,
475 const gchar *from_codeset,
478 struct _iconv_cache_bucket *bucket;
479 gchar *key, *dyn_key, auto_key[80];
481 gsize len_from_codeset, len_to_codeset;
484 len_from_codeset = strlen (from_codeset);
485 len_to_codeset = strlen (to_codeset);
486 if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
492 key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
493 memcpy (key, from_codeset, len_from_codeset);
494 key[len_from_codeset] = ':';
495 strcpy (key + len_from_codeset + 1, to_codeset);
497 G_LOCK (iconv_cache_lock);
499 /* make sure the cache has been initialized */
502 bucket = g_hash_table_lookup (iconv_cache, key);
509 cd = g_iconv_open (to_codeset, from_codeset);
510 if (cd == (GIConv) -1)
515 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
516 * NULL for anything but inbuf; work around that. (NULL outbuf
517 * or NULL *outbuf is allowed by Unix98.)
519 gsize inbytes_left = 0;
520 gchar *outbuf = NULL;
521 gsize outbytes_left = 0;
526 /* reset the descriptor */
527 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
534 cd = g_iconv_open (to_codeset, from_codeset);
535 if (cd == (GIConv) -1)
541 iconv_cache_expire_unused ();
543 bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
546 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
548 G_UNLOCK (iconv_cache_lock);
554 G_UNLOCK (iconv_cache_lock);
556 /* Something went wrong. */
560 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
561 _("Conversion from character set '%s' to '%s' is not supported"),
562 from_codeset, to_codeset);
564 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
565 _("Could not open converter from '%s' to '%s'"),
566 from_codeset, to_codeset);
573 close_converter (GIConv converter)
575 struct _iconv_cache_bucket *bucket;
581 if (cd == (GIConv) -1)
584 G_LOCK (iconv_cache_lock);
586 key = g_hash_table_lookup (iconv_open_hash, cd);
589 g_hash_table_remove (iconv_open_hash, cd);
591 bucket = g_hash_table_lookup (iconv_cache, key);
596 if (cd == bucket->cd)
597 bucket->used = FALSE;
601 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
603 /* expire this cache bucket */
604 iconv_cache_bucket_expire (NULL, bucket);
609 G_UNLOCK (iconv_cache_lock);
611 g_warning ("This iconv context wasn't opened using open_converter");
613 return g_iconv_close (converter);
616 G_UNLOCK (iconv_cache_lock);
621 #else /* !NEED_ICONV_CACHE */
624 open_converter (const gchar *to_codeset,
625 const gchar *from_codeset,
630 cd = g_iconv_open (to_codeset, from_codeset);
632 if (cd == (GIConv) -1)
634 /* Something went wrong. */
638 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
639 _("Conversion from character set '%s' to '%s' is not supported"),
640 from_codeset, to_codeset);
642 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
643 _("Could not open converter from '%s' to '%s'"),
644 from_codeset, to_codeset);
652 close_converter (GIConv cd)
654 if (cd == (GIConv) -1)
657 return g_iconv_close (cd);
660 #endif /* NEED_ICONV_CACHE */
663 * g_convert_with_iconv:
664 * @str: the string to convert
665 * @len: the length of the string, or -1 if the string is
666 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
667 * @converter: conversion descriptor from g_iconv_open()
668 * @bytes_read: location to store the number of bytes in the
669 * input string that were successfully converted, or %NULL.
670 * Even if the conversion was successful, this may be
671 * less than @len if there were partial characters
672 * at the end of the input. If the error
673 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
674 * stored will the byte offset after the last valid
676 * @bytes_written: the number of bytes stored in the output buffer (not
677 * including the terminating nul).
678 * @error: location to store the error occuring, or %NULL to ignore
679 * errors. Any of the errors in #GConvertError may occur.
681 * Converts a string from one character set to another.
683 * Note that you should use g_iconv() for streaming
684 * conversions<footnote id="streaming-state">
686 * Despite the fact that @byes_read can return information about partial
687 * characters, the <literal>g_convert_...</literal> functions
688 * are not generally suitable for streaming. If the underlying converter
689 * being used maintains internal state, then this won't be preserved
690 * across successive calls to g_convert(), g_convert_with_iconv() or
691 * g_convert_with_fallback(). (An example of this is the GNU C converter
692 * for CP1255 which does not emit a base character until it knows that
693 * the next character is not a mark that could combine with the base
698 * Return value: If the conversion was successful, a newly allocated
699 * nul-terminated string, which must be freed with
700 * g_free(). Otherwise %NULL and @error will be set.
703 g_convert_with_iconv (const gchar *str,
707 gsize *bytes_written,
713 gsize inbytes_remaining;
714 gsize outbytes_remaining;
717 gboolean have_error = FALSE;
718 gboolean done = FALSE;
719 gboolean reset = FALSE;
721 g_return_val_if_fail (converter != (GIConv) -1, NULL);
727 inbytes_remaining = len;
728 outbuf_size = len + NUL_TERMINATOR_LENGTH;
730 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
731 outp = dest = g_malloc (outbuf_size);
733 while (!done && !have_error)
736 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
738 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
740 if (err == (gsize) -1)
745 /* Incomplete text, do not report an error */
750 gsize used = outp - dest;
753 dest = g_realloc (dest, outbuf_size);
756 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
761 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
762 _("Invalid byte sequence in conversion input"));
769 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
770 _("Error during conversion: %s"),
781 /* call g_iconv with NULL inbuf to cleanup shift state */
783 inbytes_remaining = 0;
790 memset (outp, 0, NUL_TERMINATOR_LENGTH);
793 *bytes_read = p - str;
796 if ((p - str) != len)
801 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
802 _("Partial character sequence at end of input"));
809 *bytes_written = outp - dest; /* Doesn't include '\0' */
822 * @str: the string to convert
823 * @len: the length of the string, or -1 if the string is
824 * nul-terminated<footnote id="nul-unsafe">
826 Note that some encodings may allow nul bytes to
827 occur inside strings. In that case, using -1 for
828 the @len parameter is unsafe.
831 * @to_codeset: name of character set into which to convert @str
832 * @from_codeset: character set of @str.
833 * @bytes_read: location to store the number of bytes in the
834 * input string that were successfully converted, or %NULL.
835 * Even if the conversion was successful, this may be
836 * less than @len if there were partial characters
837 * at the end of the input. If the error
838 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
839 * stored will the byte offset after the last valid
841 * @bytes_written: the number of bytes stored in the output buffer (not
842 * including the terminating nul).
843 * @error: location to store the error occuring, or %NULL to ignore
844 * errors. Any of the errors in #GConvertError may occur.
846 * Converts a string from one character set to another.
848 * Note that you should use g_iconv() for streaming
849 * conversions<footnoteref linkend="streaming-state"/>.
851 * Return value: If the conversion was successful, a newly allocated
852 * nul-terminated string, which must be freed with
853 * g_free(). Otherwise %NULL and @error will be set.
856 g_convert (const gchar *str,
858 const gchar *to_codeset,
859 const gchar *from_codeset,
861 gsize *bytes_written,
867 g_return_val_if_fail (str != NULL, NULL);
868 g_return_val_if_fail (to_codeset != NULL, NULL);
869 g_return_val_if_fail (from_codeset != NULL, NULL);
871 cd = open_converter (to_codeset, from_codeset, error);
873 if (cd == (GIConv) -1)
884 res = g_convert_with_iconv (str, len, cd,
885 bytes_read, bytes_written,
888 close_converter (cd);
894 * g_convert_with_fallback:
895 * @str: the string to convert
896 * @len: the length of the string, or -1 if the string is
897 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
898 * @to_codeset: name of character set into which to convert @str
899 * @from_codeset: character set of @str.
900 * @fallback: UTF-8 string to use in place of character not
901 * present in the target encoding. (The string must be
902 * representable in the target encoding).
903 If %NULL, characters not in the target encoding will
904 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
905 * @bytes_read: location to store the number of bytes in the
906 * input string that were successfully converted, or %NULL.
907 * Even if the conversion was successful, this may be
908 * less than @len if there were partial characters
909 * at the end of the input.
910 * @bytes_written: the number of bytes stored in the output buffer (not
911 * including the terminating nul).
912 * @error: location to store the error occuring, or %NULL to ignore
913 * errors. Any of the errors in #GConvertError may occur.
915 * Converts a string from one character set to another, possibly
916 * including fallback sequences for characters not representable
917 * in the output. Note that it is not guaranteed that the specification
918 * for the fallback sequences in @fallback will be honored. Some
919 * systems may do an approximate conversion from @from_codeset
920 * to @to_codeset in their iconv() functions,
921 * in which case GLib will simply return that approximate conversion.
923 * Note that you should use g_iconv() for streaming
924 * conversions<footnoteref linkend="streaming-state"/>.
926 * Return value: If the conversion was successful, a newly allocated
927 * nul-terminated string, which must be freed with
928 * g_free(). Otherwise %NULL and @error will be set.
931 g_convert_with_fallback (const gchar *str,
933 const gchar *to_codeset,
934 const gchar *from_codeset,
935 const gchar *fallback,
937 gsize *bytes_written,
943 const gchar *insert_str = NULL;
945 gsize inbytes_remaining;
946 const gchar *save_p = NULL;
947 gsize save_inbytes = 0;
948 gsize outbytes_remaining;
952 gboolean have_error = FALSE;
953 gboolean done = FALSE;
955 GError *local_error = NULL;
957 g_return_val_if_fail (str != NULL, NULL);
958 g_return_val_if_fail (to_codeset != NULL, NULL);
959 g_return_val_if_fail (from_codeset != NULL, NULL);
964 /* Try an exact conversion; we only proceed if this fails
965 * due to an illegal sequence in the input string.
967 dest = g_convert (str, len, to_codeset, from_codeset,
968 bytes_read, bytes_written, &local_error);
972 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
974 g_propagate_error (error, local_error);
978 g_error_free (local_error);
982 /* No go; to proceed, we need a converter from "UTF-8" to
983 * to_codeset, and the string as UTF-8.
985 cd = open_converter (to_codeset, "UTF-8", error);
986 if (cd == (GIConv) -1)
997 utf8 = g_convert (str, len, "UTF-8", from_codeset,
998 bytes_read, &inbytes_remaining, error);
1001 close_converter (cd);
1007 /* Now the heart of the code. We loop through the UTF-8 string, and
1008 * whenever we hit an offending character, we form fallback, convert
1009 * the fallback to the target codeset, and then go back to
1010 * converting the original string after finishing with the fallback.
1012 * The variables save_p and save_inbytes store the input state
1013 * for the original string while we are converting the fallback
1017 outbuf_size = len + NUL_TERMINATOR_LENGTH;
1018 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
1019 outp = dest = g_malloc (outbuf_size);
1021 while (!done && !have_error)
1023 gsize inbytes_tmp = inbytes_remaining;
1024 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
1025 inbytes_remaining = inbytes_tmp;
1027 if (err == (gsize) -1)
1032 g_assert_not_reached();
1036 gsize used = outp - dest;
1039 dest = g_realloc (dest, outbuf_size);
1042 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
1049 /* Error converting fallback string - fatal
1051 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1052 _("Cannot convert fallback '%s' to codeset '%s'"),
1053 insert_str, to_codeset);
1061 gunichar ch = g_utf8_get_char (p);
1062 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
1066 insert_str = fallback;
1068 save_p = g_utf8_next_char (p);
1069 save_inbytes = inbytes_remaining - (save_p - p);
1071 inbytes_remaining = strlen (p);
1074 /* fall thru if p is NULL */
1079 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1080 _("Error during conversion: %s"),
1081 g_strerror (errsv));
1093 g_free ((gchar *)insert_str);
1095 inbytes_remaining = save_inbytes;
1100 /* call g_iconv with NULL inbuf to cleanup shift state */
1102 inbytes_remaining = 0;
1111 memset (outp, 0, NUL_TERMINATOR_LENGTH);
1113 close_converter (cd);
1116 *bytes_written = outp - dest; /* Doesn't include '\0' */
1122 if (save_p && !fallback)
1123 g_free ((gchar *)insert_str);
1138 strdup_len (const gchar *string,
1140 gsize *bytes_written,
1147 if (!g_utf8_validate (string, len, NULL))
1154 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1155 _("Invalid byte sequence in conversion input"));
1160 real_len = strlen (string);
1165 while (real_len < len && string[real_len])
1170 *bytes_read = real_len;
1172 *bytes_written = real_len;
1174 return g_strndup (string, real_len);
1179 * @opsysstring: a string in the encoding of the current locale. On Windows
1180 * this means the system codepage.
1181 * @len: the length of the string, or -1 if the string is
1182 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1183 * @bytes_read: location to store the number of bytes in the
1184 * input string that were successfully converted, or %NULL.
1185 * Even if the conversion was successful, this may be
1186 * less than @len if there were partial characters
1187 * at the end of the input. If the error
1188 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1189 * stored will the byte offset after the last valid
1191 * @bytes_written: the number of bytes stored in the output buffer (not
1192 * including the terminating nul).
1193 * @error: location to store the error occuring, or %NULL to ignore
1194 * errors. Any of the errors in #GConvertError may occur.
1196 * Converts a string which is in the encoding used for strings by
1197 * the C runtime (usually the same as that used by the operating
1198 * system) in the <link linkend="setlocale">current locale</link> into a
1201 * Return value: The converted string, or %NULL on an error.
1204 g_locale_to_utf8 (const gchar *opsysstring,
1207 gsize *bytes_written,
1210 const char *charset;
1212 if (g_get_charset (&charset))
1213 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1215 return g_convert (opsysstring, len,
1216 "UTF-8", charset, bytes_read, bytes_written, error);
1220 * g_locale_from_utf8:
1221 * @utf8string: a UTF-8 encoded string
1222 * @len: the length of the string, or -1 if the string is
1223 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1224 * @bytes_read: location to store the number of bytes in the
1225 * input string that were successfully converted, or %NULL.
1226 * Even if the conversion was successful, this may be
1227 * less than @len if there were partial characters
1228 * at the end of the input. If the error
1229 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1230 * stored will the byte offset after the last valid
1232 * @bytes_written: the number of bytes stored in the output buffer (not
1233 * including the terminating nul).
1234 * @error: location to store the error occuring, or %NULL to ignore
1235 * errors. Any of the errors in #GConvertError may occur.
1237 * Converts a string from UTF-8 to the encoding used for strings by
1238 * the C runtime (usually the same as that used by the operating
1239 * system) in the <link linkend="setlocale">current locale</link>. On
1240 * Windows this means the system codepage.
1242 * Return value: The converted string, or %NULL on an error.
1245 g_locale_from_utf8 (const gchar *utf8string,
1248 gsize *bytes_written,
1251 const gchar *charset;
1253 if (g_get_charset (&charset))
1254 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1256 return g_convert (utf8string, len,
1257 charset, "UTF-8", bytes_read, bytes_written, error);
1260 #ifndef G_PLATFORM_WIN32
1262 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1264 struct _GFilenameCharsetCache {
1267 gchar **filename_charsets;
1271 filename_charset_cache_free (gpointer data)
1273 GFilenameCharsetCache *cache = data;
1274 g_free (cache->charset);
1275 g_strfreev (cache->filename_charsets);
1280 * g_get_filename_charsets:
1281 * @charsets: return location for the %NULL-terminated list of encoding names
1283 * Determines the preferred character sets used for filenames.
1284 * The first character set from the @charsets is the filename encoding, the
1285 * subsequent character sets are used when trying to generate a displayable
1286 * representation of a filename, see g_filename_display_name().
1288 * On Unix, the character sets are determined by consulting the
1289 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1290 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1291 * used in the GLib API is always UTF-8 and said environment variables
1294 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1295 * of character set names. The special token "@locale" is taken to
1296 * mean the character set for the <link linkend="setlocale">current
1297 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1298 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1299 * locale is taken as the filename encoding. If neither environment variable
1300 * is set, UTF-8 is taken as the filename encoding, but the character
1301 * set of the current locale is also put in the list of encodings.
1303 * The returned @charsets belong to GLib and must not be freed.
1305 * Note that on Unix, regardless of the locale character set or
1306 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1307 * on a system might be in any random encoding or just gibberish.
1309 * Return value: %TRUE if the filename encoding is UTF-8.
1314 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1316 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1317 GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1318 const gchar *charset;
1322 cache = g_new0 (GFilenameCharsetCache, 1);
1323 g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1326 g_get_charset (&charset);
1328 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1330 const gchar *new_charset;
1334 g_free (cache->charset);
1335 g_strfreev (cache->filename_charsets);
1336 cache->charset = g_strdup (charset);
1338 p = getenv ("G_FILENAME_ENCODING");
1339 if (p != NULL && p[0] != '\0')
1341 cache->filename_charsets = g_strsplit (p, ",", 0);
1342 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1344 for (i = 0; cache->filename_charsets[i]; i++)
1346 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1348 g_get_charset (&new_charset);
1349 g_free (cache->filename_charsets[i]);
1350 cache->filename_charsets[i] = g_strdup (new_charset);
1354 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1356 cache->filename_charsets = g_new0 (gchar *, 2);
1357 cache->is_utf8 = g_get_charset (&new_charset);
1358 cache->filename_charsets[0] = g_strdup (new_charset);
1362 cache->filename_charsets = g_new0 (gchar *, 3);
1363 cache->is_utf8 = TRUE;
1364 cache->filename_charsets[0] = g_strdup ("UTF-8");
1365 if (!g_get_charset (&new_charset))
1366 cache->filename_charsets[1] = g_strdup (new_charset);
1370 if (filename_charsets)
1371 *filename_charsets = (const gchar **)cache->filename_charsets;
1373 return cache->is_utf8;
1376 #else /* G_PLATFORM_WIN32 */
1379 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1381 static const gchar *charsets[] = {
1387 /* On Windows GLib pretends that the filename charset is UTF-8 */
1388 if (filename_charsets)
1389 *filename_charsets = charsets;
1395 /* Cygwin works like before */
1396 result = g_get_charset (&(charsets[0]));
1398 if (filename_charsets)
1399 *filename_charsets = charsets;
1405 #endif /* G_PLATFORM_WIN32 */
1408 get_filename_charset (const gchar **filename_charset)
1410 const gchar **charsets;
1413 is_utf8 = g_get_filename_charsets (&charsets);
1415 if (filename_charset)
1416 *filename_charset = charsets[0];
1421 /* This is called from g_thread_init(). It's used to
1422 * initialize some static data in a threadsafe way.
1425 _g_convert_thread_init (void)
1427 const gchar **dummy;
1428 (void) g_get_filename_charsets (&dummy);
1432 * g_filename_to_utf8:
1433 * @opsysstring: a string in the encoding for filenames
1434 * @len: the length of the string, or -1 if the string is
1435 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1436 * @bytes_read: location to store the number of bytes in the
1437 * input string that were successfully converted, or %NULL.
1438 * Even if the conversion was successful, this may be
1439 * less than @len if there were partial characters
1440 * at the end of the input. If the error
1441 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1442 * stored will the byte offset after the last valid
1444 * @bytes_written: the number of bytes stored in the output buffer (not
1445 * including the terminating nul).
1446 * @error: location to store the error occuring, or %NULL to ignore
1447 * errors. Any of the errors in #GConvertError may occur.
1449 * Converts a string which is in the encoding used by GLib for
1450 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1451 * for filenames; on other platforms, this function indirectly depends on
1452 * the <link linkend="setlocale">current locale</link>.
1454 * Return value: The converted string, or %NULL on an error.
1457 g_filename_to_utf8 (const gchar *opsysstring,
1460 gsize *bytes_written,
1463 const gchar *charset;
1465 if (get_filename_charset (&charset))
1466 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1468 return g_convert (opsysstring, len,
1469 "UTF-8", charset, bytes_read, bytes_written, error);
1472 #if defined (G_OS_WIN32) && !defined (_WIN64)
1474 #undef g_filename_to_utf8
1476 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1477 * 64-bit versions as there should be no old deployed binaries that would use
1482 g_filename_to_utf8 (const gchar *opsysstring,
1485 gsize *bytes_written,
1488 const gchar *charset;
1490 if (g_get_charset (&charset))
1491 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1493 return g_convert (opsysstring, len,
1494 "UTF-8", charset, bytes_read, bytes_written, error);
1500 * g_filename_from_utf8:
1501 * @utf8string: a UTF-8 encoded string.
1502 * @len: the length of the string, or -1 if the string is
1504 * @bytes_read: location to store the number of bytes in the
1505 * input string that were successfully converted, or %NULL.
1506 * Even if the conversion was successful, this may be
1507 * less than @len if there were partial characters
1508 * at the end of the input. If the error
1509 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1510 * stored will the byte offset after the last valid
1512 * @bytes_written: the number of bytes stored in the output buffer (not
1513 * including the terminating nul).
1514 * @error: location to store the error occuring, or %NULL to ignore
1515 * errors. Any of the errors in #GConvertError may occur.
1517 * Converts a string from UTF-8 to the encoding GLib uses for
1518 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1519 * on other platforms, this function indirectly depends on the
1520 * <link linkend="setlocale">current locale</link>.
1522 * Return value: The converted string, or %NULL on an error.
1525 g_filename_from_utf8 (const gchar *utf8string,
1528 gsize *bytes_written,
1531 const gchar *charset;
1533 if (get_filename_charset (&charset))
1534 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1536 return g_convert (utf8string, len,
1537 charset, "UTF-8", bytes_read, bytes_written, error);
1540 #if defined (G_OS_WIN32) && !defined (_WIN64)
1542 #undef g_filename_from_utf8
1544 /* Binary compatibility version. Not for newly compiled code. */
1547 g_filename_from_utf8 (const gchar *utf8string,
1550 gsize *bytes_written,
1553 const gchar *charset;
1555 if (g_get_charset (&charset))
1556 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1558 return g_convert (utf8string, len,
1559 charset, "UTF-8", bytes_read, bytes_written, error);
1564 /* Test of haystack has the needle prefix, comparing case
1565 * insensitive. haystack may be UTF-8, but needle must
1566 * contain only ascii. */
1568 has_case_prefix (const gchar *haystack, const gchar *needle)
1572 /* Eat one character at a time. */
1577 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1587 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1588 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1589 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1590 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1591 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1592 } UnsafeCharacterSet;
1594 static const guchar acceptable[96] = {
1595 /* A table of the ASCII chars from space (32) to DEL (127) */
1596 /* ! " # $ % & ' ( ) * + , - . / */
1597 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1598 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1599 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1600 /* @ A B C D E F G H I J K L M N O */
1601 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1602 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1603 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1604 /* ` a b c d e f g h i j k l m n o */
1605 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1606 /* p q r s t u v w x y z { | } ~ DEL */
1607 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1610 static const gchar hex[16] = "0123456789ABCDEF";
1612 /* Note: This escape function works on file: URIs, but if you want to
1613 * escape something else, please read RFC-2396 */
1615 g_escape_uri_string (const gchar *string,
1616 UnsafeCharacterSet mask)
1618 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1625 UnsafeCharacterSet use_mask;
1627 g_return_val_if_fail (mask == UNSAFE_ALL
1628 || mask == UNSAFE_ALLOW_PLUS
1629 || mask == UNSAFE_PATH
1630 || mask == UNSAFE_HOST
1631 || mask == UNSAFE_SLASHES, NULL);
1635 for (p = string; *p != '\0'; p++)
1638 if (!ACCEPTABLE (c))
1642 result = g_malloc (p - string + unacceptable * 2 + 1);
1645 for (q = result, p = string; *p != '\0'; p++)
1649 if (!ACCEPTABLE (c))
1651 *q++ = '%'; /* means hex coming */
1666 g_escape_file_uri (const gchar *hostname,
1667 const gchar *pathname)
1669 char *escaped_hostname = NULL;
1674 char *p, *backslash;
1676 /* Turn backslashes into forward slashes. That's what Netscape
1677 * does, and they are actually more or less equivalent in Windows.
1680 pathname = g_strdup (pathname);
1681 p = (char *) pathname;
1683 while ((backslash = strchr (p, '\\')) != NULL)
1690 if (hostname && *hostname != '\0')
1692 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1695 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1697 res = g_strconcat ("file://",
1698 (escaped_hostname) ? escaped_hostname : "",
1699 (*escaped_path != '/') ? "/" : "",
1704 g_free ((char *) pathname);
1707 g_free (escaped_hostname);
1708 g_free (escaped_path);
1714 unescape_character (const char *scanner)
1719 first_digit = g_ascii_xdigit_value (scanner[0]);
1720 if (first_digit < 0)
1723 second_digit = g_ascii_xdigit_value (scanner[1]);
1724 if (second_digit < 0)
1727 return (first_digit << 4) | second_digit;
1731 g_unescape_uri_string (const char *escaped,
1733 const char *illegal_escaped_characters,
1734 gboolean ascii_must_not_be_escaped)
1736 const gchar *in, *in_end;
1737 gchar *out, *result;
1740 if (escaped == NULL)
1744 len = strlen (escaped);
1746 result = g_malloc (len + 1);
1749 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1755 /* catch partial escape sequences past the end of the substring */
1756 if (in + 3 > in_end)
1759 c = unescape_character (in + 1);
1761 /* catch bad escape sequences and NUL characters */
1765 /* catch escaped ASCII */
1766 if (ascii_must_not_be_escaped && c <= 0x7F)
1769 /* catch other illegal escaped characters */
1770 if (strchr (illegal_escaped_characters, c) != NULL)
1779 g_assert (out - result <= len);
1792 is_asciialphanum (gunichar c)
1794 return c <= 0x7F && g_ascii_isalnum (c);
1798 is_asciialpha (gunichar c)
1800 return c <= 0x7F && g_ascii_isalpha (c);
1803 /* allows an empty string */
1805 hostname_validate (const char *hostname)
1808 gunichar c, first_char, last_char;
1815 /* read in a label */
1816 c = g_utf8_get_char (p);
1817 p = g_utf8_next_char (p);
1818 if (!is_asciialphanum (c))
1824 c = g_utf8_get_char (p);
1825 p = g_utf8_next_char (p);
1827 while (is_asciialphanum (c) || c == '-');
1828 if (last_char == '-')
1831 /* if that was the last label, check that it was a toplabel */
1832 if (c == '\0' || (c == '.' && *p == '\0'))
1833 return is_asciialpha (first_char);
1840 * g_filename_from_uri:
1841 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1842 * @hostname: Location to store hostname for the URI, or %NULL.
1843 * If there is no hostname in the URI, %NULL will be
1844 * stored in this location.
1845 * @error: location to store the error occuring, or %NULL to ignore
1846 * errors. Any of the errors in #GConvertError may occur.
1848 * Converts an escaped ASCII-encoded URI to a local filename in the
1849 * encoding used for filenames.
1851 * Return value: a newly-allocated string holding the resulting
1852 * filename, or %NULL on an error.
1855 g_filename_from_uri (const gchar *uri,
1859 const char *path_part;
1860 const char *host_part;
1861 char *unescaped_hostname;
1872 if (!has_case_prefix (uri, "file:/"))
1874 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1875 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1880 path_part = uri + strlen ("file:");
1882 if (strchr (path_part, '#') != NULL)
1884 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1885 _("The local file URI '%s' may not include a '#'"),
1890 if (has_case_prefix (path_part, "///"))
1892 else if (has_case_prefix (path_part, "//"))
1895 host_part = path_part;
1897 path_part = strchr (path_part, '/');
1899 if (path_part == NULL)
1901 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1902 _("The URI '%s' is invalid"),
1907 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1909 if (unescaped_hostname == NULL ||
1910 !hostname_validate (unescaped_hostname))
1912 g_free (unescaped_hostname);
1913 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1914 _("The hostname of the URI '%s' is invalid"),
1920 *hostname = unescaped_hostname;
1922 g_free (unescaped_hostname);
1925 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1927 if (filename == NULL)
1929 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1930 _("The URI '%s' contains invalidly escaped characters"),
1937 /* Drop localhost */
1938 if (hostname && *hostname != NULL &&
1939 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1945 /* Turn slashes into backslashes, because that's the canonical spelling */
1947 while ((slash = strchr (p, '/')) != NULL)
1953 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1954 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1955 * the filename from the drive letter.
1957 if (g_ascii_isalpha (filename[1]))
1959 if (filename[2] == ':')
1961 else if (filename[2] == '|')
1969 result = g_strdup (filename + offs);
1975 #if defined (G_OS_WIN32) && !defined (_WIN64)
1977 #undef g_filename_from_uri
1980 g_filename_from_uri (const gchar *uri,
1984 gchar *utf8_filename;
1985 gchar *retval = NULL;
1987 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1990 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1991 g_free (utf8_filename);
1999 * g_filename_to_uri:
2000 * @filename: an absolute filename specified in the GLib file name encoding,
2001 * which is the on-disk file name bytes on Unix, and UTF-8 on
2003 * @hostname: A UTF-8 encoded hostname, or %NULL for none.
2004 * @error: location to store the error occuring, or %NULL to ignore
2005 * errors. Any of the errors in #GConvertError may occur.
2007 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
2008 * component following Section 3.3. of RFC 2396.
2010 * Return value: a newly-allocated string holding the resulting
2011 * URI, or %NULL on an error.
2014 g_filename_to_uri (const gchar *filename,
2015 const gchar *hostname,
2020 g_return_val_if_fail (filename != NULL, NULL);
2022 if (!g_path_is_absolute (filename))
2024 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
2025 _("The pathname '%s' is not an absolute path"),
2031 !(g_utf8_validate (hostname, -1, NULL)
2032 && hostname_validate (hostname)))
2034 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2035 _("Invalid hostname"));
2040 /* Don't use localhost unnecessarily */
2041 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
2045 escaped_uri = g_escape_file_uri (hostname, filename);
2050 #if defined (G_OS_WIN32) && !defined (_WIN64)
2052 #undef g_filename_to_uri
2055 g_filename_to_uri (const gchar *filename,
2056 const gchar *hostname,
2059 gchar *utf8_filename;
2060 gchar *retval = NULL;
2062 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2066 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
2067 g_free (utf8_filename);
2076 * g_uri_list_extract_uris:
2077 * @uri_list: an URI list
2079 * Splits an URI list conforming to the text/uri-list
2080 * mime type defined in RFC 2483 into individual URIs,
2081 * discarding any comments. The URIs are not validated.
2083 * Returns: a newly allocated %NULL-terminated list of
2084 * strings holding the individual URIs. The array should
2085 * be freed with g_strfreev().
2090 g_uri_list_extract_uris (const gchar *uri_list)
2101 /* We don't actually try to validate the URI according to RFC
2102 * 2396, or even check for allowed characters - we just ignore
2103 * comments and trim whitespace off the ends. We also
2104 * allow LF delimination as well as the specified CRLF.
2106 * We do allow comments like specified in RFC 2483.
2112 while (g_ascii_isspace (*p))
2116 while (*q && (*q != '\n') && (*q != '\r'))
2122 while (q > p && g_ascii_isspace (*q))
2127 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2132 p = strchr (p, '\n');
2137 result = g_new (gchar *, n_uris + 1);
2139 result[n_uris--] = NULL;
2140 for (u = uris; u; u = u->next)
2141 result[n_uris--] = u->data;
2143 g_slist_free (uris);
2149 * g_filename_display_basename:
2150 * @filename: an absolute pathname in the GLib file name encoding
2152 * Returns the display basename for the particular filename, guaranteed
2153 * to be valid UTF-8. The display name might not be identical to the filename,
2154 * for instance there might be problems converting it to UTF-8, and some files
2155 * can be translated in the display.
2157 * If GLib can not make sense of the encoding of @filename, as a last resort it
2158 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2159 * You can search the result for the UTF-8 encoding of this character (which is
2160 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2163 * You must pass the whole absolute pathname to this functions so that
2164 * translation of well known locations can be done.
2166 * This function is preferred over g_filename_display_name() if you know the
2167 * whole path, as it allows translation.
2169 * Return value: a newly allocated string containing
2170 * a rendition of the basename of the filename in valid UTF-8
2175 g_filename_display_basename (const gchar *filename)
2180 g_return_val_if_fail (filename != NULL, NULL);
2182 basename = g_path_get_basename (filename);
2183 display_name = g_filename_display_name (basename);
2185 return display_name;
2189 * g_filename_display_name:
2190 * @filename: a pathname hopefully in the GLib file name encoding
2192 * Converts a filename into a valid UTF-8 string. The conversion is
2193 * not necessarily reversible, so you should keep the original around
2194 * and use the return value of this function only for display purposes.
2195 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2196 * even if the filename actually isn't in the GLib file name encoding.
2198 * If GLib can not make sense of the encoding of @filename, as a last resort it
2199 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2200 * You can search the result for the UTF-8 encoding of this character (which is
2201 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2204 * If you know the whole pathname of the file you should use
2205 * g_filename_display_basename(), since that allows location-based
2206 * translation of filenames.
2208 * Return value: a newly allocated string containing
2209 * a rendition of the filename in valid UTF-8
2214 g_filename_display_name (const gchar *filename)
2217 const gchar **charsets;
2218 gchar *display_name = NULL;
2221 is_utf8 = g_get_filename_charsets (&charsets);
2225 if (g_utf8_validate (filename, -1, NULL))
2226 display_name = g_strdup (filename);
2231 /* Try to convert from the filename charsets to UTF-8.
2232 * Skip the first charset if it is UTF-8.
2234 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2236 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
2244 /* if all conversions failed, we replace invalid UTF-8
2245 * by a question mark
2248 display_name = _g_utf8_make_valid (filename);
2250 return display_name;