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 "gcharsetprivate.h"
48 #include "gstrfuncs.h"
49 #include "gtestutils.h"
52 #include "gfileutils.h"
54 #ifdef NEED_ICONV_CACHE
60 #include "gwin32compat.h"
62 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
63 #error GNU libiconv in use but included iconv.h not from libiconv
65 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H) \
66 && !defined (__APPLE_CC__) && !defined (__LP_64__)
67 #error GNU libiconv not in use but included iconv.h is from libiconv
73 * @title: Character Set Conversion
74 * @short_description: convert strings between different character sets
76 * The g_convert() family of function wraps the functionality of iconv(). In
77 * addition to pure character set conversions, GLib has functions to deal
78 * with the extra complications of encodings for file names.
80 * <refsect2 id="file-name-encodings">
81 * <title>File Name Encodings</title>
83 * Historically, Unix has not had a defined encoding for file
84 * names: a file name is valid as long as it does not have path
85 * separators in it ("/"). However, displaying file names may
86 * require conversion: from the character set in which they were
87 * created, to the character set in which the application
88 * operates. Consider the Spanish file name
89 * "<filename>Presentación.sxi</filename>". If the
90 * application which created it uses ISO-8859-1 for its encoding,
92 * <programlisting id="filename-iso8859-1">
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 f3 6e 2e 73 78 69
97 * However, if the application use UTF-8, the actual file name on
98 * disk would look like this:
100 * <programlisting id="filename-utf-8">
101 * Character: P r e s e n t a c i ó n . s x i
102 * Hex code: 50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
105 * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+
106 * that use Glib do the same thing. If you get a file name from
107 * the file system, for example, from readdir(3) or from g_dir_read_name(),
108 * and you wish to display the file name to the user, you
109 * <emphasis>will</emphasis> need to convert it into UTF-8. The
110 * opposite case is when the user types the name of a file he
111 * wishes to save: the toolkit will give you that string in
112 * UTF-8 encoding, and you will need to convert it to the
113 * character set used for file names before you can create the
114 * file with open(2) or fopen(3).
117 * By default, Glib assumes that file names on disk are in UTF-8
118 * encoding. This is a valid assumption for file systems which
119 * were created relatively recently: most applications use UTF-8
120 * encoding for their strings, and that is also what they use for
121 * the file names they create. However, older file systems may
122 * still contain file names created in "older" encodings, such as
123 * ISO-8859-1. In this case, for compatibility reasons, you may
124 * want to instruct Glib to use that particular encoding for file
125 * names rather than UTF-8. You can do this by specifying the
126 * encoding for file names in the <link
127 * linkend="G_FILENAME_ENCODING"><envar>G_FILENAME_ENCODING</envar></link>
128 * environment variable. For example, if your installation uses
129 * ISO-8859-1 for file names, you can put this in your
130 * <filename>~/.profile</filename>:
133 * export G_FILENAME_ENCODING=ISO-8859-1
136 * Glib provides the functions g_filename_to_utf8() and
137 * g_filename_from_utf8() to perform the necessary conversions. These
138 * functions convert file names from the encoding specified in
139 * <envar>G_FILENAME_ENCODING</envar> to UTF-8 and vice-versa.
140 * <xref linkend="file-name-encodings-diagram"/> illustrates how
141 * these functions are used to convert between UTF-8 and the
142 * encoding for file names in the file system.
144 * <figure id="file-name-encodings-diagram">
145 * <title>Conversion between File Name Encodings</title>
146 * <graphic fileref="file-name-encodings.png" format="PNG"/>
148 * <refsect3 id="file-name-encodings-checklist">
149 * <title>Checklist for Application Writers</title>
151 * This section is a practical summary of the detailed
152 * description above. You can use this as a checklist of
153 * things to do to make sure your applications process file
154 * name encodings correctly.
158 * If you get a file name from the file system from a function
159 * such as readdir(3) or gtk_file_chooser_get_filename(),
160 * you do not need to do any conversion to pass that
161 * file name to functions like open(2), rename(2), or
162 * fopen(3) — those are "raw" file names which the file
163 * system understands.
166 * If you need to display a file name, convert it to UTF-8 first by
167 * using g_filename_to_utf8(). If conversion fails, display a string like
168 * "<literal>Unknown file name</literal>". <emphasis>Do not</emphasis>
169 * convert this string back into the encoding used for file names if you
170 * wish to pass it to the file system; use the original file name instead.
171 * For example, the document window of a word processor could display
172 * "Unknown file name" in its title bar but still let the user save the
173 * file, as it would keep the raw file name internally. This can happen
174 * if the user has not set the <envar>G_FILENAME_ENCODING</envar>
175 * environment variable even though he has files whose names are not
179 * If your user interface lets the user type a file name for saving or
180 * renaming, convert it to the encoding used for file names in the file
181 * system by using g_filename_from_utf8(). Pass the converted file name
182 * to functions like fopen(3). If conversion fails, ask the user to enter
183 * a different file name. This can happen if the user types Japanese
184 * characters when <envar>G_FILENAME_ENCODING</envar> is set to
185 * <literal>ISO-8859-1</literal>, for example.
192 /* We try to terminate strings in unknown charsets with this many zero bytes
193 * to ensure that multibyte strings really are nul-terminated when we return
194 * them from g_convert() and friends.
196 #define NUL_TERMINATOR_LENGTH 4
198 G_DEFINE_QUARK (g_convert_error, g_convert_error)
201 try_conversion (const char *to_codeset,
202 const char *from_codeset,
205 *cd = iconv_open (to_codeset, from_codeset);
207 if (*cd == (iconv_t)-1 && errno == EINVAL)
214 try_to_aliases (const char **to_aliases,
215 const char *from_codeset,
220 const char **p = to_aliases;
223 if (try_conversion (*p, from_codeset, cd))
233 G_GNUC_INTERNAL extern const char **
234 _g_charset_get_aliases (const char *canonical_name);
238 * @to_codeset: destination codeset
239 * @from_codeset: source codeset
241 * Same as the standard UNIX routine iconv_open(), but
242 * may be implemented via libiconv on UNIX flavors that lack
243 * a native implementation.
245 * GLib provides g_convert() and g_locale_to_utf8() which are likely
246 * more convenient than the raw iconv wrappers.
248 * Return value: a "conversion descriptor", or (GIConv)-1 if
249 * opening the converter failed.
252 g_iconv_open (const gchar *to_codeset,
253 const gchar *from_codeset)
257 if (!try_conversion (to_codeset, from_codeset, &cd))
259 const char **to_aliases = _g_charset_get_aliases (to_codeset);
260 const char **from_aliases = _g_charset_get_aliases (from_codeset);
264 const char **p = from_aliases;
267 if (try_conversion (to_codeset, *p, &cd))
270 if (try_to_aliases (to_aliases, *p, &cd))
277 if (try_to_aliases (to_aliases, from_codeset, &cd))
282 return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
287 * @converter: conversion descriptor from g_iconv_open()
288 * @inbuf: bytes to convert
289 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
290 * @outbuf: converted output bytes
291 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
293 * Same as the standard UNIX routine iconv(), but
294 * may be implemented via libiconv on UNIX flavors that lack
295 * a native implementation.
297 * GLib provides g_convert() and g_locale_to_utf8() which are likely
298 * more convenient than the raw iconv wrappers.
300 * Return value: count of non-reversible conversions, or -1 on error
303 g_iconv (GIConv converter,
307 gsize *outbytes_left)
309 iconv_t cd = (iconv_t)converter;
311 return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
316 * @converter: a conversion descriptor from g_iconv_open()
318 * Same as the standard UNIX routine iconv_close(), but
319 * may be implemented via libiconv on UNIX flavors that lack
320 * a native implementation. Should be called to clean up
321 * the conversion descriptor from g_iconv_open() when
322 * you are done converting things.
324 * GLib provides g_convert() and g_locale_to_utf8() which are likely
325 * more convenient than the raw iconv wrappers.
327 * Return value: -1 on error, 0 on success
330 g_iconv_close (GIConv converter)
332 iconv_t cd = (iconv_t)converter;
334 return iconv_close (cd);
338 #ifdef NEED_ICONV_CACHE
340 #define ICONV_CACHE_SIZE (16)
342 struct _iconv_cache_bucket {
349 static GList *iconv_cache_list;
350 static GHashTable *iconv_cache;
351 static GHashTable *iconv_open_hash;
352 static guint iconv_cache_size = 0;
353 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
355 /* caller *must* hold the iconv_cache_lock */
357 iconv_cache_init (void)
359 static gboolean initialized = FALSE;
364 iconv_cache_list = NULL;
365 iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
366 iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
373 * iconv_cache_bucket_new:
375 * @cd: iconv descriptor
377 * Creates a new cache bucket, inserts it into the cache and
378 * increments the cache size.
380 * This assumes ownership of @key.
382 * Returns a pointer to the newly allocated cache bucket.
384 static struct _iconv_cache_bucket *
385 iconv_cache_bucket_new (gchar *key, GIConv cd)
387 struct _iconv_cache_bucket *bucket;
389 bucket = g_new (struct _iconv_cache_bucket, 1);
391 bucket->refcount = 1;
395 g_hash_table_insert (iconv_cache, bucket->key, bucket);
397 /* FIXME: if we sorted the list so items with few refcounts were
398 first, then we could expire them faster in iconv_cache_expire_unused () */
399 iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
408 * iconv_cache_bucket_expire:
409 * @node: cache bucket's node
410 * @bucket: cache bucket
412 * Expires a single cache bucket @bucket. This should only ever be
413 * called on a bucket that currently has no used iconv descriptors
416 * @node is not a required argument. If @node is not supplied, we
417 * search for it ourselves.
420 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
422 g_hash_table_remove (iconv_cache, bucket->key);
425 node = g_list_find (iconv_cache_list, bucket);
427 g_assert (node != NULL);
431 node->prev->next = node->next;
433 node->next->prev = node->prev;
437 iconv_cache_list = node->next;
439 node->next->prev = NULL;
442 g_list_free_1 (node);
444 g_free (bucket->key);
445 g_iconv_close (bucket->cd);
453 * iconv_cache_expire_unused:
455 * Expires as many unused cache buckets as it needs to in order to get
456 * the total number of buckets < ICONV_CACHE_SIZE.
459 iconv_cache_expire_unused (void)
461 struct _iconv_cache_bucket *bucket;
464 node = iconv_cache_list;
465 while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
470 if (bucket->refcount == 0)
471 iconv_cache_bucket_expire (node, bucket);
478 open_converter (const gchar *to_codeset,
479 const gchar *from_codeset,
482 struct _iconv_cache_bucket *bucket;
483 gchar *key, *dyn_key, auto_key[80];
485 gsize len_from_codeset, len_to_codeset;
488 len_from_codeset = strlen (from_codeset);
489 len_to_codeset = strlen (to_codeset);
490 if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
496 key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
497 memcpy (key, from_codeset, len_from_codeset);
498 key[len_from_codeset] = ':';
499 strcpy (key + len_from_codeset + 1, to_codeset);
501 G_LOCK (iconv_cache_lock);
503 /* make sure the cache has been initialized */
506 bucket = g_hash_table_lookup (iconv_cache, key);
513 cd = g_iconv_open (to_codeset, from_codeset);
514 if (cd == (GIConv) -1)
519 /* Apparently iconv on Solaris <= 7 segfaults if you pass in
520 * NULL for anything but inbuf; work around that. (NULL outbuf
521 * or NULL *outbuf is allowed by Unix98.)
523 gsize inbytes_left = 0;
524 gchar *outbuf = NULL;
525 gsize outbytes_left = 0;
530 /* reset the descriptor */
531 g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
538 cd = g_iconv_open (to_codeset, from_codeset);
539 if (cd == (GIConv) -1)
545 iconv_cache_expire_unused ();
547 bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
550 g_hash_table_insert (iconv_open_hash, cd, bucket->key);
552 G_UNLOCK (iconv_cache_lock);
558 G_UNLOCK (iconv_cache_lock);
560 /* Something went wrong. */
564 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
565 _("Conversion from character set '%s' to '%s' is not supported"),
566 from_codeset, to_codeset);
568 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
569 _("Could not open converter from '%s' to '%s'"),
570 from_codeset, to_codeset);
577 close_converter (GIConv converter)
579 struct _iconv_cache_bucket *bucket;
585 if (cd == (GIConv) -1)
588 G_LOCK (iconv_cache_lock);
590 key = g_hash_table_lookup (iconv_open_hash, cd);
593 g_hash_table_remove (iconv_open_hash, cd);
595 bucket = g_hash_table_lookup (iconv_cache, key);
600 if (cd == bucket->cd)
601 bucket->used = FALSE;
605 if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
607 /* expire this cache bucket */
608 iconv_cache_bucket_expire (NULL, bucket);
613 G_UNLOCK (iconv_cache_lock);
615 g_warning ("This iconv context wasn't opened using open_converter");
617 return g_iconv_close (converter);
620 G_UNLOCK (iconv_cache_lock);
625 #else /* !NEED_ICONV_CACHE */
628 open_converter (const gchar *to_codeset,
629 const gchar *from_codeset,
634 cd = g_iconv_open (to_codeset, from_codeset);
636 if (cd == (GIConv) -1)
638 /* Something went wrong. */
642 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
643 _("Conversion from character set '%s' to '%s' is not supported"),
644 from_codeset, to_codeset);
646 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
647 _("Could not open converter from '%s' to '%s'"),
648 from_codeset, to_codeset);
656 close_converter (GIConv cd)
658 if (cd == (GIConv) -1)
661 return g_iconv_close (cd);
664 #endif /* NEED_ICONV_CACHE */
667 * g_convert_with_iconv:
668 * @str: the string to convert
669 * @len: the length of the string, or -1 if the string is
670 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
671 * @converter: conversion descriptor from g_iconv_open()
672 * @bytes_read: location to store the number of bytes in the
673 * input string that were successfully converted, or %NULL.
674 * Even if the conversion was successful, this may be
675 * less than @len if there were partial characters
676 * at the end of the input. If the error
677 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
678 * stored will the byte offset after the last valid
680 * @bytes_written: the number of bytes stored in the output buffer (not
681 * including the terminating nul).
682 * @error: location to store the error occurring, or %NULL to ignore
683 * errors. Any of the errors in #GConvertError may occur.
685 * Converts a string from one character set to another.
687 * Note that you should use g_iconv() for streaming
688 * conversions<footnote id="streaming-state">
690 * Despite the fact that @byes_read can return information about partial
691 * characters, the <literal>g_convert_...</literal> functions
692 * are not generally suitable for streaming. If the underlying converter
693 * being used maintains internal state, then this won't be preserved
694 * across successive calls to g_convert(), g_convert_with_iconv() or
695 * g_convert_with_fallback(). (An example of this is the GNU C converter
696 * for CP1255 which does not emit a base character until it knows that
697 * the next character is not a mark that could combine with the base
702 * Return value: If the conversion was successful, a newly allocated
703 * nul-terminated string, which must be freed with
704 * g_free(). Otherwise %NULL and @error will be set.
707 g_convert_with_iconv (const gchar *str,
711 gsize *bytes_written,
717 gsize inbytes_remaining;
718 gsize outbytes_remaining;
721 gboolean have_error = FALSE;
722 gboolean done = FALSE;
723 gboolean reset = FALSE;
725 g_return_val_if_fail (converter != (GIConv) -1, NULL);
731 inbytes_remaining = len;
732 outbuf_size = len + NUL_TERMINATOR_LENGTH;
734 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
735 outp = dest = g_malloc (outbuf_size);
737 while (!done && !have_error)
740 err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
742 err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
744 if (err == (gsize) -1)
749 /* Incomplete text, do not report an error */
754 gsize used = outp - dest;
757 dest = g_realloc (dest, outbuf_size);
760 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
764 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
765 _("Invalid byte sequence in conversion input"));
772 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
773 _("Error during conversion: %s"),
784 /* call g_iconv with NULL inbuf to cleanup shift state */
786 inbytes_remaining = 0;
793 memset (outp, 0, NUL_TERMINATOR_LENGTH);
796 *bytes_read = p - str;
799 if ((p - str) != len)
803 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
804 _("Partial character sequence at end of input"));
811 *bytes_written = outp - dest; /* Doesn't include '\0' */
824 * @str: the string to convert
825 * @len: the length of the string, or -1 if the string is
826 * nul-terminated<footnote id="nul-unsafe">
828 Note that some encodings may allow nul bytes to
829 occur inside strings. In that case, using -1 for
830 the @len parameter is unsafe.
833 * @to_codeset: name of character set into which to convert @str
834 * @from_codeset: character set of @str.
835 * @bytes_read: (out): location to store the number of bytes in the
836 * input string that were successfully converted, or %NULL.
837 * Even if the conversion was successful, this may be
838 * less than @len if there were partial characters
839 * at the end of the input. If the error
840 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
841 * stored will the byte offset after the last valid
843 * @bytes_written: (out): the number of bytes stored in the output buffer (not
844 * including the terminating nul).
845 * @error: location to store the error occurring, or %NULL to ignore
846 * errors. Any of the errors in #GConvertError may occur.
848 * Converts a string from one character set to another.
850 * Note that you should use g_iconv() for streaming
851 * conversions<footnoteref linkend="streaming-state"/>.
853 * Return value: If the conversion was successful, a newly allocated
854 * nul-terminated string, which must be freed with
855 * g_free(). Otherwise %NULL and @error will be set.
858 g_convert (const gchar *str,
860 const gchar *to_codeset,
861 const gchar *from_codeset,
863 gsize *bytes_written,
869 g_return_val_if_fail (str != NULL, NULL);
870 g_return_val_if_fail (to_codeset != NULL, NULL);
871 g_return_val_if_fail (from_codeset != NULL, NULL);
873 cd = open_converter (to_codeset, from_codeset, error);
875 if (cd == (GIConv) -1)
886 res = g_convert_with_iconv (str, len, cd,
887 bytes_read, bytes_written,
890 close_converter (cd);
896 * g_convert_with_fallback:
897 * @str: the string to convert
898 * @len: the length of the string, or -1 if the string is
899 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
900 * @to_codeset: name of character set into which to convert @str
901 * @from_codeset: character set of @str.
902 * @fallback: UTF-8 string to use in place of character not
903 * present in the target encoding. (The string must be
904 * representable in the target encoding).
905 If %NULL, characters not in the target encoding will
906 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
907 * @bytes_read: location to store the number of bytes in the
908 * input string that were successfully converted, or %NULL.
909 * Even if the conversion was successful, this may be
910 * less than @len if there were partial characters
911 * at the end of the input.
912 * @bytes_written: the number of bytes stored in the output buffer (not
913 * including the terminating nul).
914 * @error: location to store the error occurring, or %NULL to ignore
915 * errors. Any of the errors in #GConvertError may occur.
917 * Converts a string from one character set to another, possibly
918 * including fallback sequences for characters not representable
919 * in the output. Note that it is not guaranteed that the specification
920 * for the fallback sequences in @fallback will be honored. Some
921 * systems may do an approximate conversion from @from_codeset
922 * to @to_codeset in their iconv() functions,
923 * in which case GLib will simply return that approximate conversion.
925 * Note that you should use g_iconv() for streaming
926 * conversions<footnoteref linkend="streaming-state"/>.
928 * Return value: If the conversion was successful, a newly allocated
929 * nul-terminated string, which must be freed with
930 * g_free(). Otherwise %NULL and @error will be set.
933 g_convert_with_fallback (const gchar *str,
935 const gchar *to_codeset,
936 const gchar *from_codeset,
937 const gchar *fallback,
939 gsize *bytes_written,
945 const gchar *insert_str = NULL;
947 gsize inbytes_remaining;
948 const gchar *save_p = NULL;
949 gsize save_inbytes = 0;
950 gsize outbytes_remaining;
954 gboolean have_error = FALSE;
955 gboolean done = FALSE;
957 GError *local_error = NULL;
959 g_return_val_if_fail (str != NULL, NULL);
960 g_return_val_if_fail (to_codeset != NULL, NULL);
961 g_return_val_if_fail (from_codeset != NULL, NULL);
966 /* Try an exact conversion; we only proceed if this fails
967 * due to an illegal sequence in the input string.
969 dest = g_convert (str, len, to_codeset, from_codeset,
970 bytes_read, bytes_written, &local_error);
974 if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
976 g_propagate_error (error, local_error);
980 g_error_free (local_error);
984 /* No go; to proceed, we need a converter from "UTF-8" to
985 * to_codeset, and the string as UTF-8.
987 cd = open_converter (to_codeset, "UTF-8", error);
988 if (cd == (GIConv) -1)
999 utf8 = g_convert (str, len, "UTF-8", from_codeset,
1000 bytes_read, &inbytes_remaining, error);
1003 close_converter (cd);
1009 /* Now the heart of the code. We loop through the UTF-8 string, and
1010 * whenever we hit an offending character, we form fallback, convert
1011 * the fallback to the target codeset, and then go back to
1012 * converting the original string after finishing with the fallback.
1014 * The variables save_p and save_inbytes store the input state
1015 * for the original string while we are converting the fallback
1019 outbuf_size = len + NUL_TERMINATOR_LENGTH;
1020 outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
1021 outp = dest = g_malloc (outbuf_size);
1023 while (!done && !have_error)
1025 gsize inbytes_tmp = inbytes_remaining;
1026 err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
1027 inbytes_remaining = inbytes_tmp;
1029 if (err == (gsize) -1)
1034 g_assert_not_reached();
1038 gsize used = outp - dest;
1041 dest = g_realloc (dest, outbuf_size);
1044 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
1051 /* Error converting fallback string - fatal
1053 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1054 _("Cannot convert fallback '%s' to codeset '%s'"),
1055 insert_str, to_codeset);
1063 gunichar ch = g_utf8_get_char (p);
1064 insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
1068 insert_str = fallback;
1070 save_p = g_utf8_next_char (p);
1071 save_inbytes = inbytes_remaining - (save_p - p);
1073 inbytes_remaining = strlen (p);
1076 /* fall thru if p is NULL */
1081 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1082 _("Error during conversion: %s"),
1083 g_strerror (errsv));
1095 g_free ((gchar *)insert_str);
1097 inbytes_remaining = save_inbytes;
1102 /* call g_iconv with NULL inbuf to cleanup shift state */
1104 inbytes_remaining = 0;
1113 memset (outp, 0, NUL_TERMINATOR_LENGTH);
1115 close_converter (cd);
1118 *bytes_written = outp - dest; /* Doesn't include '\0' */
1124 if (save_p && !fallback)
1125 g_free ((gchar *)insert_str);
1140 strdup_len (const gchar *string,
1142 gsize *bytes_written,
1149 if (!g_utf8_validate (string, len, NULL))
1156 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1157 _("Invalid byte sequence in conversion input"));
1162 real_len = strlen (string);
1167 while (real_len < len && string[real_len])
1172 *bytes_read = real_len;
1174 *bytes_written = real_len;
1176 return g_strndup (string, real_len);
1181 * @opsysstring: a string in the encoding of the current locale. On Windows
1182 * this means the system codepage.
1183 * @len: the length of the string, or -1 if the string is
1184 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1185 * @bytes_read: location to store the number of bytes in the
1186 * input string that were successfully converted, or %NULL.
1187 * Even if the conversion was successful, this may be
1188 * less than @len if there were partial characters
1189 * at the end of the input. If the error
1190 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1191 * stored will the byte offset after the last valid
1193 * @bytes_written: the number of bytes stored in the output buffer (not
1194 * including the terminating nul).
1195 * @error: location to store the error occurring, or %NULL to ignore
1196 * errors. Any of the errors in #GConvertError may occur.
1198 * Converts a string which is in the encoding used for strings by
1199 * the C runtime (usually the same as that used by the operating
1200 * system) in the <link linkend="setlocale">current locale</link> into a
1203 * Return value: The converted string, or %NULL on an error.
1206 g_locale_to_utf8 (const gchar *opsysstring,
1209 gsize *bytes_written,
1212 const char *charset;
1214 if (g_get_charset (&charset))
1215 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1217 return g_convert (opsysstring, len,
1218 "UTF-8", charset, bytes_read, bytes_written, error);
1222 * g_locale_from_utf8:
1223 * @utf8string: a UTF-8 encoded string
1224 * @len: the length of the string, or -1 if the string is
1225 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1226 * @bytes_read: location to store the number of bytes in the
1227 * input string that were successfully converted, or %NULL.
1228 * Even if the conversion was successful, this may be
1229 * less than @len if there were partial characters
1230 * at the end of the input. If the error
1231 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1232 * stored will the byte offset after the last valid
1234 * @bytes_written: the number of bytes stored in the output buffer (not
1235 * including the terminating nul).
1236 * @error: location to store the error occurring, or %NULL to ignore
1237 * errors. Any of the errors in #GConvertError may occur.
1239 * Converts a string from UTF-8 to the encoding used for strings by
1240 * the C runtime (usually the same as that used by the operating
1241 * system) in the <link linkend="setlocale">current locale</link>. On
1242 * Windows this means the system codepage.
1244 * Return value: The converted string, or %NULL on an error.
1247 g_locale_from_utf8 (const gchar *utf8string,
1250 gsize *bytes_written,
1253 const gchar *charset;
1255 if (g_get_charset (&charset))
1256 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1258 return g_convert (utf8string, len,
1259 charset, "UTF-8", bytes_read, bytes_written, error);
1262 #ifndef G_PLATFORM_WIN32
1264 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1266 struct _GFilenameCharsetCache {
1269 gchar **filename_charsets;
1273 filename_charset_cache_free (gpointer data)
1275 GFilenameCharsetCache *cache = data;
1276 g_free (cache->charset);
1277 g_strfreev (cache->filename_charsets);
1282 * g_get_filename_charsets:
1283 * @charsets: return location for the %NULL-terminated list of encoding names
1285 * Determines the preferred character sets used for filenames.
1286 * The first character set from the @charsets is the filename encoding, the
1287 * subsequent character sets are used when trying to generate a displayable
1288 * representation of a filename, see g_filename_display_name().
1290 * On Unix, the character sets are determined by consulting the
1291 * environment variables <envar>G_FILENAME_ENCODING</envar> and
1292 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1293 * used in the GLib API is always UTF-8 and said environment variables
1296 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
1297 * of character set names. The special token "@locale" is taken to
1298 * mean the character set for the <link linkend="setlocale">current
1299 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1300 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1301 * locale is taken as the filename encoding. If neither environment variable
1302 * is set, UTF-8 is taken as the filename encoding, but the character
1303 * set of the current locale is also put in the list of encodings.
1305 * The returned @charsets belong to GLib and must not be freed.
1307 * Note that on Unix, regardless of the locale character set or
1308 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1309 * on a system might be in any random encoding or just gibberish.
1311 * Return value: %TRUE if the filename encoding is UTF-8.
1316 g_get_filename_charsets (const gchar ***filename_charsets)
1318 static GPrivate cache_private = G_PRIVATE_INIT (filename_charset_cache_free);
1319 GFilenameCharsetCache *cache = g_private_get (&cache_private);
1320 const gchar *charset;
1324 cache = g_new0 (GFilenameCharsetCache, 1);
1325 g_private_set (&cache_private, cache);
1328 g_get_charset (&charset);
1330 if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1332 const gchar *new_charset;
1336 g_free (cache->charset);
1337 g_strfreev (cache->filename_charsets);
1338 cache->charset = g_strdup (charset);
1340 p = getenv ("G_FILENAME_ENCODING");
1341 if (p != NULL && p[0] != '\0')
1343 cache->filename_charsets = g_strsplit (p, ",", 0);
1344 cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1346 for (i = 0; cache->filename_charsets[i]; i++)
1348 if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1350 g_get_charset (&new_charset);
1351 g_free (cache->filename_charsets[i]);
1352 cache->filename_charsets[i] = g_strdup (new_charset);
1356 else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1358 cache->filename_charsets = g_new0 (gchar *, 2);
1359 cache->is_utf8 = g_get_charset (&new_charset);
1360 cache->filename_charsets[0] = g_strdup (new_charset);
1364 cache->filename_charsets = g_new0 (gchar *, 3);
1365 cache->is_utf8 = TRUE;
1366 cache->filename_charsets[0] = g_strdup ("UTF-8");
1367 if (!g_get_charset (&new_charset))
1368 cache->filename_charsets[1] = g_strdup (new_charset);
1372 if (filename_charsets)
1373 *filename_charsets = (const gchar **)cache->filename_charsets;
1375 return cache->is_utf8;
1378 #else /* G_PLATFORM_WIN32 */
1381 g_get_filename_charsets (const gchar ***filename_charsets)
1383 static const gchar *charsets[] = {
1389 /* On Windows GLib pretends that the filename charset is UTF-8 */
1390 if (filename_charsets)
1391 *filename_charsets = charsets;
1397 /* Cygwin works like before */
1398 result = g_get_charset (&(charsets[0]));
1400 if (filename_charsets)
1401 *filename_charsets = charsets;
1407 #endif /* G_PLATFORM_WIN32 */
1410 get_filename_charset (const gchar **filename_charset)
1412 const gchar **charsets;
1415 is_utf8 = g_get_filename_charsets (&charsets);
1417 if (filename_charset)
1418 *filename_charset = charsets[0];
1424 * g_filename_to_utf8:
1425 * @opsysstring: a string in the encoding for filenames
1426 * @len: the length of the string, or -1 if the string is
1427 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1428 * @bytes_read: location to store the number of bytes in the
1429 * input string that were successfully converted, or %NULL.
1430 * Even if the conversion was successful, this may be
1431 * less than @len if there were partial characters
1432 * at the end of the input. If the error
1433 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1434 * stored will the byte offset after the last valid
1436 * @bytes_written: the number of bytes stored in the output buffer (not
1437 * including the terminating nul).
1438 * @error: location to store the error occurring, or %NULL to ignore
1439 * errors. Any of the errors in #GConvertError may occur.
1441 * Converts a string which is in the encoding used by GLib for
1442 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1443 * for filenames; on other platforms, this function indirectly depends on
1444 * the <link linkend="setlocale">current locale</link>.
1446 * Return value: The converted string, or %NULL on an error.
1449 g_filename_to_utf8 (const gchar *opsysstring,
1452 gsize *bytes_written,
1455 const gchar *charset;
1457 g_return_val_if_fail (opsysstring != NULL, NULL);
1459 if (get_filename_charset (&charset))
1460 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1462 return g_convert (opsysstring, len,
1463 "UTF-8", charset, bytes_read, bytes_written, error);
1466 #if defined (G_OS_WIN32) && !defined (_WIN64)
1468 #undef g_filename_to_utf8
1470 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1471 * 64-bit versions as there should be no old deployed binaries that would use
1476 g_filename_to_utf8 (const gchar *opsysstring,
1479 gsize *bytes_written,
1482 const gchar *charset;
1484 g_return_val_if_fail (opsysstring != NULL, NULL);
1486 if (g_get_charset (&charset))
1487 return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1489 return g_convert (opsysstring, len,
1490 "UTF-8", charset, bytes_read, bytes_written, error);
1496 * g_filename_from_utf8:
1497 * @utf8string: a UTF-8 encoded string.
1498 * @len: the length of the string, or -1 if the string is
1500 * @bytes_read: (out) (allow-none): location to store the number of bytes in
1501 * the input string that were successfully converted, or %NULL.
1502 * Even if the conversion was successful, this may be
1503 * less than @len if there were partial characters
1504 * at the end of the input. If the error
1505 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1506 * stored will the byte offset after the last valid
1508 * @bytes_written: (out): the number of bytes stored in the output buffer (not
1509 * including the terminating nul).
1510 * @error: location to store the error occurring, or %NULL to ignore
1511 * errors. Any of the errors in #GConvertError may occur.
1513 * Converts a string from UTF-8 to the encoding GLib uses for
1514 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1515 * on other platforms, this function indirectly depends on the
1516 * <link linkend="setlocale">current locale</link>.
1518 * Return value: (array length=bytes_written) (element-type guint8) (transfer full):
1519 * The converted string, or %NULL on an error.
1522 g_filename_from_utf8 (const gchar *utf8string,
1525 gsize *bytes_written,
1528 const gchar *charset;
1530 if (get_filename_charset (&charset))
1531 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1533 return g_convert (utf8string, len,
1534 charset, "UTF-8", bytes_read, bytes_written, error);
1537 #if defined (G_OS_WIN32) && !defined (_WIN64)
1539 #undef g_filename_from_utf8
1541 /* Binary compatibility version. Not for newly compiled code. */
1544 g_filename_from_utf8 (const gchar *utf8string,
1547 gsize *bytes_written,
1550 const gchar *charset;
1552 if (g_get_charset (&charset))
1553 return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1555 return g_convert (utf8string, len,
1556 charset, "UTF-8", bytes_read, bytes_written, error);
1561 /* Test of haystack has the needle prefix, comparing case
1562 * insensitive. haystack may be UTF-8, but needle must
1563 * contain only ascii. */
1565 has_case_prefix (const gchar *haystack, const gchar *needle)
1569 /* Eat one character at a time. */
1574 g_ascii_tolower (*n) == g_ascii_tolower (*h))
1584 UNSAFE_ALL = 0x1, /* Escape all unsafe characters */
1585 UNSAFE_ALLOW_PLUS = 0x2, /* Allows '+' */
1586 UNSAFE_PATH = 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1587 UNSAFE_HOST = 0x10, /* Allows '/' and ':' and '@' */
1588 UNSAFE_SLASHES = 0x20 /* Allows all characters except for '/' and '%' */
1589 } UnsafeCharacterSet;
1591 static const guchar acceptable[96] = {
1592 /* A table of the ASCII chars from space (32) to DEL (127) */
1593 /* ! " # $ % & ' ( ) * + , - . / */
1594 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1595 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1596 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1597 /* @ A B C D E F G H I J K L M N O */
1598 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1599 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1600 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1601 /* ` a b c d e f g h i j k l m n o */
1602 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1603 /* p q r s t u v w x y z { | } ~ DEL */
1604 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1607 static const gchar hex[16] = "0123456789ABCDEF";
1609 /* Note: This escape function works on file: URIs, but if you want to
1610 * escape something else, please read RFC-2396 */
1612 g_escape_uri_string (const gchar *string,
1613 UnsafeCharacterSet mask)
1615 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1622 UnsafeCharacterSet use_mask;
1624 g_return_val_if_fail (mask == UNSAFE_ALL
1625 || mask == UNSAFE_ALLOW_PLUS
1626 || mask == UNSAFE_PATH
1627 || mask == UNSAFE_HOST
1628 || mask == UNSAFE_SLASHES, NULL);
1632 for (p = string; *p != '\0'; p++)
1635 if (!ACCEPTABLE (c))
1639 result = g_malloc (p - string + unacceptable * 2 + 1);
1642 for (q = result, p = string; *p != '\0'; p++)
1646 if (!ACCEPTABLE (c))
1648 *q++ = '%'; /* means hex coming */
1663 g_escape_file_uri (const gchar *hostname,
1664 const gchar *pathname)
1666 char *escaped_hostname = NULL;
1671 char *p, *backslash;
1673 /* Turn backslashes into forward slashes. That's what Netscape
1674 * does, and they are actually more or less equivalent in Windows.
1677 pathname = g_strdup (pathname);
1678 p = (char *) pathname;
1680 while ((backslash = strchr (p, '\\')) != NULL)
1687 if (hostname && *hostname != '\0')
1689 escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1692 escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1694 res = g_strconcat ("file://",
1695 (escaped_hostname) ? escaped_hostname : "",
1696 (*escaped_path != '/') ? "/" : "",
1701 g_free ((char *) pathname);
1704 g_free (escaped_hostname);
1705 g_free (escaped_path);
1711 unescape_character (const char *scanner)
1716 first_digit = g_ascii_xdigit_value (scanner[0]);
1717 if (first_digit < 0)
1720 second_digit = g_ascii_xdigit_value (scanner[1]);
1721 if (second_digit < 0)
1724 return (first_digit << 4) | second_digit;
1728 g_unescape_uri_string (const char *escaped,
1730 const char *illegal_escaped_characters,
1731 gboolean ascii_must_not_be_escaped)
1733 const gchar *in, *in_end;
1734 gchar *out, *result;
1737 if (escaped == NULL)
1741 len = strlen (escaped);
1743 result = g_malloc (len + 1);
1746 for (in = escaped, in_end = escaped + len; in < in_end; in++)
1752 /* catch partial escape sequences past the end of the substring */
1753 if (in + 3 > in_end)
1756 c = unescape_character (in + 1);
1758 /* catch bad escape sequences and NUL characters */
1762 /* catch escaped ASCII */
1763 if (ascii_must_not_be_escaped && c <= 0x7F)
1766 /* catch other illegal escaped characters */
1767 if (strchr (illegal_escaped_characters, c) != NULL)
1776 g_assert (out - result <= len);
1789 is_asciialphanum (gunichar c)
1791 return c <= 0x7F && g_ascii_isalnum (c);
1795 is_asciialpha (gunichar c)
1797 return c <= 0x7F && g_ascii_isalpha (c);
1800 /* allows an empty string */
1802 hostname_validate (const char *hostname)
1805 gunichar c, first_char, last_char;
1812 /* read in a label */
1813 c = g_utf8_get_char (p);
1814 p = g_utf8_next_char (p);
1815 if (!is_asciialphanum (c))
1821 c = g_utf8_get_char (p);
1822 p = g_utf8_next_char (p);
1824 while (is_asciialphanum (c) || c == '-');
1825 if (last_char == '-')
1828 /* if that was the last label, check that it was a toplabel */
1829 if (c == '\0' || (c == '.' && *p == '\0'))
1830 return is_asciialpha (first_char);
1837 * g_filename_from_uri:
1838 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1839 * @hostname: (out) (allow-none): Location to store hostname for the URI, or %NULL.
1840 * If there is no hostname in the URI, %NULL will be
1841 * stored in this location.
1842 * @error: location to store the error occurring, or %NULL to ignore
1843 * errors. Any of the errors in #GConvertError may occur.
1845 * Converts an escaped ASCII-encoded URI to a local filename in the
1846 * encoding used for filenames.
1848 * Return value: (type filename): a newly-allocated string holding
1849 * the resulting filename, or %NULL on an error.
1852 g_filename_from_uri (const gchar *uri,
1856 const char *path_part;
1857 const char *host_part;
1858 char *unescaped_hostname;
1869 if (!has_case_prefix (uri, "file:/"))
1871 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1872 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1877 path_part = uri + strlen ("file:");
1879 if (strchr (path_part, '#') != NULL)
1881 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1882 _("The local file URI '%s' may not include a '#'"),
1887 if (has_case_prefix (path_part, "///"))
1889 else if (has_case_prefix (path_part, "//"))
1892 host_part = path_part;
1894 path_part = strchr (path_part, '/');
1896 if (path_part == NULL)
1898 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1899 _("The URI '%s' is invalid"),
1904 unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1906 if (unescaped_hostname == NULL ||
1907 !hostname_validate (unescaped_hostname))
1909 g_free (unescaped_hostname);
1910 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1911 _("The hostname of the URI '%s' is invalid"),
1917 *hostname = unescaped_hostname;
1919 g_free (unescaped_hostname);
1922 filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1924 if (filename == NULL)
1926 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1927 _("The URI '%s' contains invalidly escaped characters"),
1934 /* Drop localhost */
1935 if (hostname && *hostname != NULL &&
1936 g_ascii_strcasecmp (*hostname, "localhost") == 0)
1942 /* Turn slashes into backslashes, because that's the canonical spelling */
1944 while ((slash = strchr (p, '/')) != NULL)
1950 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1951 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1952 * the filename from the drive letter.
1954 if (g_ascii_isalpha (filename[1]))
1956 if (filename[2] == ':')
1958 else if (filename[2] == '|')
1966 result = g_strdup (filename + offs);
1972 #if defined (G_OS_WIN32) && !defined (_WIN64)
1974 #undef g_filename_from_uri
1977 g_filename_from_uri (const gchar *uri,
1981 gchar *utf8_filename;
1982 gchar *retval = NULL;
1984 utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1987 retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1988 g_free (utf8_filename);
1996 * g_filename_to_uri:
1997 * @filename: an absolute filename specified in the GLib file name encoding,
1998 * which is the on-disk file name bytes on Unix, and UTF-8 on
2000 * @hostname: (allow-none): A UTF-8 encoded hostname, or %NULL for none.
2001 * @error: location to store the error occurring, or %NULL to ignore
2002 * errors. Any of the errors in #GConvertError may occur.
2004 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
2005 * component following Section 3.3. of RFC 2396.
2007 * Return value: a newly-allocated string holding the resulting
2008 * URI, or %NULL on an error.
2011 g_filename_to_uri (const gchar *filename,
2012 const gchar *hostname,
2017 g_return_val_if_fail (filename != NULL, NULL);
2019 if (!g_path_is_absolute (filename))
2021 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
2022 _("The pathname '%s' is not an absolute path"),
2028 !(g_utf8_validate (hostname, -1, NULL)
2029 && hostname_validate (hostname)))
2031 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2032 _("Invalid hostname"));
2037 /* Don't use localhost unnecessarily */
2038 if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
2042 escaped_uri = g_escape_file_uri (hostname, filename);
2047 #if defined (G_OS_WIN32) && !defined (_WIN64)
2049 #undef g_filename_to_uri
2052 g_filename_to_uri (const gchar *filename,
2053 const gchar *hostname,
2056 gchar *utf8_filename;
2057 gchar *retval = NULL;
2059 utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2063 retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
2064 g_free (utf8_filename);
2073 * g_uri_list_extract_uris:
2074 * @uri_list: an URI list
2076 * Splits an URI list conforming to the text/uri-list
2077 * mime type defined in RFC 2483 into individual URIs,
2078 * discarding any comments. The URIs are not validated.
2080 * Returns: (transfer full): a newly allocated %NULL-terminated list
2081 * of strings holding the individual URIs. The array should be freed
2082 * with g_strfreev().
2087 g_uri_list_extract_uris (const gchar *uri_list)
2098 /* We don't actually try to validate the URI according to RFC
2099 * 2396, or even check for allowed characters - we just ignore
2100 * comments and trim whitespace off the ends. We also
2101 * allow LF delimination as well as the specified CRLF.
2103 * We do allow comments like specified in RFC 2483.
2109 while (g_ascii_isspace (*p))
2113 while (*q && (*q != '\n') && (*q != '\r'))
2119 while (q > p && g_ascii_isspace (*q))
2124 uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2129 p = strchr (p, '\n');
2134 result = g_new (gchar *, n_uris + 1);
2136 result[n_uris--] = NULL;
2137 for (u = uris; u; u = u->next)
2138 result[n_uris--] = u->data;
2140 g_slist_free (uris);
2146 * g_filename_display_basename:
2147 * @filename: an absolute pathname in the GLib file name encoding
2149 * Returns the display basename for the particular filename, guaranteed
2150 * to be valid UTF-8. The display name might not be identical to the filename,
2151 * for instance there might be problems converting it to UTF-8, and some files
2152 * can be translated in the display.
2154 * If GLib cannot make sense of the encoding of @filename, as a last resort it
2155 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2156 * You can search the result for the UTF-8 encoding of this character (which is
2157 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2160 * You must pass the whole absolute pathname to this functions so that
2161 * translation of well known locations can be done.
2163 * This function is preferred over g_filename_display_name() if you know the
2164 * whole path, as it allows translation.
2166 * Return value: a newly allocated string containing
2167 * a rendition of the basename of the filename in valid UTF-8
2172 g_filename_display_basename (const gchar *filename)
2177 g_return_val_if_fail (filename != NULL, NULL);
2179 basename = g_path_get_basename (filename);
2180 display_name = g_filename_display_name (basename);
2182 return display_name;
2186 * g_filename_display_name:
2187 * @filename: a pathname hopefully in the GLib file name encoding
2189 * Converts a filename into a valid UTF-8 string. The conversion is
2190 * not necessarily reversible, so you should keep the original around
2191 * and use the return value of this function only for display purposes.
2192 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
2193 * even if the filename actually isn't in the GLib file name encoding.
2195 * If GLib cannot make sense of the encoding of @filename, as a last resort it
2196 * replaces unknown characters with U+FFFD, the Unicode replacement character.
2197 * You can search the result for the UTF-8 encoding of this character (which is
2198 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2201 * If you know the whole pathname of the file you should use
2202 * g_filename_display_basename(), since that allows location-based
2203 * translation of filenames.
2205 * Return value: a newly allocated string containing
2206 * a rendition of the filename in valid UTF-8
2211 g_filename_display_name (const gchar *filename)
2214 const gchar **charsets;
2215 gchar *display_name = NULL;
2218 is_utf8 = g_get_filename_charsets (&charsets);
2222 if (g_utf8_validate (filename, -1, NULL))
2223 display_name = g_strdup (filename);
2228 /* Try to convert from the filename charsets to UTF-8.
2229 * Skip the first charset if it is UTF-8.
2231 for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2233 display_name = g_convert (filename, -1, "UTF-8", charsets[i],
2241 /* if all conversions failed, we replace invalid UTF-8
2242 * by a question mark
2245 display_name = _g_utf8_make_valid (filename);
2247 return display_name;