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"
56 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
57 #error GNU libiconv in use but included iconv.h not from libiconv
59 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H) \
60 && !defined (__APPLE_CC__) && !defined (__LP_64__)
61 #error GNU libiconv not in use but included iconv.h is from libiconv
67 * @title: Character Set Conversion
68 * @short_description: convert strings between different character sets
70 * The g_convert() family of function wraps the functionality of iconv(). In
71 * addition to pure character set conversions, GLib has functions to deal
72 * with the extra complications of encodings for file names.
74 * <refsect2 id="file-name-encodings">
75 * <title>File Name Encodings</title>
77 * Historically, Unix has not had a defined encoding for file
78 * names: a file name is valid as long as it does not have path
79 * separators in it ("/"). However, displaying file names may
80 * require conversion: from the character set in which they were
81 * created, to the character set in which the application
82 * operates. Consider the Spanish file name
83 * "<filename>Presentación.sxi</filename>". If the
84 * application which created it uses ISO-8859-1 for its encoding,
86 * <programlisting id="filename-iso8859-1">
87 * Character: P r e s e n t a c i ó n . s x i
88 * Hex code: 50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
91 * However, if the application use UTF-8, the actual file name on
92 * disk would look like this:
94 * <programlisting id="filename-utf-8">
95 * Character: P r e s e n t a c i ó n . s x i
96 * Hex code: 50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
99 * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+
100 * that use Glib do the same thing. If you get a file name from
101 * the file system, for example, from readdir(3) or from g_dir_read_name(),
102 * and you wish to display the file name to the user, you
103 * <emphasis>will</emphasis> need to convert it into UTF-8. The
104 * opposite case is when the user types the name of a file he
105 * wishes to save: the toolkit will give you that string in
106 * UTF-8 encoding, and you will need to convert it to the
107 * character set used for file names before you can create the
108 * file with open(2) or fopen(3).
111 * By default, Glib assumes that file names on disk are in UTF-8
112 * encoding. This is a valid assumption for file systems which
113 * were created relatively recently: most applications use UTF-8
114 * encoding for their strings, and that is also what they use for
115 * the file names they create. However, older file systems may
116 * still contain file names created in "older" encodings, such as
117 * ISO-8859-1. In this case, for compatibility reasons, you may
118 * want to instruct Glib to use that particular encoding for file
119 * names rather than UTF-8. You can do this by specifying the
120 * encoding for file names in the <link
121 * linkend="G_FILENAME_ENCODING"><envar>G_FILENAME_ENCODING</envar></link>
122 * environment variable. For example, if your installation uses
123 * ISO-8859-1 for file names, you can put this in your
124 * <filename>~/.profile</filename>:
127 * export G_FILENAME_ENCODING=ISO-8859-1
130 * Glib provides the functions g_filename_to_utf8() and
131 * g_filename_from_utf8() to perform the necessary conversions. These
132 * functions convert file names from the encoding specified in
133 * <envar>G_FILENAME_ENCODING</envar> to UTF-8 and vice-versa.
134 * <xref linkend="file-name-encodings-diagram"/> illustrates how
135 * these functions are used to convert between UTF-8 and the
136 * encoding for file names in the file system.
138 * <figure id="file-name-encodings-diagram">
139 * <title>Conversion between File Name Encodings</title>
140 * <graphic fileref="file-name-encodings.png" format="PNG"/>
142 * <refsect3 id="file-name-encodings-checklist">
143 * <title>Checklist for Application Writers</title>
145 * This section is a practical summary of the detailed
146 * description above. You can use this as a checklist of
147 * things to do to make sure your applications process file
148 * name encodings correctly.
152 * If you get a file name from the file system from a function
153 * such as readdir(3) or gtk_file_chooser_get_filename(),
154 * you do not need to do any conversion to pass that
155 * file name to functions like open(2), rename(2), or
156 * fopen(3) — those are "raw" file names which the file
157 * system understands.
160 * If you need to display a file name, convert it to UTF-8 first by
161 * using g_filename_to_utf8(). If conversion fails, display a string like
162 * "<literal>Unknown file name</literal>". <emphasis>Do not</emphasis>
163 * convert this string back into the encoding used for file names if you
164 * wish to pass it to the file system; use the original file name instead.
165 * For example, the document window of a word processor could display
166 * "Unknown file name" in its title bar but still let the user save the
167 * file, as it would keep the raw file name internally. This can happen
168 * if the user has not set the <envar>G_FILENAME_ENCODING</envar>
169 * environment variable even though he has files whose names are not
173 * If your user interface lets the user type a file name for saving or
174 * renaming, convert it to the encoding used for file names in the file
175 * system by using g_filename_from_utf8(). Pass the converted file name
176 * to functions like fopen(3). If conversion fails, ask the user to enter
177 * a different file name. This can happen if the user types Japanese
178 * characters when <envar>G_FILENAME_ENCODING</envar> is set to
179 * <literal>ISO-8859-1</literal>, for example.
186 /* We try to terminate strings in unknown charsets with this many zero bytes
187 * to ensure that multibyte strings really are nul-terminated when we return
188 * them from g_convert() and friends.
190 #define NUL_TERMINATOR_LENGTH 4
192 G_DEFINE_QUARK (g_convert_error
, g_convert_error
)
195 try_conversion (const char *to_codeset
,
196 const char *from_codeset
,
199 *cd
= iconv_open (to_codeset
, from_codeset
);
201 if (*cd
== (iconv_t
)-1 && errno
== EINVAL
)
208 try_to_aliases (const char **to_aliases
,
209 const char *from_codeset
,
214 const char **p
= to_aliases
;
217 if (try_conversion (*p
, from_codeset
, cd
))
229 * @to_codeset: destination codeset
230 * @from_codeset: source codeset
232 * Same as the standard UNIX routine iconv_open(), but
233 * may be implemented via libiconv on UNIX flavors that lack
234 * a native implementation.
236 * GLib provides g_convert() and g_locale_to_utf8() which are likely
237 * more convenient than the raw iconv wrappers.
239 * Return value: a "conversion descriptor", or (GIConv)-1 if
240 * opening the converter failed.
243 g_iconv_open (const gchar
*to_codeset
,
244 const gchar
*from_codeset
)
248 if (!try_conversion (to_codeset
, from_codeset
, &cd
))
250 const char **to_aliases
= _g_charset_get_aliases (to_codeset
);
251 const char **from_aliases
= _g_charset_get_aliases (from_codeset
);
255 const char **p
= from_aliases
;
258 if (try_conversion (to_codeset
, *p
, &cd
))
261 if (try_to_aliases (to_aliases
, *p
, &cd
))
268 if (try_to_aliases (to_aliases
, from_codeset
, &cd
))
273 return (cd
== (iconv_t
)-1) ? (GIConv
)-1 : (GIConv
)cd
;
278 * @converter: conversion descriptor from g_iconv_open()
279 * @inbuf: bytes to convert
280 * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
281 * @outbuf: converted output bytes
282 * @outbytes_left: inout parameter, bytes available to fill in @outbuf
284 * Same as the standard UNIX routine iconv(), but
285 * may be implemented via libiconv on UNIX flavors that lack
286 * a native implementation.
288 * GLib provides g_convert() and g_locale_to_utf8() which are likely
289 * more convenient than the raw iconv wrappers.
291 * Return value: count of non-reversible conversions, or -1 on error
294 g_iconv (GIConv converter
,
298 gsize
*outbytes_left
)
300 iconv_t cd
= (iconv_t
)converter
;
302 return iconv (cd
, inbuf
, inbytes_left
, outbuf
, outbytes_left
);
307 * @converter: a conversion descriptor from g_iconv_open()
309 * Same as the standard UNIX routine iconv_close(), but
310 * may be implemented via libiconv on UNIX flavors that lack
311 * a native implementation. Should be called to clean up
312 * the conversion descriptor from g_iconv_open() when
313 * you are done converting things.
315 * GLib provides g_convert() and g_locale_to_utf8() which are likely
316 * more convenient than the raw iconv wrappers.
318 * Return value: -1 on error, 0 on success
321 g_iconv_close (GIConv converter
)
323 iconv_t cd
= (iconv_t
)converter
;
325 return iconv_close (cd
);
329 open_converter (const gchar
*to_codeset
,
330 const gchar
*from_codeset
,
335 cd
= g_iconv_open (to_codeset
, from_codeset
);
337 if (cd
== (GIConv
) -1)
339 /* Something went wrong. */
343 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_NO_CONVERSION
,
344 _("Conversion from character set '%s' to '%s' is not supported"),
345 from_codeset
, to_codeset
);
347 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_FAILED
,
348 _("Could not open converter from '%s' to '%s'"),
349 from_codeset
, to_codeset
);
357 close_converter (GIConv cd
)
359 if (cd
== (GIConv
) -1)
362 return g_iconv_close (cd
);
366 * g_convert_with_iconv:
367 * @str: the string to convert
368 * @len: the length of the string, or -1 if the string is
369 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
370 * @converter: conversion descriptor from g_iconv_open()
371 * @bytes_read: location to store the number of bytes in the
372 * input string that were successfully converted, or %NULL.
373 * Even if the conversion was successful, this may be
374 * less than @len if there were partial characters
375 * at the end of the input. If the error
376 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
377 * stored will the byte offset after the last valid
379 * @bytes_written: the number of bytes stored in the output buffer (not
380 * including the terminating nul).
381 * @error: location to store the error occurring, or %NULL to ignore
382 * errors. Any of the errors in #GConvertError may occur.
384 * Converts a string from one character set to another.
386 * Note that you should use g_iconv() for streaming
387 * conversions<footnote id="streaming-state">
389 * Despite the fact that @byes_read can return information about partial
390 * characters, the <literal>g_convert_...</literal> functions
391 * are not generally suitable for streaming. If the underlying converter
392 * being used maintains internal state, then this won't be preserved
393 * across successive calls to g_convert(), g_convert_with_iconv() or
394 * g_convert_with_fallback(). (An example of this is the GNU C converter
395 * for CP1255 which does not emit a base character until it knows that
396 * the next character is not a mark that could combine with the base
401 * Return value: If the conversion was successful, a newly allocated
402 * nul-terminated string, which must be freed with
403 * g_free(). Otherwise %NULL and @error will be set.
406 g_convert_with_iconv (const gchar
*str
,
410 gsize
*bytes_written
,
416 gsize inbytes_remaining
;
417 gsize outbytes_remaining
;
420 gboolean have_error
= FALSE
;
421 gboolean done
= FALSE
;
422 gboolean reset
= FALSE
;
424 g_return_val_if_fail (converter
!= (GIConv
) -1, NULL
);
430 inbytes_remaining
= len
;
431 outbuf_size
= len
+ NUL_TERMINATOR_LENGTH
;
433 outbytes_remaining
= outbuf_size
- NUL_TERMINATOR_LENGTH
;
434 outp
= dest
= g_malloc (outbuf_size
);
436 while (!done
&& !have_error
)
439 err
= g_iconv (converter
, NULL
, &inbytes_remaining
, &outp
, &outbytes_remaining
);
441 err
= g_iconv (converter
, (char **)&p
, &inbytes_remaining
, &outp
, &outbytes_remaining
);
443 if (err
== (gsize
) -1)
448 /* Incomplete text, do not report an error */
453 gsize used
= outp
- dest
;
456 dest
= g_realloc (dest
, outbuf_size
);
459 outbytes_remaining
= outbuf_size
- used
- NUL_TERMINATOR_LENGTH
;
463 g_set_error_literal (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
,
464 _("Invalid byte sequence in conversion input"));
471 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_FAILED
,
472 _("Error during conversion: %s"),
483 /* call g_iconv with NULL inbuf to cleanup shift state */
485 inbytes_remaining
= 0;
492 memset (outp
, 0, NUL_TERMINATOR_LENGTH
);
495 *bytes_read
= p
- str
;
498 if ((p
- str
) != len
)
502 g_set_error_literal (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_PARTIAL_INPUT
,
503 _("Partial character sequence at end of input"));
510 *bytes_written
= outp
- dest
; /* Doesn't include '\0' */
523 * @str: the string to convert
524 * @len: the length of the string, or -1 if the string is
525 * nul-terminated<footnote id="nul-unsafe">
527 Note that some encodings may allow nul bytes to
528 occur inside strings. In that case, using -1 for
529 the @len parameter is unsafe.
532 * @to_codeset: name of character set into which to convert @str
533 * @from_codeset: character set of @str.
534 * @bytes_read: (out): location to store the number of bytes in the
535 * input string that were successfully converted, or %NULL.
536 * Even if the conversion was successful, this may be
537 * less than @len if there were partial characters
538 * at the end of the input. If the error
539 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
540 * stored will the byte offset after the last valid
542 * @bytes_written: (out): the number of bytes stored in the output buffer (not
543 * including the terminating nul).
544 * @error: location to store the error occurring, or %NULL to ignore
545 * errors. Any of the errors in #GConvertError may occur.
547 * Converts a string from one character set to another.
549 * Note that you should use g_iconv() for streaming
550 * conversions<footnoteref linkend="streaming-state"/>.
552 * Return value: If the conversion was successful, a newly allocated
553 * nul-terminated string, which must be freed with
554 * g_free(). Otherwise %NULL and @error will be set.
557 g_convert (const gchar
*str
,
559 const gchar
*to_codeset
,
560 const gchar
*from_codeset
,
562 gsize
*bytes_written
,
568 g_return_val_if_fail (str
!= NULL
, NULL
);
569 g_return_val_if_fail (to_codeset
!= NULL
, NULL
);
570 g_return_val_if_fail (from_codeset
!= NULL
, NULL
);
572 cd
= open_converter (to_codeset
, from_codeset
, error
);
574 if (cd
== (GIConv
) -1)
585 res
= g_convert_with_iconv (str
, len
, cd
,
586 bytes_read
, bytes_written
,
589 close_converter (cd
);
595 * g_convert_with_fallback:
596 * @str: the string to convert
597 * @len: the length of the string, or -1 if the string is
598 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
599 * @to_codeset: name of character set into which to convert @str
600 * @from_codeset: character set of @str.
601 * @fallback: UTF-8 string to use in place of character not
602 * present in the target encoding. (The string must be
603 * representable in the target encoding).
604 If %NULL, characters not in the target encoding will
605 be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
606 * @bytes_read: location to store the number of bytes in the
607 * input string that were successfully converted, or %NULL.
608 * Even if the conversion was successful, this may be
609 * less than @len if there were partial characters
610 * at the end of the input.
611 * @bytes_written: the number of bytes stored in the output buffer (not
612 * including the terminating nul).
613 * @error: location to store the error occurring, or %NULL to ignore
614 * errors. Any of the errors in #GConvertError may occur.
616 * Converts a string from one character set to another, possibly
617 * including fallback sequences for characters not representable
618 * in the output. Note that it is not guaranteed that the specification
619 * for the fallback sequences in @fallback will be honored. Some
620 * systems may do an approximate conversion from @from_codeset
621 * to @to_codeset in their iconv() functions,
622 * in which case GLib will simply return that approximate conversion.
624 * Note that you should use g_iconv() for streaming
625 * conversions<footnoteref linkend="streaming-state"/>.
627 * Return value: If the conversion was successful, a newly allocated
628 * nul-terminated string, which must be freed with
629 * g_free(). Otherwise %NULL and @error will be set.
632 g_convert_with_fallback (const gchar
*str
,
634 const gchar
*to_codeset
,
635 const gchar
*from_codeset
,
636 const gchar
*fallback
,
638 gsize
*bytes_written
,
644 const gchar
*insert_str
= NULL
;
646 gsize inbytes_remaining
;
647 const gchar
*save_p
= NULL
;
648 gsize save_inbytes
= 0;
649 gsize outbytes_remaining
;
653 gboolean have_error
= FALSE
;
654 gboolean done
= FALSE
;
656 GError
*local_error
= NULL
;
658 g_return_val_if_fail (str
!= NULL
, NULL
);
659 g_return_val_if_fail (to_codeset
!= NULL
, NULL
);
660 g_return_val_if_fail (from_codeset
!= NULL
, NULL
);
665 /* Try an exact conversion; we only proceed if this fails
666 * due to an illegal sequence in the input string.
668 dest
= g_convert (str
, len
, to_codeset
, from_codeset
,
669 bytes_read
, bytes_written
, &local_error
);
673 if (!g_error_matches (local_error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
))
675 g_propagate_error (error
, local_error
);
679 g_error_free (local_error
);
683 /* No go; to proceed, we need a converter from "UTF-8" to
684 * to_codeset, and the string as UTF-8.
686 cd
= open_converter (to_codeset
, "UTF-8", error
);
687 if (cd
== (GIConv
) -1)
698 utf8
= g_convert (str
, len
, "UTF-8", from_codeset
,
699 bytes_read
, &inbytes_remaining
, error
);
702 close_converter (cd
);
708 /* Now the heart of the code. We loop through the UTF-8 string, and
709 * whenever we hit an offending character, we form fallback, convert
710 * the fallback to the target codeset, and then go back to
711 * converting the original string after finishing with the fallback.
713 * The variables save_p and save_inbytes store the input state
714 * for the original string while we are converting the fallback
718 outbuf_size
= len
+ NUL_TERMINATOR_LENGTH
;
719 outbytes_remaining
= outbuf_size
- NUL_TERMINATOR_LENGTH
;
720 outp
= dest
= g_malloc (outbuf_size
);
722 while (!done
&& !have_error
)
724 gsize inbytes_tmp
= inbytes_remaining
;
725 err
= g_iconv (cd
, (char **)&p
, &inbytes_tmp
, &outp
, &outbytes_remaining
);
726 inbytes_remaining
= inbytes_tmp
;
728 if (err
== (gsize
) -1)
733 g_assert_not_reached();
737 gsize used
= outp
- dest
;
740 dest
= g_realloc (dest
, outbuf_size
);
743 outbytes_remaining
= outbuf_size
- used
- NUL_TERMINATOR_LENGTH
;
750 /* Error converting fallback string - fatal
752 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
,
753 _("Cannot convert fallback '%s' to codeset '%s'"),
754 insert_str
, to_codeset
);
762 gunichar ch
= g_utf8_get_char (p
);
763 insert_str
= g_strdup_printf (ch
< 0x10000 ? "\\u%04x" : "\\U%08x",
767 insert_str
= fallback
;
769 save_p
= g_utf8_next_char (p
);
770 save_inbytes
= inbytes_remaining
- (save_p
- p
);
772 inbytes_remaining
= strlen (p
);
775 /* fall thru if p is NULL */
780 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_FAILED
,
781 _("Error during conversion: %s"),
794 g_free ((gchar
*)insert_str
);
796 inbytes_remaining
= save_inbytes
;
801 /* call g_iconv with NULL inbuf to cleanup shift state */
803 inbytes_remaining
= 0;
812 memset (outp
, 0, NUL_TERMINATOR_LENGTH
);
814 close_converter (cd
);
817 *bytes_written
= outp
- dest
; /* Doesn't include '\0' */
823 if (save_p
&& !fallback
)
824 g_free ((gchar
*)insert_str
);
839 strdup_len (const gchar
*string
,
841 gsize
*bytes_written
,
848 if (!g_utf8_validate (string
, len
, NULL
))
855 g_set_error_literal (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
,
856 _("Invalid byte sequence in conversion input"));
861 real_len
= strlen (string
);
866 while (real_len
< len
&& string
[real_len
])
871 *bytes_read
= real_len
;
873 *bytes_written
= real_len
;
875 return g_strndup (string
, real_len
);
880 * @opsysstring: a string in the encoding of the current locale. On Windows
881 * this means the system codepage.
882 * @len: the length of the string, or -1 if the string is
883 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
884 * @bytes_read: location to store the number of bytes in the
885 * input string that were successfully converted, or %NULL.
886 * Even if the conversion was successful, this may be
887 * less than @len if there were partial characters
888 * at the end of the input. If the error
889 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
890 * stored will the byte offset after the last valid
892 * @bytes_written: the number of bytes stored in the output buffer (not
893 * including the terminating nul).
894 * @error: location to store the error occurring, or %NULL to ignore
895 * errors. Any of the errors in #GConvertError may occur.
897 * Converts a string which is in the encoding used for strings by
898 * the C runtime (usually the same as that used by the operating
899 * system) in the <link linkend="setlocale">current locale</link> into a
902 * Return value: A newly-allocated buffer containing the converted string,
903 * or %NULL on an error, and error will be set.
906 g_locale_to_utf8 (const gchar
*opsysstring
,
909 gsize
*bytes_written
,
914 if (g_get_charset (&charset
))
915 return strdup_len (opsysstring
, len
, bytes_read
, bytes_written
, error
);
917 return g_convert (opsysstring
, len
,
918 "UTF-8", charset
, bytes_read
, bytes_written
, error
);
922 * g_locale_from_utf8:
923 * @utf8string: a UTF-8 encoded string
924 * @len: the length of the string, or -1 if the string is
925 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
926 * @bytes_read: location to store the number of bytes in the
927 * input string that were successfully converted, or %NULL.
928 * Even if the conversion was successful, this may be
929 * less than @len if there were partial characters
930 * at the end of the input. If the error
931 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
932 * stored will the byte offset after the last valid
934 * @bytes_written: the number of bytes stored in the output buffer (not
935 * including the terminating nul).
936 * @error: location to store the error occurring, or %NULL to ignore
937 * errors. Any of the errors in #GConvertError may occur.
939 * Converts a string from UTF-8 to the encoding used for strings by
940 * the C runtime (usually the same as that used by the operating
941 * system) in the <link linkend="setlocale">current locale</link>. On
942 * Windows this means the system codepage.
944 * Return value: A newly-allocated buffer containing the converted string,
945 * or %NULL on an error, and error will be set.
948 g_locale_from_utf8 (const gchar
*utf8string
,
951 gsize
*bytes_written
,
954 const gchar
*charset
;
956 if (g_get_charset (&charset
))
957 return strdup_len (utf8string
, len
, bytes_read
, bytes_written
, error
);
959 return g_convert (utf8string
, len
,
960 charset
, "UTF-8", bytes_read
, bytes_written
, error
);
963 #ifndef G_PLATFORM_WIN32
965 typedef struct _GFilenameCharsetCache GFilenameCharsetCache
;
967 struct _GFilenameCharsetCache
{
970 gchar
**filename_charsets
;
974 filename_charset_cache_free (gpointer data
)
976 GFilenameCharsetCache
*cache
= data
;
977 g_free (cache
->charset
);
978 g_strfreev (cache
->filename_charsets
);
983 * g_get_filename_charsets:
984 * @charsets: return location for the %NULL-terminated list of encoding names
986 * Determines the preferred character sets used for filenames.
987 * The first character set from the @charsets is the filename encoding, the
988 * subsequent character sets are used when trying to generate a displayable
989 * representation of a filename, see g_filename_display_name().
991 * On Unix, the character sets are determined by consulting the
992 * environment variables <envar>G_FILENAME_ENCODING</envar> and
993 * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
994 * used in the GLib API is always UTF-8 and said environment variables
997 * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list
998 * of character set names. The special token "@locale" is taken to
999 * mean the character set for the <link linkend="setlocale">current
1000 * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but
1001 * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current
1002 * locale is taken as the filename encoding. If neither environment variable
1003 * is set, UTF-8 is taken as the filename encoding, but the character
1004 * set of the current locale is also put in the list of encodings.
1006 * The returned @charsets belong to GLib and must not be freed.
1008 * Note that on Unix, regardless of the locale character set or
1009 * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present
1010 * on a system might be in any random encoding or just gibberish.
1012 * Return value: %TRUE if the filename encoding is UTF-8.
1017 g_get_filename_charsets (const gchar
***filename_charsets
)
1019 static GPrivate cache_private
= G_PRIVATE_INIT (filename_charset_cache_free
);
1020 GFilenameCharsetCache
*cache
= g_private_get (&cache_private
);
1021 const gchar
*charset
;
1025 cache
= g_new0 (GFilenameCharsetCache
, 1);
1026 g_private_set (&cache_private
, cache
);
1029 g_get_charset (&charset
);
1031 if (!(cache
->charset
&& strcmp (cache
->charset
, charset
) == 0))
1033 const gchar
*new_charset
;
1037 g_free (cache
->charset
);
1038 g_strfreev (cache
->filename_charsets
);
1039 cache
->charset
= g_strdup (charset
);
1041 p
= getenv ("G_FILENAME_ENCODING");
1042 if (p
!= NULL
&& p
[0] != '\0')
1044 cache
->filename_charsets
= g_strsplit (p
, ",", 0);
1045 cache
->is_utf8
= (strcmp (cache
->filename_charsets
[0], "UTF-8") == 0);
1047 for (i
= 0; cache
->filename_charsets
[i
]; i
++)
1049 if (strcmp ("@locale", cache
->filename_charsets
[i
]) == 0)
1051 g_get_charset (&new_charset
);
1052 g_free (cache
->filename_charsets
[i
]);
1053 cache
->filename_charsets
[i
] = g_strdup (new_charset
);
1057 else if (getenv ("G_BROKEN_FILENAMES") != NULL
)
1059 cache
->filename_charsets
= g_new0 (gchar
*, 2);
1060 cache
->is_utf8
= g_get_charset (&new_charset
);
1061 cache
->filename_charsets
[0] = g_strdup (new_charset
);
1065 cache
->filename_charsets
= g_new0 (gchar
*, 3);
1066 cache
->is_utf8
= TRUE
;
1067 cache
->filename_charsets
[0] = g_strdup ("UTF-8");
1068 if (!g_get_charset (&new_charset
))
1069 cache
->filename_charsets
[1] = g_strdup (new_charset
);
1073 if (filename_charsets
)
1074 *filename_charsets
= (const gchar
**)cache
->filename_charsets
;
1076 return cache
->is_utf8
;
1079 #else /* G_PLATFORM_WIN32 */
1082 g_get_filename_charsets (const gchar
***filename_charsets
)
1084 static const gchar
*charsets
[] = {
1090 /* On Windows GLib pretends that the filename charset is UTF-8 */
1091 if (filename_charsets
)
1092 *filename_charsets
= charsets
;
1098 /* Cygwin works like before */
1099 result
= g_get_charset (&(charsets
[0]));
1101 if (filename_charsets
)
1102 *filename_charsets
= charsets
;
1108 #endif /* G_PLATFORM_WIN32 */
1111 get_filename_charset (const gchar
**filename_charset
)
1113 const gchar
**charsets
;
1116 is_utf8
= g_get_filename_charsets (&charsets
);
1118 if (filename_charset
)
1119 *filename_charset
= charsets
[0];
1125 * g_filename_to_utf8:
1126 * @opsysstring: a string in the encoding for filenames
1127 * @len: the length of the string, or -1 if the string is
1128 * nul-terminated<footnoteref linkend="nul-unsafe"/>.
1129 * @bytes_read: location to store the number of bytes in the
1130 * input string that were successfully converted, or %NULL.
1131 * Even if the conversion was successful, this may be
1132 * less than @len if there were partial characters
1133 * at the end of the input. If the error
1134 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1135 * stored will the byte offset after the last valid
1137 * @bytes_written: the number of bytes stored in the output buffer (not
1138 * including the terminating nul).
1139 * @error: location to store the error occurring, or %NULL to ignore
1140 * errors. Any of the errors in #GConvertError may occur.
1142 * Converts a string which is in the encoding used by GLib for
1143 * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1144 * for filenames; on other platforms, this function indirectly depends on
1145 * the <link linkend="setlocale">current locale</link>.
1147 * Return value: The converted string, or %NULL on an error.
1150 g_filename_to_utf8 (const gchar
*opsysstring
,
1153 gsize
*bytes_written
,
1156 const gchar
*charset
;
1158 g_return_val_if_fail (opsysstring
!= NULL
, NULL
);
1160 if (get_filename_charset (&charset
))
1161 return strdup_len (opsysstring
, len
, bytes_read
, bytes_written
, error
);
1163 return g_convert (opsysstring
, len
,
1164 "UTF-8", charset
, bytes_read
, bytes_written
, error
);
1167 #if defined (G_OS_WIN32) && !defined (_WIN64)
1169 #undef g_filename_to_utf8
1171 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1172 * 64-bit versions as there should be no old deployed binaries that would use
1177 g_filename_to_utf8 (const gchar
*opsysstring
,
1180 gsize
*bytes_written
,
1183 const gchar
*charset
;
1185 g_return_val_if_fail (opsysstring
!= NULL
, NULL
);
1187 if (g_get_charset (&charset
))
1188 return strdup_len (opsysstring
, len
, bytes_read
, bytes_written
, error
);
1190 return g_convert (opsysstring
, len
,
1191 "UTF-8", charset
, bytes_read
, bytes_written
, error
);
1197 * g_filename_from_utf8:
1198 * @utf8string: a UTF-8 encoded string.
1199 * @len: the length of the string, or -1 if the string is
1201 * @bytes_read: (out) (allow-none): location to store the number of bytes in
1202 * the input string that were successfully converted, or %NULL.
1203 * Even if the conversion was successful, this may be
1204 * less than @len if there were partial characters
1205 * at the end of the input. If the error
1206 * #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1207 * stored will the byte offset after the last valid
1209 * @bytes_written: (out): the number of bytes stored in the output buffer (not
1210 * including the terminating nul).
1211 * @error: location to store the error occurring, or %NULL to ignore
1212 * errors. Any of the errors in #GConvertError may occur.
1214 * Converts a string from UTF-8 to the encoding GLib uses for
1215 * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1216 * on other platforms, this function indirectly depends on the
1217 * <link linkend="setlocale">current locale</link>.
1219 * Return value: (array length=bytes_written) (element-type guint8) (transfer full):
1220 * The converted string, or %NULL on an error.
1223 g_filename_from_utf8 (const gchar
*utf8string
,
1226 gsize
*bytes_written
,
1229 const gchar
*charset
;
1231 if (get_filename_charset (&charset
))
1232 return strdup_len (utf8string
, len
, bytes_read
, bytes_written
, error
);
1234 return g_convert (utf8string
, len
,
1235 charset
, "UTF-8", bytes_read
, bytes_written
, error
);
1238 #if defined (G_OS_WIN32) && !defined (_WIN64)
1240 #undef g_filename_from_utf8
1242 /* Binary compatibility version. Not for newly compiled code. */
1245 g_filename_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
);
1262 /* Test of haystack has the needle prefix, comparing case
1263 * insensitive. haystack may be UTF-8, but needle must
1264 * contain only ascii. */
1266 has_case_prefix (const gchar
*haystack
, const gchar
*needle
)
1270 /* Eat one character at a time. */
1275 g_ascii_tolower (*n
) == g_ascii_tolower (*h
))
1285 UNSAFE_ALL
= 0x1, /* Escape all unsafe characters */
1286 UNSAFE_ALLOW_PLUS
= 0x2, /* Allows '+' */
1287 UNSAFE_PATH
= 0x8, /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1288 UNSAFE_HOST
= 0x10, /* Allows '/' and ':' and '@' */
1289 UNSAFE_SLASHES
= 0x20 /* Allows all characters except for '/' and '%' */
1290 } UnsafeCharacterSet
;
1292 static const guchar acceptable
[96] = {
1293 /* A table of the ASCII chars from space (32) to DEL (127) */
1294 /* ! " # $ % & ' ( ) * + , - . / */
1295 0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1296 /* 0 1 2 3 4 5 6 7 8 9 : ; < = > ? */
1297 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1298 /* @ A B C D E F G H I J K L M N O */
1299 0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1300 /* P Q R S T U V W X Y Z [ \ ] ^ _ */
1301 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1302 /* ` a b c d e f g h i j k l m n o */
1303 0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1304 /* p q r s t u v w x y z { | } ~ DEL */
1305 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1308 static const gchar hex
[16] = "0123456789ABCDEF";
1310 /* Note: This escape function works on file: URIs, but if you want to
1311 * escape something else, please read RFC-2396 */
1313 g_escape_uri_string (const gchar
*string
,
1314 UnsafeCharacterSet mask
)
1316 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1323 UnsafeCharacterSet use_mask
;
1325 g_return_val_if_fail (mask
== UNSAFE_ALL
1326 || mask
== UNSAFE_ALLOW_PLUS
1327 || mask
== UNSAFE_PATH
1328 || mask
== UNSAFE_HOST
1329 || mask
== UNSAFE_SLASHES
, NULL
);
1333 for (p
= string
; *p
!= '\0'; p
++)
1336 if (!ACCEPTABLE (c
))
1340 result
= g_malloc (p
- string
+ unacceptable
* 2 + 1);
1343 for (q
= result
, p
= string
; *p
!= '\0'; p
++)
1347 if (!ACCEPTABLE (c
))
1349 *q
++ = '%'; /* means hex coming */
1364 g_escape_file_uri (const gchar
*hostname
,
1365 const gchar
*pathname
)
1367 char *escaped_hostname
= NULL
;
1372 char *p
, *backslash
;
1374 /* Turn backslashes into forward slashes. That's what Netscape
1375 * does, and they are actually more or less equivalent in Windows.
1378 pathname
= g_strdup (pathname
);
1379 p
= (char *) pathname
;
1381 while ((backslash
= strchr (p
, '\\')) != NULL
)
1388 if (hostname
&& *hostname
!= '\0')
1390 escaped_hostname
= g_escape_uri_string (hostname
, UNSAFE_HOST
);
1393 escaped_path
= g_escape_uri_string (pathname
, UNSAFE_PATH
);
1395 res
= g_strconcat ("file://",
1396 (escaped_hostname
) ? escaped_hostname
: "",
1397 (*escaped_path
!= '/') ? "/" : "",
1402 g_free ((char *) pathname
);
1405 g_free (escaped_hostname
);
1406 g_free (escaped_path
);
1412 unescape_character (const char *scanner
)
1417 first_digit
= g_ascii_xdigit_value (scanner
[0]);
1418 if (first_digit
< 0)
1421 second_digit
= g_ascii_xdigit_value (scanner
[1]);
1422 if (second_digit
< 0)
1425 return (first_digit
<< 4) | second_digit
;
1429 g_unescape_uri_string (const char *escaped
,
1431 const char *illegal_escaped_characters
,
1432 gboolean ascii_must_not_be_escaped
)
1434 const gchar
*in
, *in_end
;
1435 gchar
*out
, *result
;
1438 if (escaped
== NULL
)
1442 len
= strlen (escaped
);
1444 result
= g_malloc (len
+ 1);
1447 for (in
= escaped
, in_end
= escaped
+ len
; in
< in_end
; in
++)
1453 /* catch partial escape sequences past the end of the substring */
1454 if (in
+ 3 > in_end
)
1457 c
= unescape_character (in
+ 1);
1459 /* catch bad escape sequences and NUL characters */
1463 /* catch escaped ASCII */
1464 if (ascii_must_not_be_escaped
&& c
<= 0x7F)
1467 /* catch other illegal escaped characters */
1468 if (strchr (illegal_escaped_characters
, c
) != NULL
)
1477 g_assert (out
- result
<= len
);
1490 is_asciialphanum (gunichar c
)
1492 return c
<= 0x7F && g_ascii_isalnum (c
);
1496 is_asciialpha (gunichar c
)
1498 return c
<= 0x7F && g_ascii_isalpha (c
);
1501 /* allows an empty string */
1503 hostname_validate (const char *hostname
)
1506 gunichar c
, first_char
, last_char
;
1513 /* read in a label */
1514 c
= g_utf8_get_char (p
);
1515 p
= g_utf8_next_char (p
);
1516 if (!is_asciialphanum (c
))
1522 c
= g_utf8_get_char (p
);
1523 p
= g_utf8_next_char (p
);
1525 while (is_asciialphanum (c
) || c
== '-');
1526 if (last_char
== '-')
1529 /* if that was the last label, check that it was a toplabel */
1530 if (c
== '\0' || (c
== '.' && *p
== '\0'))
1531 return is_asciialpha (first_char
);
1538 * g_filename_from_uri:
1539 * @uri: a uri describing a filename (escaped, encoded in ASCII).
1540 * @hostname: (out) (allow-none): Location to store hostname for the URI, or %NULL.
1541 * If there is no hostname in the URI, %NULL will be
1542 * stored in this location.
1543 * @error: location to store the error occurring, or %NULL to ignore
1544 * errors. Any of the errors in #GConvertError may occur.
1546 * Converts an escaped ASCII-encoded URI to a local filename in the
1547 * encoding used for filenames.
1549 * Return value: (type filename): a newly-allocated string holding
1550 * the resulting filename, or %NULL on an error.
1553 g_filename_from_uri (const gchar
*uri
,
1557 const char *path_part
;
1558 const char *host_part
;
1559 char *unescaped_hostname
;
1570 if (!has_case_prefix (uri
, "file:/"))
1572 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1573 _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1578 path_part
= uri
+ strlen ("file:");
1580 if (strchr (path_part
, '#') != NULL
)
1582 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1583 _("The local file URI '%s' may not include a '#'"),
1588 if (has_case_prefix (path_part
, "///"))
1590 else if (has_case_prefix (path_part
, "//"))
1593 host_part
= path_part
;
1595 path_part
= strchr (path_part
, '/');
1597 if (path_part
== NULL
)
1599 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1600 _("The URI '%s' is invalid"),
1605 unescaped_hostname
= g_unescape_uri_string (host_part
, path_part
- host_part
, "", TRUE
);
1607 if (unescaped_hostname
== NULL
||
1608 !hostname_validate (unescaped_hostname
))
1610 g_free (unescaped_hostname
);
1611 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1612 _("The hostname of the URI '%s' is invalid"),
1618 *hostname
= unescaped_hostname
;
1620 g_free (unescaped_hostname
);
1623 filename
= g_unescape_uri_string (path_part
, -1, "/", FALSE
);
1625 if (filename
== NULL
)
1627 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_BAD_URI
,
1628 _("The URI '%s' contains invalidly escaped characters"),
1635 /* Drop localhost */
1636 if (hostname
&& *hostname
!= NULL
&&
1637 g_ascii_strcasecmp (*hostname
, "localhost") == 0)
1643 /* Turn slashes into backslashes, because that's the canonical spelling */
1645 while ((slash
= strchr (p
, '/')) != NULL
)
1651 /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1652 * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1653 * the filename from the drive letter.
1655 if (g_ascii_isalpha (filename
[1]))
1657 if (filename
[2] == ':')
1659 else if (filename
[2] == '|')
1667 result
= g_strdup (filename
+ offs
);
1673 #if defined (G_OS_WIN32) && !defined (_WIN64)
1675 #undef g_filename_from_uri
1678 g_filename_from_uri (const gchar
*uri
,
1682 gchar
*utf8_filename
;
1683 gchar
*retval
= NULL
;
1685 utf8_filename
= g_filename_from_uri_utf8 (uri
, hostname
, error
);
1688 retval
= g_locale_from_utf8 (utf8_filename
, -1, NULL
, NULL
, error
);
1689 g_free (utf8_filename
);
1697 * g_filename_to_uri:
1698 * @filename: an absolute filename specified in the GLib file name encoding,
1699 * which is the on-disk file name bytes on Unix, and UTF-8 on
1701 * @hostname: (allow-none): A UTF-8 encoded hostname, or %NULL for none.
1702 * @error: location to store the error occurring, or %NULL to ignore
1703 * errors. Any of the errors in #GConvertError may occur.
1705 * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1706 * component following Section 3.3. of RFC 2396.
1708 * Return value: a newly-allocated string holding the resulting
1709 * URI, or %NULL on an error.
1712 g_filename_to_uri (const gchar
*filename
,
1713 const gchar
*hostname
,
1718 g_return_val_if_fail (filename
!= NULL
, NULL
);
1720 if (!g_path_is_absolute (filename
))
1722 g_set_error (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH
,
1723 _("The pathname '%s' is not an absolute path"),
1729 !(g_utf8_validate (hostname
, -1, NULL
)
1730 && hostname_validate (hostname
)))
1732 g_set_error_literal (error
, G_CONVERT_ERROR
, G_CONVERT_ERROR_ILLEGAL_SEQUENCE
,
1733 _("Invalid hostname"));
1738 /* Don't use localhost unnecessarily */
1739 if (hostname
&& g_ascii_strcasecmp (hostname
, "localhost") == 0)
1743 escaped_uri
= g_escape_file_uri (hostname
, filename
);
1748 #if defined (G_OS_WIN32) && !defined (_WIN64)
1750 #undef g_filename_to_uri
1753 g_filename_to_uri (const gchar
*filename
,
1754 const gchar
*hostname
,
1757 gchar
*utf8_filename
;
1758 gchar
*retval
= NULL
;
1760 utf8_filename
= g_locale_to_utf8 (filename
, -1, NULL
, NULL
, error
);
1764 retval
= g_filename_to_uri_utf8 (utf8_filename
, hostname
, error
);
1765 g_free (utf8_filename
);
1774 * g_uri_list_extract_uris:
1775 * @uri_list: an URI list
1777 * Splits an URI list conforming to the text/uri-list
1778 * mime type defined in RFC 2483 into individual URIs,
1779 * discarding any comments. The URIs are not validated.
1781 * Returns: (transfer full): a newly allocated %NULL-terminated list
1782 * of strings holding the individual URIs. The array should be freed
1783 * with g_strfreev().
1788 g_uri_list_extract_uris (const gchar
*uri_list
)
1799 /* We don't actually try to validate the URI according to RFC
1800 * 2396, or even check for allowed characters - we just ignore
1801 * comments and trim whitespace off the ends. We also
1802 * allow LF delimination as well as the specified CRLF.
1804 * We do allow comments like specified in RFC 2483.
1810 while (g_ascii_isspace (*p
))
1814 while (*q
&& (*q
!= '\n') && (*q
!= '\r'))
1820 while (q
> p
&& g_ascii_isspace (*q
))
1825 uris
= g_slist_prepend (uris
, g_strndup (p
, q
- p
+ 1));
1830 p
= strchr (p
, '\n');
1835 result
= g_new (gchar
*, n_uris
+ 1);
1837 result
[n_uris
--] = NULL
;
1838 for (u
= uris
; u
; u
= u
->next
)
1839 result
[n_uris
--] = u
->data
;
1841 g_slist_free (uris
);
1847 * g_filename_display_basename:
1848 * @filename: an absolute pathname in the GLib file name encoding
1850 * Returns the display basename for the particular filename, guaranteed
1851 * to be valid UTF-8. The display name might not be identical to the filename,
1852 * for instance there might be problems converting it to UTF-8, and some files
1853 * can be translated in the display.
1855 * If GLib cannot make sense of the encoding of @filename, as a last resort it
1856 * replaces unknown characters with U+FFFD, the Unicode replacement character.
1857 * You can search the result for the UTF-8 encoding of this character (which is
1858 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
1861 * You must pass the whole absolute pathname to this functions so that
1862 * translation of well known locations can be done.
1864 * This function is preferred over g_filename_display_name() if you know the
1865 * whole path, as it allows translation.
1867 * Return value: a newly allocated string containing
1868 * a rendition of the basename of the filename in valid UTF-8
1873 g_filename_display_basename (const gchar
*filename
)
1878 g_return_val_if_fail (filename
!= NULL
, NULL
);
1880 basename
= g_path_get_basename (filename
);
1881 display_name
= g_filename_display_name (basename
);
1883 return display_name
;
1887 * g_filename_display_name:
1888 * @filename: a pathname hopefully in the GLib file name encoding
1890 * Converts a filename into a valid UTF-8 string. The conversion is
1891 * not necessarily reversible, so you should keep the original around
1892 * and use the return value of this function only for display purposes.
1893 * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL
1894 * even if the filename actually isn't in the GLib file name encoding.
1896 * If GLib cannot make sense of the encoding of @filename, as a last resort it
1897 * replaces unknown characters with U+FFFD, the Unicode replacement character.
1898 * You can search the result for the UTF-8 encoding of this character (which is
1899 * "\357\277\275" in octal notation) to find out if @filename was in an invalid
1902 * If you know the whole pathname of the file you should use
1903 * g_filename_display_basename(), since that allows location-based
1904 * translation of filenames.
1906 * Return value: a newly allocated string containing
1907 * a rendition of the filename in valid UTF-8
1912 g_filename_display_name (const gchar
*filename
)
1915 const gchar
**charsets
;
1916 gchar
*display_name
= NULL
;
1919 is_utf8
= g_get_filename_charsets (&charsets
);
1923 if (g_utf8_validate (filename
, -1, NULL
))
1924 display_name
= g_strdup (filename
);
1929 /* Try to convert from the filename charsets to UTF-8.
1930 * Skip the first charset if it is UTF-8.
1932 for (i
= is_utf8
? 1 : 0; charsets
[i
]; i
++)
1934 display_name
= g_convert (filename
, -1, "UTF-8", charsets
[i
],
1942 /* if all conversions failed, we replace invalid UTF-8
1943 * by a question mark
1946 display_name
= _g_utf8_make_valid (filename
);
1948 return display_name
;