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