Remove all uses of G_CONST_RETURN
[platform/upstream/glib.git] / glib / gconvert.c
1 /* GLIB - Library of useful routines for C programming
2  *
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>
6  *
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.
11  *
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.
16  *
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.
21  */
22
23 #include "config.h"
24 #include "glibconfig.h"
25
26 #ifndef G_OS_WIN32
27 #include <iconv.h>
28 #endif
29 #include <errno.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <stdlib.h>
33
34 #ifdef G_OS_WIN32
35 #include "win_iconv.c"
36 #endif
37
38 #ifdef G_PLATFORM_WIN32
39 #define STRICT
40 #include <windows.h>
41 #undef STRICT
42 #endif
43
44 #include "gconvert.h"
45
46 #include "gprintfint.h"
47 #include "gslist.h"
48 #include "gstrfuncs.h"
49 #include "gtestutils.h"
50 #include "gthread.h"
51 #include "gthreadprivate.h"
52 #include "gunicode.h"
53
54 #ifdef NEED_ICONV_CACHE
55 #include "glist.h"
56 #include "ghash.h"
57 #endif
58
59 #include "glibintl.h"
60
61 #if defined(USE_LIBICONV_GNU) && !defined (_LIBICONV_H)
62 #error GNU libiconv in use but included iconv.h not from libiconv
63 #endif
64 #if !defined(USE_LIBICONV_GNU) && defined (_LIBICONV_H)
65 #error GNU libiconv not in use but included iconv.h is from libiconv
66 #endif
67
68
69 /**
70  * SECTION:conversions
71  * @title: Character Set Conversion
72  * @short_description: Convert strings between different character sets
73  *
74  * The g_convert() family of function wraps the functionality of iconv(). In
75  * addition to pure character set conversions, GLib has functions to deal
76  * with the extra complications of encodings for file names.
77  *
78  * <refsect2 id="file-name-encodings">
79  * <title>File Name Encodings</title>
80  * <para>
81  * Historically, Unix has not had a defined encoding for file
82  * names:  a file name is valid as long as it does not have path
83  * separators in it ("/").  However, displaying file names may
84  * require conversion:  from the character set in which they were
85  * created, to the character set in which the application
86  * operates.  Consider the Spanish file name
87  * "<filename>Presentaci&oacute;n.sxi</filename>".  If the
88  * application which created it uses ISO-8859-1 for its encoding,
89  * </para>
90  * <programlisting id="filename-iso8859-1">
91  * Character:  P  r  e  s  e  n  t  a  c  i  &oacute;  n  .  s  x  i
92  * Hex code:   50 72 65 73 65 6e 74 61 63 69 f3 6e 2e 73 78 69
93  * </programlisting>
94  * <para>
95  * However, if the application use UTF-8, the actual file name on
96  * disk would look like this:
97  * </para>
98  * <programlisting id="filename-utf-8">
99  * Character:  P  r  e  s  e  n  t  a  c  i  &oacute;     n  .  s  x  i
100  * Hex code:   50 72 65 73 65 6e 74 61 63 69 c3 b3 6e 2e 73 78 69
101  * </programlisting>
102  * <para>
103  * Glib uses UTF-8 for its strings, and GUI toolkits like GTK+
104  * that use Glib do the same thing.  If you get a file name from
105  * the file system, for example, from readdir(3) or from g_dir_read_name(),
106  * and you wish to display the file name to the user, you
107  * <emphasis>will</emphasis> need to convert it into UTF-8.  The
108  * opposite case is when the user types the name of a file he
109  * wishes to save:  the toolkit will give you that string in
110  * UTF-8 encoding, and you will need to convert it to the
111  * character set used for file names before you can create the
112  * file with open(2) or fopen(3).
113  * </para>
114  * <para>
115  * By default, Glib assumes that file names on disk are in UTF-8
116  * encoding.  This is a valid assumption for file systems which
117  * were created relatively recently:  most applications use UTF-8
118  * encoding for their strings, and that is also what they use for
119  * the file names they create.  However, older file systems may
120  * still contain file names created in "older" encodings, such as
121  * ISO-8859-1. In this case, for compatibility reasons, you may
122  * want to instruct Glib to use that particular encoding for file
123  * names rather than UTF-8.  You can do this by specifying the
124  * encoding for file names in the <link
125  * linkend="G_FILENAME_ENCODING"><envar>G_FILENAME_ENCODING</envar></link>
126  * environment variable.  For example, if your installation uses
127  * ISO-8859-1 for file names, you can put this in your
128  * <filename>~/.profile</filename>:
129  * </para>
130  * <programlisting>
131  * export G_FILENAME_ENCODING=ISO-8859-1
132  * </programlisting>
133  * <para>
134  * Glib provides the functions g_filename_to_utf8() and
135  * g_filename_from_utf8() to perform the necessary conversions. These
136  * functions convert file names from the encoding specified in
137  * <envar>G_FILENAME_ENCODING</envar> to UTF-8 and vice-versa.
138  * <xref linkend="file-name-encodings-diagram"/> illustrates how
139  * these functions are used to convert between UTF-8 and the
140  * encoding for file names in the file system.
141  * </para>
142  * <figure id="file-name-encodings-diagram">
143  * <title>Conversion between File Name Encodings</title>
144  * <graphic fileref="file-name-encodings.png" format="PNG"/>
145  * </figure>
146  * <refsect3 id="file-name-encodings-checklist">
147  * <title>Checklist for Application Writers</title>
148  * <para>
149  * This section is a practical summary of the detailed
150  * description above.  You can use this as a checklist of
151  * things to do to make sure your applications process file
152  * name encodings correctly.
153  * </para>
154  * <orderedlist>
155  * <listitem><para>
156  * If you get a file name from the file system from a function
157  * such as readdir(3) or gtk_file_chooser_get_filename(),
158  * you do not need to do any conversion to pass that
159  * file name to functions like open(2), rename(2), or
160  * fopen(3) &mdash; those are "raw" file names which the file
161  * system understands.
162  * </para></listitem>
163  * <listitem><para>
164  * If you need to display a file name, convert it to UTF-8 first by
165  * using g_filename_to_utf8(). If conversion fails, display a string like
166  * "<literal>Unknown file name</literal>". <emphasis>Do not</emphasis>
167  * convert this string back into the encoding used for file names if you
168  * wish to pass it to the file system; use the original file name instead.
169  * For example, the document window of a word processor could display
170  * "Unknown file name" in its title bar but still let the user save the
171  * file, as it would keep the raw file name internally. This can happen
172  * if the user has not set the <envar>G_FILENAME_ENCODING</envar>
173  * environment variable even though he has files whose names are not
174  * encoded in UTF-8.
175  * </para></listitem>
176  * <listitem><para>
177  * If your user interface lets the user type a file name for saving or
178  * renaming, convert it to the encoding used for file names in the file
179  * system by using g_filename_from_utf8(). Pass the converted file name
180  * to functions like fopen(3). If conversion fails, ask the user to enter
181  * a different file name. This can happen if the user types Japanese
182  * characters when <envar>G_FILENAME_ENCODING</envar> is set to
183  * <literal>ISO-8859-1</literal>, for example.
184  * </para></listitem>
185  * </orderedlist>
186  * </refsect3>
187  * </refsect2>
188  */
189
190 /* We try to terminate strings in unknown charsets with this many zero bytes
191  * to ensure that multibyte strings really are nul-terminated when we return
192  * them from g_convert() and friends.
193  */
194 #define NUL_TERMINATOR_LENGTH 4
195
196 GQuark 
197 g_convert_error_quark (void)
198 {
199   return g_quark_from_static_string ("g_convert_error");
200 }
201
202 static gboolean
203 try_conversion (const char *to_codeset,
204                 const char *from_codeset,
205                 iconv_t    *cd)
206 {
207   *cd = iconv_open (to_codeset, from_codeset);
208
209   if (*cd == (iconv_t)-1 && errno == EINVAL)
210     return FALSE;
211   else
212     return TRUE;
213 }
214
215 static gboolean
216 try_to_aliases (const char **to_aliases,
217                 const char  *from_codeset,
218                 iconv_t     *cd)
219 {
220   if (to_aliases)
221     {
222       const char **p = to_aliases;
223       while (*p)
224         {
225           if (try_conversion (*p, from_codeset, cd))
226             return TRUE;
227
228           p++;
229         }
230     }
231
232   return FALSE;
233 }
234
235 G_GNUC_INTERNAL extern const char ** 
236 _g_charset_get_aliases (const char *canonical_name);
237
238 /**
239  * g_iconv_open:
240  * @to_codeset: destination codeset
241  * @from_codeset: source codeset
242  * 
243  * Same as the standard UNIX routine iconv_open(), but
244  * may be implemented via libiconv on UNIX flavors that lack
245  * a native implementation.
246  * 
247  * GLib provides g_convert() and g_locale_to_utf8() which are likely
248  * more convenient than the raw iconv wrappers.
249  * 
250  * Return value: a "conversion descriptor", or (GIConv)-1 if
251  *  opening the converter failed.
252  **/
253 GIConv
254 g_iconv_open (const gchar  *to_codeset,
255               const gchar  *from_codeset)
256 {
257   iconv_t cd;
258   
259   if (!try_conversion (to_codeset, from_codeset, &cd))
260     {
261       const char **to_aliases = _g_charset_get_aliases (to_codeset);
262       const char **from_aliases = _g_charset_get_aliases (from_codeset);
263
264       if (from_aliases)
265         {
266           const char **p = from_aliases;
267           while (*p)
268             {
269               if (try_conversion (to_codeset, *p, &cd))
270                 goto out;
271
272               if (try_to_aliases (to_aliases, *p, &cd))
273                 goto out;
274
275               p++;
276             }
277         }
278
279       if (try_to_aliases (to_aliases, from_codeset, &cd))
280         goto out;
281     }
282
283  out:
284   return (cd == (iconv_t)-1) ? (GIConv)-1 : (GIConv)cd;
285 }
286
287 /**
288  * g_iconv:
289  * @converter: conversion descriptor from g_iconv_open()
290  * @inbuf: bytes to convert
291  * @inbytes_left: inout parameter, bytes remaining to convert in @inbuf
292  * @outbuf: converted output bytes
293  * @outbytes_left: inout parameter, bytes available to fill in @outbuf
294  * 
295  * Same as the standard UNIX routine iconv(), but
296  * may be implemented via libiconv on UNIX flavors that lack
297  * a native implementation.
298  *
299  * GLib provides g_convert() and g_locale_to_utf8() which are likely
300  * more convenient than the raw iconv wrappers.
301  * 
302  * Return value: count of non-reversible conversions, or -1 on error
303  **/
304 gsize 
305 g_iconv (GIConv   converter,
306          gchar  **inbuf,
307          gsize   *inbytes_left,
308          gchar  **outbuf,
309          gsize   *outbytes_left)
310 {
311   iconv_t cd = (iconv_t)converter;
312
313   return iconv (cd, inbuf, inbytes_left, outbuf, outbytes_left);
314 }
315
316 /**
317  * g_iconv_close:
318  * @converter: a conversion descriptor from g_iconv_open()
319  *
320  * Same as the standard UNIX routine iconv_close(), but
321  * may be implemented via libiconv on UNIX flavors that lack
322  * a native implementation. Should be called to clean up
323  * the conversion descriptor from g_iconv_open() when
324  * you are done converting things.
325  *
326  * GLib provides g_convert() and g_locale_to_utf8() which are likely
327  * more convenient than the raw iconv wrappers.
328  * 
329  * Return value: -1 on error, 0 on success
330  **/
331 gint
332 g_iconv_close (GIConv converter)
333 {
334   iconv_t cd = (iconv_t)converter;
335
336   return iconv_close (cd);
337 }
338
339
340 #ifdef NEED_ICONV_CACHE
341
342 #define ICONV_CACHE_SIZE   (16)
343
344 struct _iconv_cache_bucket {
345   gchar *key;
346   guint32 refcount;
347   gboolean used;
348   GIConv cd;
349 };
350
351 static GList *iconv_cache_list;
352 static GHashTable *iconv_cache;
353 static GHashTable *iconv_open_hash;
354 static guint iconv_cache_size = 0;
355 G_LOCK_DEFINE_STATIC (iconv_cache_lock);
356
357 /* caller *must* hold the iconv_cache_lock */
358 static void
359 iconv_cache_init (void)
360 {
361   static gboolean initialized = FALSE;
362   
363   if (initialized)
364     return;
365   
366   iconv_cache_list = NULL;
367   iconv_cache = g_hash_table_new (g_str_hash, g_str_equal);
368   iconv_open_hash = g_hash_table_new (g_direct_hash, g_direct_equal);
369   
370   initialized = TRUE;
371 }
372
373
374 /*
375  * iconv_cache_bucket_new:
376  * @key: cache key
377  * @cd: iconv descriptor
378  *
379  * Creates a new cache bucket, inserts it into the cache and
380  * increments the cache size.
381  *
382  * This assumes ownership of @key.
383  *
384  * Returns a pointer to the newly allocated cache bucket.
385  **/
386 static struct _iconv_cache_bucket *
387 iconv_cache_bucket_new (gchar *key, GIConv cd)
388 {
389   struct _iconv_cache_bucket *bucket;
390   
391   bucket = g_new (struct _iconv_cache_bucket, 1);
392   bucket->key = key;
393   bucket->refcount = 1;
394   bucket->used = TRUE;
395   bucket->cd = cd;
396   
397   g_hash_table_insert (iconv_cache, bucket->key, bucket);
398   
399   /* FIXME: if we sorted the list so items with few refcounts were
400      first, then we could expire them faster in iconv_cache_expire_unused () */
401   iconv_cache_list = g_list_prepend (iconv_cache_list, bucket);
402   
403   iconv_cache_size++;
404   
405   return bucket;
406 }
407
408
409 /*
410  * iconv_cache_bucket_expire:
411  * @node: cache bucket's node
412  * @bucket: cache bucket
413  *
414  * Expires a single cache bucket @bucket. This should only ever be
415  * called on a bucket that currently has no used iconv descriptors
416  * open.
417  *
418  * @node is not a required argument. If @node is not supplied, we
419  * search for it ourselves.
420  **/
421 static void
422 iconv_cache_bucket_expire (GList *node, struct _iconv_cache_bucket *bucket)
423 {
424   g_hash_table_remove (iconv_cache, bucket->key);
425   
426   if (node == NULL)
427     node = g_list_find (iconv_cache_list, bucket);
428   
429   g_assert (node != NULL);
430   
431   if (node->prev)
432     {
433       node->prev->next = node->next;
434       if (node->next)
435         node->next->prev = node->prev;
436     }
437   else
438     {
439       iconv_cache_list = node->next;
440       if (node->next)
441         node->next->prev = NULL;
442     }
443   
444   g_list_free_1 (node);
445   
446   g_free (bucket->key);
447   g_iconv_close (bucket->cd);
448   g_free (bucket);
449   
450   iconv_cache_size--;
451 }
452
453
454 /*
455  * iconv_cache_expire_unused:
456  *
457  * Expires as many unused cache buckets as it needs to in order to get
458  * the total number of buckets < ICONV_CACHE_SIZE.
459  **/
460 static void
461 iconv_cache_expire_unused (void)
462 {
463   struct _iconv_cache_bucket *bucket;
464   GList *node, *next;
465   
466   node = iconv_cache_list;
467   while (node && iconv_cache_size >= ICONV_CACHE_SIZE)
468     {
469       next = node->next;
470       
471       bucket = node->data;
472       if (bucket->refcount == 0)
473         iconv_cache_bucket_expire (node, bucket);
474       
475       node = next;
476     }
477 }
478
479 static GIConv
480 open_converter (const gchar *to_codeset,
481                 const gchar *from_codeset,
482                 GError     **error)
483 {
484   struct _iconv_cache_bucket *bucket;
485   gchar *key, *dyn_key, auto_key[80];
486   GIConv cd;
487   gsize len_from_codeset, len_to_codeset;
488   
489   /* create our key */
490   len_from_codeset = strlen (from_codeset);
491   len_to_codeset = strlen (to_codeset);
492   if (len_from_codeset + len_to_codeset + 2 < sizeof (auto_key))
493     {
494       key = auto_key;
495       dyn_key = NULL;
496     }
497   else
498     key = dyn_key = g_malloc (len_from_codeset + len_to_codeset + 2);
499   memcpy (key, from_codeset, len_from_codeset);
500   key[len_from_codeset] = ':';
501   strcpy (key + len_from_codeset + 1, to_codeset);
502
503   G_LOCK (iconv_cache_lock);
504   
505   /* make sure the cache has been initialized */
506   iconv_cache_init ();
507   
508   bucket = g_hash_table_lookup (iconv_cache, key);
509   if (bucket)
510     {
511       g_free (dyn_key);
512
513       if (bucket->used)
514         {
515           cd = g_iconv_open (to_codeset, from_codeset);
516           if (cd == (GIConv) -1)
517             goto error;
518         }
519       else
520         {
521           /* Apparently iconv on Solaris <= 7 segfaults if you pass in
522            * NULL for anything but inbuf; work around that. (NULL outbuf
523            * or NULL *outbuf is allowed by Unix98.)
524            */
525           gsize inbytes_left = 0;
526           gchar *outbuf = NULL;
527           gsize outbytes_left = 0;
528                 
529           cd = bucket->cd;
530           bucket->used = TRUE;
531           
532           /* reset the descriptor */
533           g_iconv (cd, NULL, &inbytes_left, &outbuf, &outbytes_left);
534         }
535       
536       bucket->refcount++;
537     }
538   else
539     {
540       cd = g_iconv_open (to_codeset, from_codeset);
541       if (cd == (GIConv) -1) 
542         {
543           g_free (dyn_key);
544           goto error;
545         }
546       
547       iconv_cache_expire_unused ();
548
549       bucket = iconv_cache_bucket_new (dyn_key ? dyn_key : g_strdup (key), cd);
550     }
551   
552   g_hash_table_insert (iconv_open_hash, cd, bucket->key);
553   
554   G_UNLOCK (iconv_cache_lock);
555   
556   return cd;
557   
558  error:
559   
560   G_UNLOCK (iconv_cache_lock);
561   
562   /* Something went wrong.  */
563   if (error)
564     {
565       if (errno == EINVAL)
566         g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
567                      _("Conversion from character set '%s' to '%s' is not supported"),
568                      from_codeset, to_codeset);
569       else
570         g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
571                      _("Could not open converter from '%s' to '%s'"),
572                      from_codeset, to_codeset);
573     }
574   
575   return cd;
576 }
577
578 static int
579 close_converter (GIConv converter)
580 {
581   struct _iconv_cache_bucket *bucket;
582   const gchar *key;
583   GIConv cd;
584   
585   cd = converter;
586   
587   if (cd == (GIConv) -1)
588     return 0;
589   
590   G_LOCK (iconv_cache_lock);
591   
592   key = g_hash_table_lookup (iconv_open_hash, cd);
593   if (key)
594     {
595       g_hash_table_remove (iconv_open_hash, cd);
596       
597       bucket = g_hash_table_lookup (iconv_cache, key);
598       g_assert (bucket);
599       
600       bucket->refcount--;
601       
602       if (cd == bucket->cd)
603         bucket->used = FALSE;
604       else
605         g_iconv_close (cd);
606       
607       if (!bucket->refcount && iconv_cache_size > ICONV_CACHE_SIZE)
608         {
609           /* expire this cache bucket */
610           iconv_cache_bucket_expire (NULL, bucket);
611         }
612     }
613   else
614     {
615       G_UNLOCK (iconv_cache_lock);
616       
617       g_warning ("This iconv context wasn't opened using open_converter");
618       
619       return g_iconv_close (converter);
620     }
621   
622   G_UNLOCK (iconv_cache_lock);
623   
624   return 0;
625 }
626
627 #else  /* !NEED_ICONV_CACHE */
628
629 static GIConv
630 open_converter (const gchar *to_codeset,
631                 const gchar *from_codeset,
632                 GError     **error)
633 {
634   GIConv cd;
635
636   cd = g_iconv_open (to_codeset, from_codeset);
637
638   if (cd == (GIConv) -1)
639     {
640       /* Something went wrong.  */
641       if (error)
642         {
643           if (errno == EINVAL)
644             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NO_CONVERSION,
645                          _("Conversion from character set '%s' to '%s' is not supported"),
646                          from_codeset, to_codeset);
647           else
648             g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
649                          _("Could not open converter from '%s' to '%s'"),
650                          from_codeset, to_codeset);
651         }
652     }
653   
654   return cd;
655 }
656
657 static int
658 close_converter (GIConv cd)
659 {
660   if (cd == (GIConv) -1)
661     return 0;
662   
663   return g_iconv_close (cd);  
664 }
665
666 #endif /* NEED_ICONV_CACHE */
667
668 /**
669  * g_convert_with_iconv:
670  * @str:           the string to convert
671  * @len:           the length of the string, or -1 if the string is 
672  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
673  * @converter:     conversion descriptor from g_iconv_open()
674  * @bytes_read:    location to store the number of bytes in the
675  *                 input string that were successfully converted, or %NULL.
676  *                 Even if the conversion was successful, this may be 
677  *                 less than @len if there were partial characters
678  *                 at the end of the input. If the error
679  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
680  *                 stored will the byte offset after the last valid
681  *                 input sequence.
682  * @bytes_written: the number of bytes stored in the output buffer (not 
683  *                 including the terminating nul).
684  * @error:         location to store the error occuring, or %NULL to ignore
685  *                 errors. Any of the errors in #GConvertError may occur.
686  *
687  * Converts a string from one character set to another. 
688  * 
689  * Note that you should use g_iconv() for streaming 
690  * conversions<footnote id="streaming-state">
691  *  <para>
692  * Despite the fact that @byes_read can return information about partial 
693  * characters, the <literal>g_convert_...</literal> functions
694  * are not generally suitable for streaming. If the underlying converter 
695  * being used maintains internal state, then this won't be preserved 
696  * across successive calls to g_convert(), g_convert_with_iconv() or 
697  * g_convert_with_fallback(). (An example of this is the GNU C converter 
698  * for CP1255 which does not emit a base character until it knows that 
699  * the next character is not a mark that could combine with the base 
700  * character.)
701  *  </para>
702  * </footnote>. 
703  *
704  * Return value: If the conversion was successful, a newly allocated
705  *               nul-terminated string, which must be freed with
706  *               g_free(). Otherwise %NULL and @error will be set.
707  **/
708 gchar*
709 g_convert_with_iconv (const gchar *str,
710                       gssize       len,
711                       GIConv       converter,
712                       gsize       *bytes_read, 
713                       gsize       *bytes_written, 
714                       GError     **error)
715 {
716   gchar *dest;
717   gchar *outp;
718   const gchar *p;
719   gsize inbytes_remaining;
720   gsize outbytes_remaining;
721   gsize err;
722   gsize outbuf_size;
723   gboolean have_error = FALSE;
724   gboolean done = FALSE;
725   gboolean reset = FALSE;
726   
727   g_return_val_if_fail (converter != (GIConv) -1, NULL);
728      
729   if (len < 0)
730     len = strlen (str);
731
732   p = str;
733   inbytes_remaining = len;
734   outbuf_size = len + NUL_TERMINATOR_LENGTH;
735   
736   outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
737   outp = dest = g_malloc (outbuf_size);
738
739   while (!done && !have_error)
740     {
741       if (reset)
742         err = g_iconv (converter, NULL, &inbytes_remaining, &outp, &outbytes_remaining);
743       else
744         err = g_iconv (converter, (char **)&p, &inbytes_remaining, &outp, &outbytes_remaining);
745
746       if (err == (gsize) -1)
747         {
748           switch (errno)
749             {
750             case EINVAL:
751               /* Incomplete text, do not report an error */
752               done = TRUE;
753               break;
754             case E2BIG:
755               {
756                 gsize used = outp - dest;
757                 
758                 outbuf_size *= 2;
759                 dest = g_realloc (dest, outbuf_size);
760                 
761                 outp = dest + used;
762                 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
763               }
764               break;
765             case EILSEQ:
766               if (error)
767                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
768                                      _("Invalid byte sequence in conversion input"));
769               have_error = TRUE;
770               break;
771             default:
772               if (error)
773                 {
774                   int errsv = errno;
775
776                   g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
777                                _("Error during conversion: %s"),
778                                g_strerror (errsv));
779                 }
780               have_error = TRUE;
781               break;
782             }
783         }
784       else 
785         {
786           if (!reset)
787             {
788               /* call g_iconv with NULL inbuf to cleanup shift state */
789               reset = TRUE;
790               inbytes_remaining = 0;
791             }
792           else
793             done = TRUE;
794         }
795     }
796
797   memset (outp, 0, NUL_TERMINATOR_LENGTH);
798   
799   if (bytes_read)
800     *bytes_read = p - str;
801   else
802     {
803       if ((p - str) != len) 
804         {
805           if (!have_error)
806             {
807               if (error)
808                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
809                                      _("Partial character sequence at end of input"));
810               have_error = TRUE;
811             }
812         }
813     }
814
815   if (bytes_written)
816     *bytes_written = outp - dest;       /* Doesn't include '\0' */
817
818   if (have_error)
819     {
820       g_free (dest);
821       return NULL;
822     }
823   else
824     return dest;
825 }
826
827 /**
828  * g_convert:
829  * @str:           the string to convert
830  * @len:           the length of the string, or -1 if the string is 
831  *                 nul-terminated<footnote id="nul-unsafe">
832                      <para>
833                        Note that some encodings may allow nul bytes to 
834                        occur inside strings. In that case, using -1 for 
835                        the @len parameter is unsafe.
836                      </para>
837                    </footnote>. 
838  * @to_codeset:    name of character set into which to convert @str
839  * @from_codeset:  character set of @str.
840  * @bytes_read:    location to store the number of bytes in the
841  *                 input string that were successfully converted, or %NULL.
842  *                 Even if the conversion was successful, this may be 
843  *                 less than @len if there were partial characters
844  *                 at the end of the input. If the error
845  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
846  *                 stored will the byte offset after the last valid
847  *                 input sequence.
848  * @bytes_written: the number of bytes stored in the output buffer (not 
849  *                 including the terminating nul).
850  * @error:         location to store the error occuring, or %NULL to ignore
851  *                 errors. Any of the errors in #GConvertError may occur.
852  *
853  * Converts a string from one character set to another.
854  *
855  * Note that you should use g_iconv() for streaming 
856  * conversions<footnoteref linkend="streaming-state"/>.
857  *
858  * Return value: If the conversion was successful, a newly allocated
859  *               nul-terminated string, which must be freed with
860  *               g_free(). Otherwise %NULL and @error will be set.
861  **/
862 gchar*
863 g_convert (const gchar *str,
864            gssize       len,  
865            const gchar *to_codeset,
866            const gchar *from_codeset,
867            gsize       *bytes_read, 
868            gsize       *bytes_written, 
869            GError     **error)
870 {
871   gchar *res;
872   GIConv cd;
873
874   g_return_val_if_fail (str != NULL, NULL);
875   g_return_val_if_fail (to_codeset != NULL, NULL);
876   g_return_val_if_fail (from_codeset != NULL, NULL);
877   
878   cd = open_converter (to_codeset, from_codeset, error);
879
880   if (cd == (GIConv) -1)
881     {
882       if (bytes_read)
883         *bytes_read = 0;
884       
885       if (bytes_written)
886         *bytes_written = 0;
887       
888       return NULL;
889     }
890
891   res = g_convert_with_iconv (str, len, cd,
892                               bytes_read, bytes_written,
893                               error);
894
895   close_converter (cd);
896
897   return res;
898 }
899
900 /**
901  * g_convert_with_fallback:
902  * @str:          the string to convert
903  * @len:          the length of the string, or -1 if the string is 
904  *                nul-terminated<footnoteref linkend="nul-unsafe"/>. 
905  * @to_codeset:   name of character set into which to convert @str
906  * @from_codeset: character set of @str.
907  * @fallback:     UTF-8 string to use in place of character not
908  *                present in the target encoding. (The string must be
909  *                representable in the target encoding). 
910                   If %NULL, characters not in the target encoding will 
911                   be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
912  * @bytes_read:   location to store the number of bytes in the
913  *                input string that were successfully converted, or %NULL.
914  *                Even if the conversion was successful, this may be 
915  *                less than @len if there were partial characters
916  *                at the end of the input.
917  * @bytes_written: the number of bytes stored in the output buffer (not 
918  *                including the terminating nul).
919  * @error:        location to store the error occuring, or %NULL to ignore
920  *                errors. Any of the errors in #GConvertError may occur.
921  *
922  * Converts a string from one character set to another, possibly
923  * including fallback sequences for characters not representable
924  * in the output. Note that it is not guaranteed that the specification
925  * for the fallback sequences in @fallback will be honored. Some
926  * systems may do an approximate conversion from @from_codeset
927  * to @to_codeset in their iconv() functions, 
928  * in which case GLib will simply return that approximate conversion.
929  *
930  * Note that you should use g_iconv() for streaming 
931  * conversions<footnoteref linkend="streaming-state"/>.
932  *
933  * Return value: If the conversion was successful, a newly allocated
934  *               nul-terminated string, which must be freed with
935  *               g_free(). Otherwise %NULL and @error will be set.
936  **/
937 gchar*
938 g_convert_with_fallback (const gchar *str,
939                          gssize       len,    
940                          const gchar *to_codeset,
941                          const gchar *from_codeset,
942                          const gchar *fallback,
943                          gsize       *bytes_read,
944                          gsize       *bytes_written,
945                          GError     **error)
946 {
947   gchar *utf8;
948   gchar *dest;
949   gchar *outp;
950   const gchar *insert_str = NULL;
951   const gchar *p;
952   gsize inbytes_remaining;   
953   const gchar *save_p = NULL;
954   gsize save_inbytes = 0;
955   gsize outbytes_remaining; 
956   gsize err;
957   GIConv cd;
958   gsize outbuf_size;
959   gboolean have_error = FALSE;
960   gboolean done = FALSE;
961
962   GError *local_error = NULL;
963   
964   g_return_val_if_fail (str != NULL, NULL);
965   g_return_val_if_fail (to_codeset != NULL, NULL);
966   g_return_val_if_fail (from_codeset != NULL, NULL);
967      
968   if (len < 0)
969     len = strlen (str);
970   
971   /* Try an exact conversion; we only proceed if this fails
972    * due to an illegal sequence in the input string.
973    */
974   dest = g_convert (str, len, to_codeset, from_codeset, 
975                     bytes_read, bytes_written, &local_error);
976   if (!local_error)
977     return dest;
978
979   if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
980     {
981       g_propagate_error (error, local_error);
982       return NULL;
983     }
984   else
985     g_error_free (local_error);
986
987   local_error = NULL;
988   
989   /* No go; to proceed, we need a converter from "UTF-8" to
990    * to_codeset, and the string as UTF-8.
991    */
992   cd = open_converter (to_codeset, "UTF-8", error);
993   if (cd == (GIConv) -1)
994     {
995       if (bytes_read)
996         *bytes_read = 0;
997       
998       if (bytes_written)
999         *bytes_written = 0;
1000       
1001       return NULL;
1002     }
1003
1004   utf8 = g_convert (str, len, "UTF-8", from_codeset, 
1005                     bytes_read, &inbytes_remaining, error);
1006   if (!utf8)
1007     {
1008       close_converter (cd);
1009       if (bytes_written)
1010         *bytes_written = 0;
1011       return NULL;
1012     }
1013
1014   /* Now the heart of the code. We loop through the UTF-8 string, and
1015    * whenever we hit an offending character, we form fallback, convert
1016    * the fallback to the target codeset, and then go back to
1017    * converting the original string after finishing with the fallback.
1018    *
1019    * The variables save_p and save_inbytes store the input state
1020    * for the original string while we are converting the fallback
1021    */
1022   p = utf8;
1023
1024   outbuf_size = len + NUL_TERMINATOR_LENGTH;
1025   outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
1026   outp = dest = g_malloc (outbuf_size);
1027
1028   while (!done && !have_error)
1029     {
1030       gsize inbytes_tmp = inbytes_remaining;
1031       err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
1032       inbytes_remaining = inbytes_tmp;
1033
1034       if (err == (gsize) -1)
1035         {
1036           switch (errno)
1037             {
1038             case EINVAL:
1039               g_assert_not_reached();
1040               break;
1041             case E2BIG:
1042               {
1043                 gsize used = outp - dest;
1044
1045                 outbuf_size *= 2;
1046                 dest = g_realloc (dest, outbuf_size);
1047                 
1048                 outp = dest + used;
1049                 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
1050                 
1051                 break;
1052               }
1053             case EILSEQ:
1054               if (save_p)
1055                 {
1056                   /* Error converting fallback string - fatal
1057                    */
1058                   g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1059                                _("Cannot convert fallback '%s' to codeset '%s'"),
1060                                insert_str, to_codeset);
1061                   have_error = TRUE;
1062                   break;
1063                 }
1064               else if (p)
1065                 {
1066                   if (!fallback)
1067                     { 
1068                       gunichar ch = g_utf8_get_char (p);
1069                       insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
1070                                                     ch);
1071                     }
1072                   else
1073                     insert_str = fallback;
1074                   
1075                   save_p = g_utf8_next_char (p);
1076                   save_inbytes = inbytes_remaining - (save_p - p);
1077                   p = insert_str;
1078                   inbytes_remaining = strlen (p);
1079                   break;
1080                 }
1081               /* fall thru if p is NULL */
1082             default:
1083               {
1084                 int errsv = errno;
1085
1086                 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1087                              _("Error during conversion: %s"),
1088                              g_strerror (errsv));
1089               }
1090
1091               have_error = TRUE;
1092               break;
1093             }
1094         }
1095       else
1096         {
1097           if (save_p)
1098             {
1099               if (!fallback)
1100                 g_free ((gchar *)insert_str);
1101               p = save_p;
1102               inbytes_remaining = save_inbytes;
1103               save_p = NULL;
1104             }
1105           else if (p)
1106             {
1107               /* call g_iconv with NULL inbuf to cleanup shift state */
1108               p = NULL;
1109               inbytes_remaining = 0;
1110             }
1111           else
1112             done = TRUE;
1113         }
1114     }
1115
1116   /* Cleanup
1117    */
1118   memset (outp, 0, NUL_TERMINATOR_LENGTH);
1119   
1120   close_converter (cd);
1121
1122   if (bytes_written)
1123     *bytes_written = outp - dest;       /* Doesn't include '\0' */
1124
1125   g_free (utf8);
1126
1127   if (have_error)
1128     {
1129       if (save_p && !fallback)
1130         g_free ((gchar *)insert_str);
1131       g_free (dest);
1132       return NULL;
1133     }
1134   else
1135     return dest;
1136 }
1137
1138 /*
1139  * g_locale_to_utf8
1140  *
1141  * 
1142  */
1143
1144 static gchar *
1145 strdup_len (const gchar *string,
1146             gssize       len,
1147             gsize       *bytes_written,
1148             gsize       *bytes_read,
1149             GError      **error)
1150          
1151 {
1152   gsize real_len;
1153
1154   if (!g_utf8_validate (string, len, NULL))
1155     {
1156       if (bytes_read)
1157         *bytes_read = 0;
1158       if (bytes_written)
1159         *bytes_written = 0;
1160
1161       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1162                            _("Invalid byte sequence in conversion input"));
1163       return NULL;
1164     }
1165   
1166   if (len < 0)
1167     real_len = strlen (string);
1168   else
1169     {
1170       real_len = 0;
1171       
1172       while (real_len < len && string[real_len])
1173         real_len++;
1174     }
1175   
1176   if (bytes_read)
1177     *bytes_read = real_len;
1178   if (bytes_written)
1179     *bytes_written = real_len;
1180
1181   return g_strndup (string, real_len);
1182 }
1183
1184 /**
1185  * g_locale_to_utf8:
1186  * @opsysstring:   a string in the encoding of the current locale. On Windows
1187  *                 this means the system codepage.
1188  * @len:           the length of the string, or -1 if the string is
1189  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1190  * @bytes_read:    location to store the number of bytes in the
1191  *                 input string that were successfully converted, or %NULL.
1192  *                 Even if the conversion was successful, this may be 
1193  *                 less than @len if there were partial characters
1194  *                 at the end of the input. If the error
1195  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1196  *                 stored will the byte offset after the last valid
1197  *                 input sequence.
1198  * @bytes_written: the number of bytes stored in the output buffer (not 
1199  *                 including the terminating nul).
1200  * @error:         location to store the error occuring, or %NULL to ignore
1201  *                 errors. Any of the errors in #GConvertError may occur.
1202  * 
1203  * Converts a string which is in the encoding used for strings by
1204  * the C runtime (usually the same as that used by the operating
1205  * system) in the <link linkend="setlocale">current locale</link> into a
1206  * UTF-8 string.
1207  * 
1208  * Return value: The converted string, or %NULL on an error.
1209  **/
1210 gchar *
1211 g_locale_to_utf8 (const gchar  *opsysstring,
1212                   gssize        len,            
1213                   gsize        *bytes_read,    
1214                   gsize        *bytes_written,
1215                   GError      **error)
1216 {
1217   const char *charset;
1218
1219   if (g_get_charset (&charset))
1220     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1221   else
1222     return g_convert (opsysstring, len, 
1223                       "UTF-8", charset, bytes_read, bytes_written, error);
1224 }
1225
1226 /**
1227  * g_locale_from_utf8:
1228  * @utf8string:    a UTF-8 encoded string 
1229  * @len:           the length of the string, or -1 if the string is
1230  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1231  * @bytes_read:    location to store the number of bytes in the
1232  *                 input string that were successfully converted, or %NULL.
1233  *                 Even if the conversion was successful, this may be 
1234  *                 less than @len if there were partial characters
1235  *                 at the end of the input. If the error
1236  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1237  *                 stored will the byte offset after the last valid
1238  *                 input sequence.
1239  * @bytes_written: the number of bytes stored in the output buffer (not 
1240  *                 including the terminating nul).
1241  * @error:         location to store the error occuring, or %NULL to ignore
1242  *                 errors. Any of the errors in #GConvertError may occur.
1243  * 
1244  * Converts a string from UTF-8 to the encoding used for strings by
1245  * the C runtime (usually the same as that used by the operating
1246  * system) in the <link linkend="setlocale">current locale</link>. On
1247  * Windows this means the system codepage.
1248  * 
1249  * Return value: The converted string, or %NULL on an error.
1250  **/
1251 gchar *
1252 g_locale_from_utf8 (const gchar *utf8string,
1253                     gssize       len,            
1254                     gsize       *bytes_read,    
1255                     gsize       *bytes_written,
1256                     GError     **error)
1257 {
1258   const gchar *charset;
1259
1260   if (g_get_charset (&charset))
1261     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1262   else
1263     return g_convert (utf8string, len,
1264                       charset, "UTF-8", bytes_read, bytes_written, error);
1265 }
1266
1267 #ifndef G_PLATFORM_WIN32
1268
1269 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1270
1271 struct _GFilenameCharsetCache {
1272   gboolean is_utf8;
1273   gchar *charset;
1274   gchar **filename_charsets;
1275 };
1276
1277 static void
1278 filename_charset_cache_free (gpointer data)
1279 {
1280   GFilenameCharsetCache *cache = data;
1281   g_free (cache->charset);
1282   g_strfreev (cache->filename_charsets);
1283   g_free (cache);
1284 }
1285
1286 /**
1287  * g_get_filename_charsets:
1288  * @charsets: return location for the %NULL-terminated list of encoding names
1289  *
1290  * Determines the preferred character sets used for filenames.
1291  * The first character set from the @charsets is the filename encoding, the
1292  * subsequent character sets are used when trying to generate a displayable
1293  * representation of a filename, see g_filename_display_name().
1294  *
1295  * On Unix, the character sets are determined by consulting the
1296  * environment variables <envar>G_FILENAME_ENCODING</envar> and
1297  * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1298  * used in the GLib API is always UTF-8 and said environment variables
1299  * have no effect.
1300  *
1301  * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list 
1302  * of character set names. The special token "&commat;locale" is taken to 
1303  * mean the character set for the <link linkend="setlocale">current 
1304  * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but 
1305  * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current 
1306  * locale is taken as the filename encoding. If neither environment variable 
1307  * is set, UTF-8 is taken as the filename encoding, but the character
1308  * set of the current locale is also put in the list of encodings.
1309  *
1310  * The returned @charsets belong to GLib and must not be freed.
1311  *
1312  * Note that on Unix, regardless of the locale character set or
1313  * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present 
1314  * on a system might be in any random encoding or just gibberish.
1315  *
1316  * Return value: %TRUE if the filename encoding is UTF-8.
1317  * 
1318  * Since: 2.6
1319  */
1320 gboolean
1321 g_get_filename_charsets (const gchar ***filename_charsets)
1322 {
1323   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1324   GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1325   const gchar *charset;
1326
1327   if (!cache)
1328     {
1329       cache = g_new0 (GFilenameCharsetCache, 1);
1330       g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1331     }
1332
1333   g_get_charset (&charset);
1334
1335   if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1336     {
1337       const gchar *new_charset;
1338       gchar *p;
1339       gint i;
1340
1341       g_free (cache->charset);
1342       g_strfreev (cache->filename_charsets);
1343       cache->charset = g_strdup (charset);
1344       
1345       p = getenv ("G_FILENAME_ENCODING");
1346       if (p != NULL && p[0] != '\0') 
1347         {
1348           cache->filename_charsets = g_strsplit (p, ",", 0);
1349           cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1350
1351           for (i = 0; cache->filename_charsets[i]; i++)
1352             {
1353               if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1354                 {
1355                   g_get_charset (&new_charset);
1356                   g_free (cache->filename_charsets[i]);
1357                   cache->filename_charsets[i] = g_strdup (new_charset);
1358                 }
1359             }
1360         }
1361       else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1362         {
1363           cache->filename_charsets = g_new0 (gchar *, 2);
1364           cache->is_utf8 = g_get_charset (&new_charset);
1365           cache->filename_charsets[0] = g_strdup (new_charset);
1366         }
1367       else 
1368         {
1369           cache->filename_charsets = g_new0 (gchar *, 3);
1370           cache->is_utf8 = TRUE;
1371           cache->filename_charsets[0] = g_strdup ("UTF-8");
1372           if (!g_get_charset (&new_charset))
1373             cache->filename_charsets[1] = g_strdup (new_charset);
1374         }
1375     }
1376
1377   if (filename_charsets)
1378     *filename_charsets = (const gchar **)cache->filename_charsets;
1379
1380   return cache->is_utf8;
1381 }
1382
1383 #else /* G_PLATFORM_WIN32 */
1384
1385 gboolean
1386 g_get_filename_charsets (const gchar ***filename_charsets) 
1387 {
1388   static const gchar *charsets[] = {
1389     "UTF-8",
1390     NULL
1391   };
1392
1393 #ifdef G_OS_WIN32
1394   /* On Windows GLib pretends that the filename charset is UTF-8 */
1395   if (filename_charsets)
1396     *filename_charsets = charsets;
1397
1398   return TRUE;
1399 #else
1400   gboolean result;
1401
1402   /* Cygwin works like before */
1403   result = g_get_charset (&(charsets[0]));
1404
1405   if (filename_charsets)
1406     *filename_charsets = charsets;
1407
1408   return result;
1409 #endif
1410 }
1411
1412 #endif /* G_PLATFORM_WIN32 */
1413
1414 static gboolean
1415 get_filename_charset (const gchar **filename_charset)
1416 {
1417   const gchar **charsets;
1418   gboolean is_utf8;
1419   
1420   is_utf8 = g_get_filename_charsets (&charsets);
1421
1422   if (filename_charset)
1423     *filename_charset = charsets[0];
1424   
1425   return is_utf8;
1426 }
1427
1428 /* This is called from g_thread_init(). It's used to
1429  * initialize some static data in a threadsafe way.
1430  */
1431 void 
1432 _g_convert_thread_init (void)
1433 {
1434   const gchar **dummy;
1435   (void) g_get_filename_charsets (&dummy);
1436 }
1437
1438 /**
1439  * g_filename_to_utf8:
1440  * @opsysstring:   a string in the encoding for filenames
1441  * @len:           the length of the string, or -1 if the string is
1442  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1443  * @bytes_read:    location to store the number of bytes in the
1444  *                 input string that were successfully converted, or %NULL.
1445  *                 Even if the conversion was successful, this may be 
1446  *                 less than @len if there were partial characters
1447  *                 at the end of the input. If the error
1448  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1449  *                 stored will the byte offset after the last valid
1450  *                 input sequence.
1451  * @bytes_written: the number of bytes stored in the output buffer (not 
1452  *                 including the terminating nul).
1453  * @error:         location to store the error occuring, or %NULL to ignore
1454  *                 errors. Any of the errors in #GConvertError may occur.
1455  * 
1456  * Converts a string which is in the encoding used by GLib for
1457  * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1458  * for filenames; on other platforms, this function indirectly depends on 
1459  * the <link linkend="setlocale">current locale</link>.
1460  * 
1461  * Return value: The converted string, or %NULL on an error.
1462  **/
1463 gchar*
1464 g_filename_to_utf8 (const gchar *opsysstring, 
1465                     gssize       len,           
1466                     gsize       *bytes_read,   
1467                     gsize       *bytes_written,
1468                     GError     **error)
1469 {
1470   const gchar *charset;
1471
1472   if (get_filename_charset (&charset))
1473     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1474   else
1475     return g_convert (opsysstring, len, 
1476                       "UTF-8", charset, bytes_read, bytes_written, error);
1477 }
1478
1479 #if defined (G_OS_WIN32) && !defined (_WIN64)
1480
1481 #undef g_filename_to_utf8
1482
1483 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1484  * 64-bit versions as there should be no old deployed binaries that would use
1485  * the old versions.
1486  */
1487
1488 gchar*
1489 g_filename_to_utf8 (const gchar *opsysstring, 
1490                     gssize       len,           
1491                     gsize       *bytes_read,   
1492                     gsize       *bytes_written,
1493                     GError     **error)
1494 {
1495   const gchar *charset;
1496
1497   if (g_get_charset (&charset))
1498     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1499   else
1500     return g_convert (opsysstring, len, 
1501                       "UTF-8", charset, bytes_read, bytes_written, error);
1502 }
1503
1504 #endif
1505
1506 /**
1507  * g_filename_from_utf8:
1508  * @utf8string:    a UTF-8 encoded string.
1509  * @len:           the length of the string, or -1 if the string is
1510  *                 nul-terminated.
1511  * @bytes_read:    location to store the number of bytes in the
1512  *                 input string that were successfully converted, or %NULL.
1513  *                 Even if the conversion was successful, this may be 
1514  *                 less than @len if there were partial characters
1515  *                 at the end of the input. If the error
1516  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1517  *                 stored will the byte offset after the last valid
1518  *                 input sequence.
1519  * @bytes_written: the number of bytes stored in the output buffer (not 
1520  *                 including the terminating nul).
1521  * @error:         location to store the error occuring, or %NULL to ignore
1522  *                 errors. Any of the errors in #GConvertError may occur.
1523  * 
1524  * Converts a string from UTF-8 to the encoding GLib uses for
1525  * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1526  * on other platforms, this function indirectly depends on the 
1527  * <link linkend="setlocale">current locale</link>.
1528  * 
1529  * Return value: The converted string, or %NULL on an error.
1530  **/
1531 gchar*
1532 g_filename_from_utf8 (const gchar *utf8string,
1533                       gssize       len,            
1534                       gsize       *bytes_read,    
1535                       gsize       *bytes_written,
1536                       GError     **error)
1537 {
1538   const gchar *charset;
1539
1540   if (get_filename_charset (&charset))
1541     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1542   else
1543     return g_convert (utf8string, len,
1544                       charset, "UTF-8", bytes_read, bytes_written, error);
1545 }
1546
1547 #if defined (G_OS_WIN32) && !defined (_WIN64)
1548
1549 #undef g_filename_from_utf8
1550
1551 /* Binary compatibility version. Not for newly compiled code. */
1552
1553 gchar*
1554 g_filename_from_utf8 (const gchar *utf8string,
1555                       gssize       len,            
1556                       gsize       *bytes_read,    
1557                       gsize       *bytes_written,
1558                       GError     **error)
1559 {
1560   const gchar *charset;
1561
1562   if (g_get_charset (&charset))
1563     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1564   else
1565     return g_convert (utf8string, len,
1566                       charset, "UTF-8", bytes_read, bytes_written, error);
1567 }
1568
1569 #endif
1570
1571 /* Test of haystack has the needle prefix, comparing case
1572  * insensitive. haystack may be UTF-8, but needle must
1573  * contain only ascii. */
1574 static gboolean
1575 has_case_prefix (const gchar *haystack, const gchar *needle)
1576 {
1577   const gchar *h, *n;
1578   
1579   /* Eat one character at a time. */
1580   h = haystack;
1581   n = needle;
1582
1583   while (*n && *h &&
1584          g_ascii_tolower (*n) == g_ascii_tolower (*h))
1585     {
1586       n++;
1587       h++;
1588     }
1589   
1590   return *n == '\0';
1591 }
1592
1593 typedef enum {
1594   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
1595   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1596   UNSAFE_PATH       = 0x8,  /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1597   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
1598   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
1599 } UnsafeCharacterSet;
1600
1601 static const guchar acceptable[96] = {
1602   /* A table of the ASCII chars from space (32) to DEL (127) */
1603   /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1604   0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1605   /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1606   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1607   /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1608   0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1609   /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
1610   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1611   /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
1612   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1613   /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
1614   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1615 };
1616
1617 static const gchar hex[16] = "0123456789ABCDEF";
1618
1619 /* Note: This escape function works on file: URIs, but if you want to
1620  * escape something else, please read RFC-2396 */
1621 static gchar *
1622 g_escape_uri_string (const gchar *string, 
1623                      UnsafeCharacterSet mask)
1624 {
1625 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1626
1627   const gchar *p;
1628   gchar *q;
1629   gchar *result;
1630   int c;
1631   gint unacceptable;
1632   UnsafeCharacterSet use_mask;
1633   
1634   g_return_val_if_fail (mask == UNSAFE_ALL
1635                         || mask == UNSAFE_ALLOW_PLUS
1636                         || mask == UNSAFE_PATH
1637                         || mask == UNSAFE_HOST
1638                         || mask == UNSAFE_SLASHES, NULL);
1639   
1640   unacceptable = 0;
1641   use_mask = mask;
1642   for (p = string; *p != '\0'; p++)
1643     {
1644       c = (guchar) *p;
1645       if (!ACCEPTABLE (c)) 
1646         unacceptable++;
1647     }
1648   
1649   result = g_malloc (p - string + unacceptable * 2 + 1);
1650   
1651   use_mask = mask;
1652   for (q = result, p = string; *p != '\0'; p++)
1653     {
1654       c = (guchar) *p;
1655       
1656       if (!ACCEPTABLE (c))
1657         {
1658           *q++ = '%'; /* means hex coming */
1659           *q++ = hex[c >> 4];
1660           *q++ = hex[c & 15];
1661         }
1662       else
1663         *q++ = *p;
1664     }
1665   
1666   *q = '\0';
1667   
1668   return result;
1669 }
1670
1671
1672 static gchar *
1673 g_escape_file_uri (const gchar *hostname,
1674                    const gchar *pathname)
1675 {
1676   char *escaped_hostname = NULL;
1677   char *escaped_path;
1678   char *res;
1679
1680 #ifdef G_OS_WIN32
1681   char *p, *backslash;
1682
1683   /* Turn backslashes into forward slashes. That's what Netscape
1684    * does, and they are actually more or less equivalent in Windows.
1685    */
1686   
1687   pathname = g_strdup (pathname);
1688   p = (char *) pathname;
1689   
1690   while ((backslash = strchr (p, '\\')) != NULL)
1691     {
1692       *backslash = '/';
1693       p = backslash + 1;
1694     }
1695 #endif
1696
1697   if (hostname && *hostname != '\0')
1698     {
1699       escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1700     }
1701
1702   escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1703
1704   res = g_strconcat ("file://",
1705                      (escaped_hostname) ? escaped_hostname : "",
1706                      (*escaped_path != '/') ? "/" : "",
1707                      escaped_path,
1708                      NULL);
1709
1710 #ifdef G_OS_WIN32
1711   g_free ((char *) pathname);
1712 #endif
1713
1714   g_free (escaped_hostname);
1715   g_free (escaped_path);
1716   
1717   return res;
1718 }
1719
1720 static int
1721 unescape_character (const char *scanner)
1722 {
1723   int first_digit;
1724   int second_digit;
1725
1726   first_digit = g_ascii_xdigit_value (scanner[0]);
1727   if (first_digit < 0) 
1728     return -1;
1729   
1730   second_digit = g_ascii_xdigit_value (scanner[1]);
1731   if (second_digit < 0) 
1732     return -1;
1733   
1734   return (first_digit << 4) | second_digit;
1735 }
1736
1737 static gchar *
1738 g_unescape_uri_string (const char *escaped,
1739                        int         len,
1740                        const char *illegal_escaped_characters,
1741                        gboolean    ascii_must_not_be_escaped)
1742 {
1743   const gchar *in, *in_end;
1744   gchar *out, *result;
1745   int c;
1746   
1747   if (escaped == NULL)
1748     return NULL;
1749
1750   if (len < 0)
1751     len = strlen (escaped);
1752
1753   result = g_malloc (len + 1);
1754   
1755   out = result;
1756   for (in = escaped, in_end = escaped + len; in < in_end; in++)
1757     {
1758       c = *in;
1759
1760       if (c == '%')
1761         {
1762           /* catch partial escape sequences past the end of the substring */
1763           if (in + 3 > in_end)
1764             break;
1765
1766           c = unescape_character (in + 1);
1767
1768           /* catch bad escape sequences and NUL characters */
1769           if (c <= 0)
1770             break;
1771
1772           /* catch escaped ASCII */
1773           if (ascii_must_not_be_escaped && c <= 0x7F)
1774             break;
1775
1776           /* catch other illegal escaped characters */
1777           if (strchr (illegal_escaped_characters, c) != NULL)
1778             break;
1779
1780           in += 2;
1781         }
1782
1783       *out++ = c;
1784     }
1785   
1786   g_assert (out - result <= len);
1787   *out = '\0';
1788
1789   if (in != in_end)
1790     {
1791       g_free (result);
1792       return NULL;
1793     }
1794
1795   return result;
1796 }
1797
1798 static gboolean
1799 is_asciialphanum (gunichar c)
1800 {
1801   return c <= 0x7F && g_ascii_isalnum (c);
1802 }
1803
1804 static gboolean
1805 is_asciialpha (gunichar c)
1806 {
1807   return c <= 0x7F && g_ascii_isalpha (c);
1808 }
1809
1810 /* allows an empty string */
1811 static gboolean
1812 hostname_validate (const char *hostname)
1813 {
1814   const char *p;
1815   gunichar c, first_char, last_char;
1816
1817   p = hostname;
1818   if (*p == '\0')
1819     return TRUE;
1820   do
1821     {
1822       /* read in a label */
1823       c = g_utf8_get_char (p);
1824       p = g_utf8_next_char (p);
1825       if (!is_asciialphanum (c))
1826         return FALSE;
1827       first_char = c;
1828       do
1829         {
1830           last_char = c;
1831           c = g_utf8_get_char (p);
1832           p = g_utf8_next_char (p);
1833         }
1834       while (is_asciialphanum (c) || c == '-');
1835       if (last_char == '-')
1836         return FALSE;
1837       
1838       /* if that was the last label, check that it was a toplabel */
1839       if (c == '\0' || (c == '.' && *p == '\0'))
1840         return is_asciialpha (first_char);
1841     }
1842   while (c == '.');
1843   return FALSE;
1844 }
1845
1846 /**
1847  * g_filename_from_uri:
1848  * @uri: a uri describing a filename (escaped, encoded in ASCII).
1849  * @hostname: Location to store hostname for the URI, or %NULL.
1850  *            If there is no hostname in the URI, %NULL will be
1851  *            stored in this location.
1852  * @error: location to store the error occuring, or %NULL to ignore
1853  *         errors. Any of the errors in #GConvertError may occur.
1854  * 
1855  * Converts an escaped ASCII-encoded URI to a local filename in the
1856  * encoding used for filenames. 
1857  * 
1858  * Return value: a newly-allocated string holding the resulting
1859  *               filename, or %NULL on an error.
1860  **/
1861 gchar *
1862 g_filename_from_uri (const gchar *uri,
1863                      gchar      **hostname,
1864                      GError     **error)
1865 {
1866   const char *path_part;
1867   const char *host_part;
1868   char *unescaped_hostname;
1869   char *result;
1870   char *filename;
1871   int offs;
1872 #ifdef G_OS_WIN32
1873   char *p, *slash;
1874 #endif
1875
1876   if (hostname)
1877     *hostname = NULL;
1878
1879   if (!has_case_prefix (uri, "file:/"))
1880     {
1881       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1882                    _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1883                    uri);
1884       return NULL;
1885     }
1886   
1887   path_part = uri + strlen ("file:");
1888   
1889   if (strchr (path_part, '#') != NULL)
1890     {
1891       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1892                    _("The local file URI '%s' may not include a '#'"),
1893                    uri);
1894       return NULL;
1895     }
1896         
1897   if (has_case_prefix (path_part, "///")) 
1898     path_part += 2;
1899   else if (has_case_prefix (path_part, "//"))
1900     {
1901       path_part += 2;
1902       host_part = path_part;
1903
1904       path_part = strchr (path_part, '/');
1905
1906       if (path_part == NULL)
1907         {
1908           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1909                        _("The URI '%s' is invalid"),
1910                        uri);
1911           return NULL;
1912         }
1913
1914       unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1915
1916       if (unescaped_hostname == NULL ||
1917           !hostname_validate (unescaped_hostname))
1918         {
1919           g_free (unescaped_hostname);
1920           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1921                        _("The hostname of the URI '%s' is invalid"),
1922                        uri);
1923           return NULL;
1924         }
1925       
1926       if (hostname)
1927         *hostname = unescaped_hostname;
1928       else
1929         g_free (unescaped_hostname);
1930     }
1931
1932   filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1933
1934   if (filename == NULL)
1935     {
1936       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1937                    _("The URI '%s' contains invalidly escaped characters"),
1938                    uri);
1939       return NULL;
1940     }
1941
1942   offs = 0;
1943 #ifdef G_OS_WIN32
1944   /* Drop localhost */
1945   if (hostname && *hostname != NULL &&
1946       g_ascii_strcasecmp (*hostname, "localhost") == 0)
1947     {
1948       g_free (*hostname);
1949       *hostname = NULL;
1950     }
1951
1952   /* Turn slashes into backslashes, because that's the canonical spelling */
1953   p = filename;
1954   while ((slash = strchr (p, '/')) != NULL)
1955     {
1956       *slash = '\\';
1957       p = slash + 1;
1958     }
1959
1960   /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1961    * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1962    * the filename from the drive letter.
1963    */
1964   if (g_ascii_isalpha (filename[1]))
1965     {
1966       if (filename[2] == ':')
1967         offs = 1;
1968       else if (filename[2] == '|')
1969         {
1970           filename[2] = ':';
1971           offs = 1;
1972         }
1973     }
1974 #endif
1975
1976   result = g_strdup (filename + offs);
1977   g_free (filename);
1978
1979   return result;
1980 }
1981
1982 #if defined (G_OS_WIN32) && !defined (_WIN64)
1983
1984 #undef g_filename_from_uri
1985
1986 gchar *
1987 g_filename_from_uri (const gchar *uri,
1988                      gchar      **hostname,
1989                      GError     **error)
1990 {
1991   gchar *utf8_filename;
1992   gchar *retval = NULL;
1993
1994   utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1995   if (utf8_filename)
1996     {
1997       retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1998       g_free (utf8_filename);
1999     }
2000   return retval;
2001 }
2002
2003 #endif
2004
2005 /**
2006  * g_filename_to_uri:
2007  * @filename: an absolute filename specified in the GLib file name encoding,
2008  *            which is the on-disk file name bytes on Unix, and UTF-8 on 
2009  *            Windows
2010  * @hostname: A UTF-8 encoded hostname, or %NULL for none.
2011  * @error: location to store the error occuring, or %NULL to ignore
2012  *         errors. Any of the errors in #GConvertError may occur.
2013  * 
2014  * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
2015  * component following Section 3.3. of RFC 2396.
2016  * 
2017  * Return value: a newly-allocated string holding the resulting
2018  *               URI, or %NULL on an error.
2019  **/
2020 gchar *
2021 g_filename_to_uri (const gchar *filename,
2022                    const gchar *hostname,
2023                    GError     **error)
2024 {
2025   char *escaped_uri;
2026
2027   g_return_val_if_fail (filename != NULL, NULL);
2028
2029   if (!g_path_is_absolute (filename))
2030     {
2031       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
2032                    _("The pathname '%s' is not an absolute path"),
2033                    filename);
2034       return NULL;
2035     }
2036
2037   if (hostname &&
2038       !(g_utf8_validate (hostname, -1, NULL)
2039         && hostname_validate (hostname)))
2040     {
2041       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2042                            _("Invalid hostname"));
2043       return NULL;
2044     }
2045   
2046 #ifdef G_OS_WIN32
2047   /* Don't use localhost unnecessarily */
2048   if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
2049     hostname = NULL;
2050 #endif
2051
2052   escaped_uri = g_escape_file_uri (hostname, filename);
2053
2054   return escaped_uri;
2055 }
2056
2057 #if defined (G_OS_WIN32) && !defined (_WIN64)
2058
2059 #undef g_filename_to_uri
2060
2061 gchar *
2062 g_filename_to_uri (const gchar *filename,
2063                    const gchar *hostname,
2064                    GError     **error)
2065 {
2066   gchar *utf8_filename;
2067   gchar *retval = NULL;
2068
2069   utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2070
2071   if (utf8_filename)
2072     {
2073       retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
2074       g_free (utf8_filename);
2075     }
2076
2077   return retval;
2078 }
2079
2080 #endif
2081
2082 /**
2083  * g_uri_list_extract_uris:
2084  * @uri_list: an URI list 
2085  *
2086  * Splits an URI list conforming to the text/uri-list
2087  * mime type defined in RFC 2483 into individual URIs,
2088  * discarding any comments. The URIs are not validated.
2089  *
2090  * Returns: a newly allocated %NULL-terminated list of
2091  *   strings holding the individual URIs. The array should
2092  *   be freed with g_strfreev().
2093  *
2094  * Since: 2.6
2095  */
2096 gchar **
2097 g_uri_list_extract_uris (const gchar *uri_list)
2098 {
2099   GSList *uris, *u;
2100   const gchar *p, *q;
2101   gchar **result;
2102   gint n_uris = 0;
2103
2104   uris = NULL;
2105
2106   p = uri_list;
2107
2108   /* We don't actually try to validate the URI according to RFC
2109    * 2396, or even check for allowed characters - we just ignore
2110    * comments and trim whitespace off the ends.  We also
2111    * allow LF delimination as well as the specified CRLF.
2112    *
2113    * We do allow comments like specified in RFC 2483.
2114    */
2115   while (p)
2116     {
2117       if (*p != '#')
2118         {
2119           while (g_ascii_isspace (*p))
2120             p++;
2121
2122           q = p;
2123           while (*q && (*q != '\n') && (*q != '\r'))
2124             q++;
2125
2126           if (q > p)
2127             {
2128               q--;
2129               while (q > p && g_ascii_isspace (*q))
2130                 q--;
2131
2132               if (q > p)
2133                 {
2134                   uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2135                   n_uris++;
2136                 }
2137             }
2138         }
2139       p = strchr (p, '\n');
2140       if (p)
2141         p++;
2142     }
2143
2144   result = g_new (gchar *, n_uris + 1);
2145
2146   result[n_uris--] = NULL;
2147   for (u = uris; u; u = u->next)
2148     result[n_uris--] = u->data;
2149
2150   g_slist_free (uris);
2151
2152   return result;
2153 }
2154
2155 /**
2156  * g_filename_display_basename:
2157  * @filename: an absolute pathname in the GLib file name encoding
2158  *
2159  * Returns the display basename for the particular filename, guaranteed
2160  * to be valid UTF-8. The display name might not be identical to the filename,
2161  * for instance there might be problems converting it to UTF-8, and some files
2162  * can be translated in the display.
2163  *
2164  * If GLib can not make sense of the encoding of @filename, as a last resort it 
2165  * replaces unknown characters with U+FFFD, the Unicode replacement character.
2166  * You can search the result for the UTF-8 encoding of this character (which is
2167  * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2168  * encoding.
2169  *
2170  * You must pass the whole absolute pathname to this functions so that
2171  * translation of well known locations can be done.
2172  *
2173  * This function is preferred over g_filename_display_name() if you know the
2174  * whole path, as it allows translation.
2175  *
2176  * Return value: a newly allocated string containing
2177  *   a rendition of the basename of the filename in valid UTF-8
2178  *
2179  * Since: 2.6
2180  **/
2181 gchar *
2182 g_filename_display_basename (const gchar *filename)
2183 {
2184   char *basename;
2185   char *display_name;
2186
2187   g_return_val_if_fail (filename != NULL, NULL);
2188   
2189   basename = g_path_get_basename (filename);
2190   display_name = g_filename_display_name (basename);
2191   g_free (basename);
2192   return display_name;
2193 }
2194
2195 /**
2196  * g_filename_display_name:
2197  * @filename: a pathname hopefully in the GLib file name encoding
2198  * 
2199  * Converts a filename into a valid UTF-8 string. The conversion is 
2200  * not necessarily reversible, so you should keep the original around 
2201  * and use the return value of this function only for display purposes.
2202  * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL 
2203  * even if the filename actually isn't in the GLib file name encoding.
2204  *
2205  * If GLib can not make sense of the encoding of @filename, as a last resort it 
2206  * replaces unknown characters with U+FFFD, the Unicode replacement character.
2207  * You can search the result for the UTF-8 encoding of this character (which is
2208  * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2209  * encoding.
2210  *
2211  * If you know the whole pathname of the file you should use
2212  * g_filename_display_basename(), since that allows location-based
2213  * translation of filenames.
2214  *
2215  * Return value: a newly allocated string containing
2216  *   a rendition of the filename in valid UTF-8
2217  *
2218  * Since: 2.6
2219  **/
2220 gchar *
2221 g_filename_display_name (const gchar *filename)
2222 {
2223   gint i;
2224   const gchar **charsets;
2225   gchar *display_name = NULL;
2226   gboolean is_utf8;
2227  
2228   is_utf8 = g_get_filename_charsets (&charsets);
2229
2230   if (is_utf8)
2231     {
2232       if (g_utf8_validate (filename, -1, NULL))
2233         display_name = g_strdup (filename);
2234     }
2235   
2236   if (!display_name)
2237     {
2238       /* Try to convert from the filename charsets to UTF-8.
2239        * Skip the first charset if it is UTF-8.
2240        */
2241       for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2242         {
2243           display_name = g_convert (filename, -1, "UTF-8", charsets[i], 
2244                                     NULL, NULL, NULL);
2245
2246           if (display_name)
2247             break;
2248         }
2249     }
2250   
2251   /* if all conversions failed, we replace invalid UTF-8
2252    * by a question mark
2253    */
2254   if (!display_name) 
2255     display_name = _g_utf8_make_valid (filename);
2256
2257   return display_name;
2258 }