Merge remote branch 'gvdb/master'
[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               {
773                 int errsv = errno;
774                 
775                 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
776                              _("Error during conversion: %s"),
777                              g_strerror (errsv));
778               }
779               have_error = TRUE;
780               break;
781             }
782         }
783       else 
784         {
785           if (!reset)
786             {
787               /* call g_iconv with NULL inbuf to cleanup shift state */
788               reset = TRUE;
789               inbytes_remaining = 0;
790             }
791           else
792             done = TRUE;
793         }
794     }
795
796   memset (outp, 0, NUL_TERMINATOR_LENGTH);
797   
798   if (bytes_read)
799     *bytes_read = p - str;
800   else
801     {
802       if ((p - str) != len) 
803         {
804           if (!have_error)
805             {
806               if (error)
807                 g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_PARTIAL_INPUT,
808                                      _("Partial character sequence at end of input"));
809               have_error = TRUE;
810             }
811         }
812     }
813
814   if (bytes_written)
815     *bytes_written = outp - dest;       /* Doesn't include '\0' */
816
817   if (have_error)
818     {
819       g_free (dest);
820       return NULL;
821     }
822   else
823     return dest;
824 }
825
826 /**
827  * g_convert:
828  * @str:           the string to convert
829  * @len:           the length of the string, or -1 if the string is 
830  *                 nul-terminated<footnote id="nul-unsafe">
831                      <para>
832                        Note that some encodings may allow nul bytes to 
833                        occur inside strings. In that case, using -1 for 
834                        the @len parameter is unsafe.
835                      </para>
836                    </footnote>. 
837  * @to_codeset:    name of character set into which to convert @str
838  * @from_codeset:  character set of @str.
839  * @bytes_read:    location to store the number of bytes in the
840  *                 input string that were successfully converted, or %NULL.
841  *                 Even if the conversion was successful, this may be 
842  *                 less than @len if there were partial characters
843  *                 at the end of the input. If the error
844  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
845  *                 stored will the byte offset after the last valid
846  *                 input sequence.
847  * @bytes_written: the number of bytes stored in the output buffer (not 
848  *                 including the terminating nul).
849  * @error:         location to store the error occuring, or %NULL to ignore
850  *                 errors. Any of the errors in #GConvertError may occur.
851  *
852  * Converts a string from one character set to another.
853  *
854  * Note that you should use g_iconv() for streaming 
855  * conversions<footnoteref linkend="streaming-state"/>.
856  *
857  * Return value: If the conversion was successful, a newly allocated
858  *               nul-terminated string, which must be freed with
859  *               g_free(). Otherwise %NULL and @error will be set.
860  **/
861 gchar*
862 g_convert (const gchar *str,
863            gssize       len,  
864            const gchar *to_codeset,
865            const gchar *from_codeset,
866            gsize       *bytes_read, 
867            gsize       *bytes_written, 
868            GError     **error)
869 {
870   gchar *res;
871   GIConv cd;
872
873   g_return_val_if_fail (str != NULL, NULL);
874   g_return_val_if_fail (to_codeset != NULL, NULL);
875   g_return_val_if_fail (from_codeset != NULL, NULL);
876   
877   cd = open_converter (to_codeset, from_codeset, error);
878
879   if (cd == (GIConv) -1)
880     {
881       if (bytes_read)
882         *bytes_read = 0;
883       
884       if (bytes_written)
885         *bytes_written = 0;
886       
887       return NULL;
888     }
889
890   res = g_convert_with_iconv (str, len, cd,
891                               bytes_read, bytes_written,
892                               error);
893
894   close_converter (cd);
895
896   return res;
897 }
898
899 /**
900  * g_convert_with_fallback:
901  * @str:          the string to convert
902  * @len:          the length of the string, or -1 if the string is 
903  *                nul-terminated<footnoteref linkend="nul-unsafe"/>. 
904  * @to_codeset:   name of character set into which to convert @str
905  * @from_codeset: character set of @str.
906  * @fallback:     UTF-8 string to use in place of character not
907  *                present in the target encoding. (The string must be
908  *                representable in the target encoding). 
909                   If %NULL, characters not in the target encoding will 
910                   be represented as Unicode escapes \uxxxx or \Uxxxxyyyy.
911  * @bytes_read:   location to store the number of bytes in the
912  *                input string that were successfully converted, or %NULL.
913  *                Even if the conversion was successful, this may be 
914  *                less than @len if there were partial characters
915  *                at the end of the input.
916  * @bytes_written: the number of bytes stored in the output buffer (not 
917  *                including the terminating nul).
918  * @error:        location to store the error occuring, or %NULL to ignore
919  *                errors. Any of the errors in #GConvertError may occur.
920  *
921  * Converts a string from one character set to another, possibly
922  * including fallback sequences for characters not representable
923  * in the output. Note that it is not guaranteed that the specification
924  * for the fallback sequences in @fallback will be honored. Some
925  * systems may do an approximate conversion from @from_codeset
926  * to @to_codeset in their iconv() functions, 
927  * in which case GLib will simply return that approximate conversion.
928  *
929  * Note that you should use g_iconv() for streaming 
930  * conversions<footnoteref linkend="streaming-state"/>.
931  *
932  * Return value: If the conversion was successful, a newly allocated
933  *               nul-terminated string, which must be freed with
934  *               g_free(). Otherwise %NULL and @error will be set.
935  **/
936 gchar*
937 g_convert_with_fallback (const gchar *str,
938                          gssize       len,    
939                          const gchar *to_codeset,
940                          const gchar *from_codeset,
941                          const gchar *fallback,
942                          gsize       *bytes_read,
943                          gsize       *bytes_written,
944                          GError     **error)
945 {
946   gchar *utf8;
947   gchar *dest;
948   gchar *outp;
949   const gchar *insert_str = NULL;
950   const gchar *p;
951   gsize inbytes_remaining;   
952   const gchar *save_p = NULL;
953   gsize save_inbytes = 0;
954   gsize outbytes_remaining; 
955   gsize err;
956   GIConv cd;
957   gsize outbuf_size;
958   gboolean have_error = FALSE;
959   gboolean done = FALSE;
960
961   GError *local_error = NULL;
962   
963   g_return_val_if_fail (str != NULL, NULL);
964   g_return_val_if_fail (to_codeset != NULL, NULL);
965   g_return_val_if_fail (from_codeset != NULL, NULL);
966      
967   if (len < 0)
968     len = strlen (str);
969   
970   /* Try an exact conversion; we only proceed if this fails
971    * due to an illegal sequence in the input string.
972    */
973   dest = g_convert (str, len, to_codeset, from_codeset, 
974                     bytes_read, bytes_written, &local_error);
975   if (!local_error)
976     return dest;
977
978   if (!g_error_matches (local_error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE))
979     {
980       g_propagate_error (error, local_error);
981       return NULL;
982     }
983   else
984     g_error_free (local_error);
985
986   local_error = NULL;
987   
988   /* No go; to proceed, we need a converter from "UTF-8" to
989    * to_codeset, and the string as UTF-8.
990    */
991   cd = open_converter (to_codeset, "UTF-8", error);
992   if (cd == (GIConv) -1)
993     {
994       if (bytes_read)
995         *bytes_read = 0;
996       
997       if (bytes_written)
998         *bytes_written = 0;
999       
1000       return NULL;
1001     }
1002
1003   utf8 = g_convert (str, len, "UTF-8", from_codeset, 
1004                     bytes_read, &inbytes_remaining, error);
1005   if (!utf8)
1006     {
1007       close_converter (cd);
1008       if (bytes_written)
1009         *bytes_written = 0;
1010       return NULL;
1011     }
1012
1013   /* Now the heart of the code. We loop through the UTF-8 string, and
1014    * whenever we hit an offending character, we form fallback, convert
1015    * the fallback to the target codeset, and then go back to
1016    * converting the original string after finishing with the fallback.
1017    *
1018    * The variables save_p and save_inbytes store the input state
1019    * for the original string while we are converting the fallback
1020    */
1021   p = utf8;
1022
1023   outbuf_size = len + NUL_TERMINATOR_LENGTH;
1024   outbytes_remaining = outbuf_size - NUL_TERMINATOR_LENGTH;
1025   outp = dest = g_malloc (outbuf_size);
1026
1027   while (!done && !have_error)
1028     {
1029       gsize inbytes_tmp = inbytes_remaining;
1030       err = g_iconv (cd, (char **)&p, &inbytes_tmp, &outp, &outbytes_remaining);
1031       inbytes_remaining = inbytes_tmp;
1032
1033       if (err == (gsize) -1)
1034         {
1035           switch (errno)
1036             {
1037             case EINVAL:
1038               g_assert_not_reached();
1039               break;
1040             case E2BIG:
1041               {
1042                 gsize used = outp - dest;
1043
1044                 outbuf_size *= 2;
1045                 dest = g_realloc (dest, outbuf_size);
1046                 
1047                 outp = dest + used;
1048                 outbytes_remaining = outbuf_size - used - NUL_TERMINATOR_LENGTH;
1049                 
1050                 break;
1051               }
1052             case EILSEQ:
1053               if (save_p)
1054                 {
1055                   /* Error converting fallback string - fatal
1056                    */
1057                   g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1058                                _("Cannot convert fallback '%s' to codeset '%s'"),
1059                                insert_str, to_codeset);
1060                   have_error = TRUE;
1061                   break;
1062                 }
1063               else if (p)
1064                 {
1065                   if (!fallback)
1066                     { 
1067                       gunichar ch = g_utf8_get_char (p);
1068                       insert_str = g_strdup_printf (ch < 0x10000 ? "\\u%04x" : "\\U%08x",
1069                                                     ch);
1070                     }
1071                   else
1072                     insert_str = fallback;
1073                   
1074                   save_p = g_utf8_next_char (p);
1075                   save_inbytes = inbytes_remaining - (save_p - p);
1076                   p = insert_str;
1077                   inbytes_remaining = strlen (p);
1078                   break;
1079                 }
1080               /* fall thru if p is NULL */
1081             default:
1082               {
1083                 int errsv = errno;
1084
1085                 g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_FAILED,
1086                              _("Error during conversion: %s"),
1087                              g_strerror (errsv));
1088               }
1089
1090               have_error = TRUE;
1091               break;
1092             }
1093         }
1094       else
1095         {
1096           if (save_p)
1097             {
1098               if (!fallback)
1099                 g_free ((gchar *)insert_str);
1100               p = save_p;
1101               inbytes_remaining = save_inbytes;
1102               save_p = NULL;
1103             }
1104           else if (p)
1105             {
1106               /* call g_iconv with NULL inbuf to cleanup shift state */
1107               p = NULL;
1108               inbytes_remaining = 0;
1109             }
1110           else
1111             done = TRUE;
1112         }
1113     }
1114
1115   /* Cleanup
1116    */
1117   memset (outp, 0, NUL_TERMINATOR_LENGTH);
1118   
1119   close_converter (cd);
1120
1121   if (bytes_written)
1122     *bytes_written = outp - dest;       /* Doesn't include '\0' */
1123
1124   g_free (utf8);
1125
1126   if (have_error)
1127     {
1128       if (save_p && !fallback)
1129         g_free ((gchar *)insert_str);
1130       g_free (dest);
1131       return NULL;
1132     }
1133   else
1134     return dest;
1135 }
1136
1137 /*
1138  * g_locale_to_utf8
1139  *
1140  * 
1141  */
1142
1143 static gchar *
1144 strdup_len (const gchar *string,
1145             gssize       len,
1146             gsize       *bytes_written,
1147             gsize       *bytes_read,
1148             GError      **error)
1149          
1150 {
1151   gsize real_len;
1152
1153   if (!g_utf8_validate (string, len, NULL))
1154     {
1155       if (bytes_read)
1156         *bytes_read = 0;
1157       if (bytes_written)
1158         *bytes_written = 0;
1159
1160       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
1161                            _("Invalid byte sequence in conversion input"));
1162       return NULL;
1163     }
1164   
1165   if (len < 0)
1166     real_len = strlen (string);
1167   else
1168     {
1169       real_len = 0;
1170       
1171       while (real_len < len && string[real_len])
1172         real_len++;
1173     }
1174   
1175   if (bytes_read)
1176     *bytes_read = real_len;
1177   if (bytes_written)
1178     *bytes_written = real_len;
1179
1180   return g_strndup (string, real_len);
1181 }
1182
1183 /**
1184  * g_locale_to_utf8:
1185  * @opsysstring:   a string in the encoding of the current locale. On Windows
1186  *                 this means the system codepage.
1187  * @len:           the length of the string, or -1 if the string is
1188  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1189  * @bytes_read:    location to store the number of bytes in the
1190  *                 input string that were successfully converted, or %NULL.
1191  *                 Even if the conversion was successful, this may be 
1192  *                 less than @len if there were partial characters
1193  *                 at the end of the input. If the error
1194  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1195  *                 stored will the byte offset after the last valid
1196  *                 input sequence.
1197  * @bytes_written: the number of bytes stored in the output buffer (not 
1198  *                 including the terminating nul).
1199  * @error:         location to store the error occuring, or %NULL to ignore
1200  *                 errors. Any of the errors in #GConvertError may occur.
1201  * 
1202  * Converts a string which is in the encoding used for strings by
1203  * the C runtime (usually the same as that used by the operating
1204  * system) in the <link linkend="setlocale">current locale</link> into a
1205  * UTF-8 string.
1206  * 
1207  * Return value: The converted string, or %NULL on an error.
1208  **/
1209 gchar *
1210 g_locale_to_utf8 (const gchar  *opsysstring,
1211                   gssize        len,            
1212                   gsize        *bytes_read,    
1213                   gsize        *bytes_written,
1214                   GError      **error)
1215 {
1216   const char *charset;
1217
1218   if (g_get_charset (&charset))
1219     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1220   else
1221     return g_convert (opsysstring, len, 
1222                       "UTF-8", charset, bytes_read, bytes_written, error);
1223 }
1224
1225 /**
1226  * g_locale_from_utf8:
1227  * @utf8string:    a UTF-8 encoded string 
1228  * @len:           the length of the string, or -1 if the string is
1229  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1230  * @bytes_read:    location to store the number of bytes in the
1231  *                 input string that were successfully converted, or %NULL.
1232  *                 Even if the conversion was successful, this may be 
1233  *                 less than @len if there were partial characters
1234  *                 at the end of the input. If the error
1235  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1236  *                 stored will the byte offset after the last valid
1237  *                 input sequence.
1238  * @bytes_written: the number of bytes stored in the output buffer (not 
1239  *                 including the terminating nul).
1240  * @error:         location to store the error occuring, or %NULL to ignore
1241  *                 errors. Any of the errors in #GConvertError may occur.
1242  * 
1243  * Converts a string from UTF-8 to the encoding used for strings by
1244  * the C runtime (usually the same as that used by the operating
1245  * system) in the <link linkend="setlocale">current locale</link>. On
1246  * Windows this means the system codepage.
1247  * 
1248  * Return value: The converted string, or %NULL on an error.
1249  **/
1250 gchar *
1251 g_locale_from_utf8 (const gchar *utf8string,
1252                     gssize       len,            
1253                     gsize       *bytes_read,    
1254                     gsize       *bytes_written,
1255                     GError     **error)
1256 {
1257   const gchar *charset;
1258
1259   if (g_get_charset (&charset))
1260     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1261   else
1262     return g_convert (utf8string, len,
1263                       charset, "UTF-8", bytes_read, bytes_written, error);
1264 }
1265
1266 #ifndef G_PLATFORM_WIN32
1267
1268 typedef struct _GFilenameCharsetCache GFilenameCharsetCache;
1269
1270 struct _GFilenameCharsetCache {
1271   gboolean is_utf8;
1272   gchar *charset;
1273   gchar **filename_charsets;
1274 };
1275
1276 static void
1277 filename_charset_cache_free (gpointer data)
1278 {
1279   GFilenameCharsetCache *cache = data;
1280   g_free (cache->charset);
1281   g_strfreev (cache->filename_charsets);
1282   g_free (cache);
1283 }
1284
1285 /**
1286  * g_get_filename_charsets:
1287  * @charsets: return location for the %NULL-terminated list of encoding names
1288  *
1289  * Determines the preferred character sets used for filenames.
1290  * The first character set from the @charsets is the filename encoding, the
1291  * subsequent character sets are used when trying to generate a displayable
1292  * representation of a filename, see g_filename_display_name().
1293  *
1294  * On Unix, the character sets are determined by consulting the
1295  * environment variables <envar>G_FILENAME_ENCODING</envar> and
1296  * <envar>G_BROKEN_FILENAMES</envar>. On Windows, the character set
1297  * used in the GLib API is always UTF-8 and said environment variables
1298  * have no effect.
1299  *
1300  * <envar>G_FILENAME_ENCODING</envar> may be set to a comma-separated list 
1301  * of character set names. The special token "&commat;locale" is taken to 
1302  * mean the character set for the <link linkend="setlocale">current 
1303  * locale</link>. If <envar>G_FILENAME_ENCODING</envar> is not set, but 
1304  * <envar>G_BROKEN_FILENAMES</envar> is, the character set of the current 
1305  * locale is taken as the filename encoding. If neither environment variable 
1306  * is set, UTF-8 is taken as the filename encoding, but the character
1307  * set of the current locale is also put in the list of encodings.
1308  *
1309  * The returned @charsets belong to GLib and must not be freed.
1310  *
1311  * Note that on Unix, regardless of the locale character set or
1312  * <envar>G_FILENAME_ENCODING</envar> value, the actual file names present 
1313  * on a system might be in any random encoding or just gibberish.
1314  *
1315  * Return value: %TRUE if the filename encoding is UTF-8.
1316  * 
1317  * Since: 2.6
1318  */
1319 gboolean
1320 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets)
1321 {
1322   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
1323   GFilenameCharsetCache *cache = g_static_private_get (&cache_private);
1324   const gchar *charset;
1325
1326   if (!cache)
1327     {
1328       cache = g_new0 (GFilenameCharsetCache, 1);
1329       g_static_private_set (&cache_private, cache, filename_charset_cache_free);
1330     }
1331
1332   g_get_charset (&charset);
1333
1334   if (!(cache->charset && strcmp (cache->charset, charset) == 0))
1335     {
1336       const gchar *new_charset;
1337       gchar *p;
1338       gint i;
1339
1340       g_free (cache->charset);
1341       g_strfreev (cache->filename_charsets);
1342       cache->charset = g_strdup (charset);
1343       
1344       p = getenv ("G_FILENAME_ENCODING");
1345       if (p != NULL && p[0] != '\0') 
1346         {
1347           cache->filename_charsets = g_strsplit (p, ",", 0);
1348           cache->is_utf8 = (strcmp (cache->filename_charsets[0], "UTF-8") == 0);
1349
1350           for (i = 0; cache->filename_charsets[i]; i++)
1351             {
1352               if (strcmp ("@locale", cache->filename_charsets[i]) == 0)
1353                 {
1354                   g_get_charset (&new_charset);
1355                   g_free (cache->filename_charsets[i]);
1356                   cache->filename_charsets[i] = g_strdup (new_charset);
1357                 }
1358             }
1359         }
1360       else if (getenv ("G_BROKEN_FILENAMES") != NULL)
1361         {
1362           cache->filename_charsets = g_new0 (gchar *, 2);
1363           cache->is_utf8 = g_get_charset (&new_charset);
1364           cache->filename_charsets[0] = g_strdup (new_charset);
1365         }
1366       else 
1367         {
1368           cache->filename_charsets = g_new0 (gchar *, 3);
1369           cache->is_utf8 = TRUE;
1370           cache->filename_charsets[0] = g_strdup ("UTF-8");
1371           if (!g_get_charset (&new_charset))
1372             cache->filename_charsets[1] = g_strdup (new_charset);
1373         }
1374     }
1375
1376   if (filename_charsets)
1377     *filename_charsets = (const gchar **)cache->filename_charsets;
1378
1379   return cache->is_utf8;
1380 }
1381
1382 #else /* G_PLATFORM_WIN32 */
1383
1384 gboolean
1385 g_get_filename_charsets (G_CONST_RETURN gchar ***filename_charsets) 
1386 {
1387   static const gchar *charsets[] = {
1388     "UTF-8",
1389     NULL
1390   };
1391
1392 #ifdef G_OS_WIN32
1393   /* On Windows GLib pretends that the filename charset is UTF-8 */
1394   if (filename_charsets)
1395     *filename_charsets = charsets;
1396
1397   return TRUE;
1398 #else
1399   gboolean result;
1400
1401   /* Cygwin works like before */
1402   result = g_get_charset (&(charsets[0]));
1403
1404   if (filename_charsets)
1405     *filename_charsets = charsets;
1406
1407   return result;
1408 #endif
1409 }
1410
1411 #endif /* G_PLATFORM_WIN32 */
1412
1413 static gboolean
1414 get_filename_charset (const gchar **filename_charset)
1415 {
1416   const gchar **charsets;
1417   gboolean is_utf8;
1418   
1419   is_utf8 = g_get_filename_charsets (&charsets);
1420
1421   if (filename_charset)
1422     *filename_charset = charsets[0];
1423   
1424   return is_utf8;
1425 }
1426
1427 /* This is called from g_thread_init(). It's used to
1428  * initialize some static data in a threadsafe way.
1429  */
1430 void 
1431 _g_convert_thread_init (void)
1432 {
1433   const gchar **dummy;
1434   (void) g_get_filename_charsets (&dummy);
1435 }
1436
1437 /**
1438  * g_filename_to_utf8:
1439  * @opsysstring:   a string in the encoding for filenames
1440  * @len:           the length of the string, or -1 if the string is
1441  *                 nul-terminated<footnoteref linkend="nul-unsafe"/>. 
1442  * @bytes_read:    location to store the number of bytes in the
1443  *                 input string that were successfully converted, or %NULL.
1444  *                 Even if the conversion was successful, this may be 
1445  *                 less than @len if there were partial characters
1446  *                 at the end of the input. If the error
1447  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1448  *                 stored will the byte offset after the last valid
1449  *                 input sequence.
1450  * @bytes_written: the number of bytes stored in the output buffer (not 
1451  *                 including the terminating nul).
1452  * @error:         location to store the error occuring, or %NULL to ignore
1453  *                 errors. Any of the errors in #GConvertError may occur.
1454  * 
1455  * Converts a string which is in the encoding used by GLib for
1456  * filenames into a UTF-8 string. Note that on Windows GLib uses UTF-8
1457  * for filenames; on other platforms, this function indirectly depends on 
1458  * the <link linkend="setlocale">current locale</link>.
1459  * 
1460  * Return value: The converted string, or %NULL on an error.
1461  **/
1462 gchar*
1463 g_filename_to_utf8 (const gchar *opsysstring, 
1464                     gssize       len,           
1465                     gsize       *bytes_read,   
1466                     gsize       *bytes_written,
1467                     GError     **error)
1468 {
1469   const gchar *charset;
1470
1471   if (get_filename_charset (&charset))
1472     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1473   else
1474     return g_convert (opsysstring, len, 
1475                       "UTF-8", charset, bytes_read, bytes_written, error);
1476 }
1477
1478 #if defined (G_OS_WIN32) && !defined (_WIN64)
1479
1480 #undef g_filename_to_utf8
1481
1482 /* Binary compatibility version. Not for newly compiled code. Also not needed for
1483  * 64-bit versions as there should be no old deployed binaries that would use
1484  * the old versions.
1485  */
1486
1487 gchar*
1488 g_filename_to_utf8 (const gchar *opsysstring, 
1489                     gssize       len,           
1490                     gsize       *bytes_read,   
1491                     gsize       *bytes_written,
1492                     GError     **error)
1493 {
1494   const gchar *charset;
1495
1496   if (g_get_charset (&charset))
1497     return strdup_len (opsysstring, len, bytes_read, bytes_written, error);
1498   else
1499     return g_convert (opsysstring, len, 
1500                       "UTF-8", charset, bytes_read, bytes_written, error);
1501 }
1502
1503 #endif
1504
1505 /**
1506  * g_filename_from_utf8:
1507  * @utf8string:    a UTF-8 encoded string.
1508  * @len:           the length of the string, or -1 if the string is
1509  *                 nul-terminated.
1510  * @bytes_read:    location to store the number of bytes in the
1511  *                 input string that were successfully converted, or %NULL.
1512  *                 Even if the conversion was successful, this may be 
1513  *                 less than @len if there were partial characters
1514  *                 at the end of the input. If the error
1515  *                 #G_CONVERT_ERROR_ILLEGAL_SEQUENCE occurs, the value
1516  *                 stored will the byte offset after the last valid
1517  *                 input sequence.
1518  * @bytes_written: the number of bytes stored in the output buffer (not 
1519  *                 including the terminating nul).
1520  * @error:         location to store the error occuring, or %NULL to ignore
1521  *                 errors. Any of the errors in #GConvertError may occur.
1522  * 
1523  * Converts a string from UTF-8 to the encoding GLib uses for
1524  * filenames. Note that on Windows GLib uses UTF-8 for filenames;
1525  * on other platforms, this function indirectly depends on the 
1526  * <link linkend="setlocale">current locale</link>.
1527  * 
1528  * Return value: The converted string, or %NULL on an error.
1529  **/
1530 gchar*
1531 g_filename_from_utf8 (const gchar *utf8string,
1532                       gssize       len,            
1533                       gsize       *bytes_read,    
1534                       gsize       *bytes_written,
1535                       GError     **error)
1536 {
1537   const gchar *charset;
1538
1539   if (get_filename_charset (&charset))
1540     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1541   else
1542     return g_convert (utf8string, len,
1543                       charset, "UTF-8", bytes_read, bytes_written, error);
1544 }
1545
1546 #if defined (G_OS_WIN32) && !defined (_WIN64)
1547
1548 #undef g_filename_from_utf8
1549
1550 /* Binary compatibility version. Not for newly compiled code. */
1551
1552 gchar*
1553 g_filename_from_utf8 (const gchar *utf8string,
1554                       gssize       len,            
1555                       gsize       *bytes_read,    
1556                       gsize       *bytes_written,
1557                       GError     **error)
1558 {
1559   const gchar *charset;
1560
1561   if (g_get_charset (&charset))
1562     return strdup_len (utf8string, len, bytes_read, bytes_written, error);
1563   else
1564     return g_convert (utf8string, len,
1565                       charset, "UTF-8", bytes_read, bytes_written, error);
1566 }
1567
1568 #endif
1569
1570 /* Test of haystack has the needle prefix, comparing case
1571  * insensitive. haystack may be UTF-8, but needle must
1572  * contain only ascii. */
1573 static gboolean
1574 has_case_prefix (const gchar *haystack, const gchar *needle)
1575 {
1576   const gchar *h, *n;
1577   
1578   /* Eat one character at a time. */
1579   h = haystack;
1580   n = needle;
1581
1582   while (*n && *h &&
1583          g_ascii_tolower (*n) == g_ascii_tolower (*h))
1584     {
1585       n++;
1586       h++;
1587     }
1588   
1589   return *n == '\0';
1590 }
1591
1592 typedef enum {
1593   UNSAFE_ALL        = 0x1,  /* Escape all unsafe characters   */
1594   UNSAFE_ALLOW_PLUS = 0x2,  /* Allows '+'  */
1595   UNSAFE_PATH       = 0x8,  /* Allows '/', '&', '=', ':', '@', '+', '$' and ',' */
1596   UNSAFE_HOST       = 0x10, /* Allows '/' and ':' and '@' */
1597   UNSAFE_SLASHES    = 0x20  /* Allows all characters except for '/' and '%' */
1598 } UnsafeCharacterSet;
1599
1600 static const guchar acceptable[96] = {
1601   /* A table of the ASCII chars from space (32) to DEL (127) */
1602   /*      !    "    #    $    %    &    '    (    )    *    +    ,    -    .    / */ 
1603   0x00,0x3F,0x20,0x20,0x28,0x00,0x2C,0x3F,0x3F,0x3F,0x3F,0x2A,0x28,0x3F,0x3F,0x1C,
1604   /* 0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ? */
1605   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x38,0x20,0x20,0x2C,0x20,0x20,
1606   /* @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O */
1607   0x38,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1608   /* P    Q    R    S    T    U    V    W    X    Y    Z    [    \    ]    ^    _ */
1609   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x20,0x3F,
1610   /* `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o */
1611   0x20,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,
1612   /* p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~  DEL */
1613   0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x20,0x20,0x20,0x3F,0x20
1614 };
1615
1616 static const gchar hex[16] = "0123456789ABCDEF";
1617
1618 /* Note: This escape function works on file: URIs, but if you want to
1619  * escape something else, please read RFC-2396 */
1620 static gchar *
1621 g_escape_uri_string (const gchar *string, 
1622                      UnsafeCharacterSet mask)
1623 {
1624 #define ACCEPTABLE(a) ((a)>=32 && (a)<128 && (acceptable[(a)-32] & use_mask))
1625
1626   const gchar *p;
1627   gchar *q;
1628   gchar *result;
1629   int c;
1630   gint unacceptable;
1631   UnsafeCharacterSet use_mask;
1632   
1633   g_return_val_if_fail (mask == UNSAFE_ALL
1634                         || mask == UNSAFE_ALLOW_PLUS
1635                         || mask == UNSAFE_PATH
1636                         || mask == UNSAFE_HOST
1637                         || mask == UNSAFE_SLASHES, NULL);
1638   
1639   unacceptable = 0;
1640   use_mask = mask;
1641   for (p = string; *p != '\0'; p++)
1642     {
1643       c = (guchar) *p;
1644       if (!ACCEPTABLE (c)) 
1645         unacceptable++;
1646     }
1647   
1648   result = g_malloc (p - string + unacceptable * 2 + 1);
1649   
1650   use_mask = mask;
1651   for (q = result, p = string; *p != '\0'; p++)
1652     {
1653       c = (guchar) *p;
1654       
1655       if (!ACCEPTABLE (c))
1656         {
1657           *q++ = '%'; /* means hex coming */
1658           *q++ = hex[c >> 4];
1659           *q++ = hex[c & 15];
1660         }
1661       else
1662         *q++ = *p;
1663     }
1664   
1665   *q = '\0';
1666   
1667   return result;
1668 }
1669
1670
1671 static gchar *
1672 g_escape_file_uri (const gchar *hostname,
1673                    const gchar *pathname)
1674 {
1675   char *escaped_hostname = NULL;
1676   char *escaped_path;
1677   char *res;
1678
1679 #ifdef G_OS_WIN32
1680   char *p, *backslash;
1681
1682   /* Turn backslashes into forward slashes. That's what Netscape
1683    * does, and they are actually more or less equivalent in Windows.
1684    */
1685   
1686   pathname = g_strdup (pathname);
1687   p = (char *) pathname;
1688   
1689   while ((backslash = strchr (p, '\\')) != NULL)
1690     {
1691       *backslash = '/';
1692       p = backslash + 1;
1693     }
1694 #endif
1695
1696   if (hostname && *hostname != '\0')
1697     {
1698       escaped_hostname = g_escape_uri_string (hostname, UNSAFE_HOST);
1699     }
1700
1701   escaped_path = g_escape_uri_string (pathname, UNSAFE_PATH);
1702
1703   res = g_strconcat ("file://",
1704                      (escaped_hostname) ? escaped_hostname : "",
1705                      (*escaped_path != '/') ? "/" : "",
1706                      escaped_path,
1707                      NULL);
1708
1709 #ifdef G_OS_WIN32
1710   g_free ((char *) pathname);
1711 #endif
1712
1713   g_free (escaped_hostname);
1714   g_free (escaped_path);
1715   
1716   return res;
1717 }
1718
1719 static int
1720 unescape_character (const char *scanner)
1721 {
1722   int first_digit;
1723   int second_digit;
1724
1725   first_digit = g_ascii_xdigit_value (scanner[0]);
1726   if (first_digit < 0) 
1727     return -1;
1728   
1729   second_digit = g_ascii_xdigit_value (scanner[1]);
1730   if (second_digit < 0) 
1731     return -1;
1732   
1733   return (first_digit << 4) | second_digit;
1734 }
1735
1736 static gchar *
1737 g_unescape_uri_string (const char *escaped,
1738                        int         len,
1739                        const char *illegal_escaped_characters,
1740                        gboolean    ascii_must_not_be_escaped)
1741 {
1742   const gchar *in, *in_end;
1743   gchar *out, *result;
1744   int c;
1745   
1746   if (escaped == NULL)
1747     return NULL;
1748
1749   if (len < 0)
1750     len = strlen (escaped);
1751
1752   result = g_malloc (len + 1);
1753   
1754   out = result;
1755   for (in = escaped, in_end = escaped + len; in < in_end; in++)
1756     {
1757       c = *in;
1758
1759       if (c == '%')
1760         {
1761           /* catch partial escape sequences past the end of the substring */
1762           if (in + 3 > in_end)
1763             break;
1764
1765           c = unescape_character (in + 1);
1766
1767           /* catch bad escape sequences and NUL characters */
1768           if (c <= 0)
1769             break;
1770
1771           /* catch escaped ASCII */
1772           if (ascii_must_not_be_escaped && c <= 0x7F)
1773             break;
1774
1775           /* catch other illegal escaped characters */
1776           if (strchr (illegal_escaped_characters, c) != NULL)
1777             break;
1778
1779           in += 2;
1780         }
1781
1782       *out++ = c;
1783     }
1784   
1785   g_assert (out - result <= len);
1786   *out = '\0';
1787
1788   if (in != in_end)
1789     {
1790       g_free (result);
1791       return NULL;
1792     }
1793
1794   return result;
1795 }
1796
1797 static gboolean
1798 is_asciialphanum (gunichar c)
1799 {
1800   return c <= 0x7F && g_ascii_isalnum (c);
1801 }
1802
1803 static gboolean
1804 is_asciialpha (gunichar c)
1805 {
1806   return c <= 0x7F && g_ascii_isalpha (c);
1807 }
1808
1809 /* allows an empty string */
1810 static gboolean
1811 hostname_validate (const char *hostname)
1812 {
1813   const char *p;
1814   gunichar c, first_char, last_char;
1815
1816   p = hostname;
1817   if (*p == '\0')
1818     return TRUE;
1819   do
1820     {
1821       /* read in a label */
1822       c = g_utf8_get_char (p);
1823       p = g_utf8_next_char (p);
1824       if (!is_asciialphanum (c))
1825         return FALSE;
1826       first_char = c;
1827       do
1828         {
1829           last_char = c;
1830           c = g_utf8_get_char (p);
1831           p = g_utf8_next_char (p);
1832         }
1833       while (is_asciialphanum (c) || c == '-');
1834       if (last_char == '-')
1835         return FALSE;
1836       
1837       /* if that was the last label, check that it was a toplabel */
1838       if (c == '\0' || (c == '.' && *p == '\0'))
1839         return is_asciialpha (first_char);
1840     }
1841   while (c == '.');
1842   return FALSE;
1843 }
1844
1845 /**
1846  * g_filename_from_uri:
1847  * @uri: a uri describing a filename (escaped, encoded in ASCII).
1848  * @hostname: Location to store hostname for the URI, or %NULL.
1849  *            If there is no hostname in the URI, %NULL will be
1850  *            stored in this location.
1851  * @error: location to store the error occuring, or %NULL to ignore
1852  *         errors. Any of the errors in #GConvertError may occur.
1853  * 
1854  * Converts an escaped ASCII-encoded URI to a local filename in the
1855  * encoding used for filenames. 
1856  * 
1857  * Return value: a newly-allocated string holding the resulting
1858  *               filename, or %NULL on an error.
1859  **/
1860 gchar *
1861 g_filename_from_uri (const gchar *uri,
1862                      gchar      **hostname,
1863                      GError     **error)
1864 {
1865   const char *path_part;
1866   const char *host_part;
1867   char *unescaped_hostname;
1868   char *result;
1869   char *filename;
1870   int offs;
1871 #ifdef G_OS_WIN32
1872   char *p, *slash;
1873 #endif
1874
1875   if (hostname)
1876     *hostname = NULL;
1877
1878   if (!has_case_prefix (uri, "file:/"))
1879     {
1880       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1881                    _("The URI '%s' is not an absolute URI using the \"file\" scheme"),
1882                    uri);
1883       return NULL;
1884     }
1885   
1886   path_part = uri + strlen ("file:");
1887   
1888   if (strchr (path_part, '#') != NULL)
1889     {
1890       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1891                    _("The local file URI '%s' may not include a '#'"),
1892                    uri);
1893       return NULL;
1894     }
1895         
1896   if (has_case_prefix (path_part, "///")) 
1897     path_part += 2;
1898   else if (has_case_prefix (path_part, "//"))
1899     {
1900       path_part += 2;
1901       host_part = path_part;
1902
1903       path_part = strchr (path_part, '/');
1904
1905       if (path_part == NULL)
1906         {
1907           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1908                        _("The URI '%s' is invalid"),
1909                        uri);
1910           return NULL;
1911         }
1912
1913       unescaped_hostname = g_unescape_uri_string (host_part, path_part - host_part, "", TRUE);
1914
1915       if (unescaped_hostname == NULL ||
1916           !hostname_validate (unescaped_hostname))
1917         {
1918           g_free (unescaped_hostname);
1919           g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1920                        _("The hostname of the URI '%s' is invalid"),
1921                        uri);
1922           return NULL;
1923         }
1924       
1925       if (hostname)
1926         *hostname = unescaped_hostname;
1927       else
1928         g_free (unescaped_hostname);
1929     }
1930
1931   filename = g_unescape_uri_string (path_part, -1, "/", FALSE);
1932
1933   if (filename == NULL)
1934     {
1935       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_BAD_URI,
1936                    _("The URI '%s' contains invalidly escaped characters"),
1937                    uri);
1938       return NULL;
1939     }
1940
1941   offs = 0;
1942 #ifdef G_OS_WIN32
1943   /* Drop localhost */
1944   if (hostname && *hostname != NULL &&
1945       g_ascii_strcasecmp (*hostname, "localhost") == 0)
1946     {
1947       g_free (*hostname);
1948       *hostname = NULL;
1949     }
1950
1951   /* Turn slashes into backslashes, because that's the canonical spelling */
1952   p = filename;
1953   while ((slash = strchr (p, '/')) != NULL)
1954     {
1955       *slash = '\\';
1956       p = slash + 1;
1957     }
1958
1959   /* Windows URIs with a drive letter can be like "file://host/c:/foo"
1960    * or "file://host/c|/foo" (some Netscape versions). In those cases, start
1961    * the filename from the drive letter.
1962    */
1963   if (g_ascii_isalpha (filename[1]))
1964     {
1965       if (filename[2] == ':')
1966         offs = 1;
1967       else if (filename[2] == '|')
1968         {
1969           filename[2] = ':';
1970           offs = 1;
1971         }
1972     }
1973 #endif
1974
1975   result = g_strdup (filename + offs);
1976   g_free (filename);
1977
1978   return result;
1979 }
1980
1981 #if defined (G_OS_WIN32) && !defined (_WIN64)
1982
1983 #undef g_filename_from_uri
1984
1985 gchar *
1986 g_filename_from_uri (const gchar *uri,
1987                      gchar      **hostname,
1988                      GError     **error)
1989 {
1990   gchar *utf8_filename;
1991   gchar *retval = NULL;
1992
1993   utf8_filename = g_filename_from_uri_utf8 (uri, hostname, error);
1994   if (utf8_filename)
1995     {
1996       retval = g_locale_from_utf8 (utf8_filename, -1, NULL, NULL, error);
1997       g_free (utf8_filename);
1998     }
1999   return retval;
2000 }
2001
2002 #endif
2003
2004 /**
2005  * g_filename_to_uri:
2006  * @filename: an absolute filename specified in the GLib file name encoding,
2007  *            which is the on-disk file name bytes on Unix, and UTF-8 on 
2008  *            Windows
2009  * @hostname: A UTF-8 encoded hostname, or %NULL for none.
2010  * @error: location to store the error occuring, or %NULL to ignore
2011  *         errors. Any of the errors in #GConvertError may occur.
2012  * 
2013  * Converts an absolute filename to an escaped ASCII-encoded URI, with the path
2014  * component following Section 3.3. of RFC 2396.
2015  * 
2016  * Return value: a newly-allocated string holding the resulting
2017  *               URI, or %NULL on an error.
2018  **/
2019 gchar *
2020 g_filename_to_uri (const gchar *filename,
2021                    const gchar *hostname,
2022                    GError     **error)
2023 {
2024   char *escaped_uri;
2025
2026   g_return_val_if_fail (filename != NULL, NULL);
2027
2028   if (!g_path_is_absolute (filename))
2029     {
2030       g_set_error (error, G_CONVERT_ERROR, G_CONVERT_ERROR_NOT_ABSOLUTE_PATH,
2031                    _("The pathname '%s' is not an absolute path"),
2032                    filename);
2033       return NULL;
2034     }
2035
2036   if (hostname &&
2037       !(g_utf8_validate (hostname, -1, NULL)
2038         && hostname_validate (hostname)))
2039     {
2040       g_set_error_literal (error, G_CONVERT_ERROR, G_CONVERT_ERROR_ILLEGAL_SEQUENCE,
2041                            _("Invalid hostname"));
2042       return NULL;
2043     }
2044   
2045 #ifdef G_OS_WIN32
2046   /* Don't use localhost unnecessarily */
2047   if (hostname && g_ascii_strcasecmp (hostname, "localhost") == 0)
2048     hostname = NULL;
2049 #endif
2050
2051   escaped_uri = g_escape_file_uri (hostname, filename);
2052
2053   return escaped_uri;
2054 }
2055
2056 #if defined (G_OS_WIN32) && !defined (_WIN64)
2057
2058 #undef g_filename_to_uri
2059
2060 gchar *
2061 g_filename_to_uri (const gchar *filename,
2062                    const gchar *hostname,
2063                    GError     **error)
2064 {
2065   gchar *utf8_filename;
2066   gchar *retval = NULL;
2067
2068   utf8_filename = g_locale_to_utf8 (filename, -1, NULL, NULL, error);
2069
2070   if (utf8_filename)
2071     {
2072       retval = g_filename_to_uri_utf8 (utf8_filename, hostname, error);
2073       g_free (utf8_filename);
2074     }
2075
2076   return retval;
2077 }
2078
2079 #endif
2080
2081 /**
2082  * g_uri_list_extract_uris:
2083  * @uri_list: an URI list 
2084  *
2085  * Splits an URI list conforming to the text/uri-list
2086  * mime type defined in RFC 2483 into individual URIs,
2087  * discarding any comments. The URIs are not validated.
2088  *
2089  * Returns: a newly allocated %NULL-terminated list of
2090  *   strings holding the individual URIs. The array should
2091  *   be freed with g_strfreev().
2092  *
2093  * Since: 2.6
2094  */
2095 gchar **
2096 g_uri_list_extract_uris (const gchar *uri_list)
2097 {
2098   GSList *uris, *u;
2099   const gchar *p, *q;
2100   gchar **result;
2101   gint n_uris = 0;
2102
2103   uris = NULL;
2104
2105   p = uri_list;
2106
2107   /* We don't actually try to validate the URI according to RFC
2108    * 2396, or even check for allowed characters - we just ignore
2109    * comments and trim whitespace off the ends.  We also
2110    * allow LF delimination as well as the specified CRLF.
2111    *
2112    * We do allow comments like specified in RFC 2483.
2113    */
2114   while (p)
2115     {
2116       if (*p != '#')
2117         {
2118           while (g_ascii_isspace (*p))
2119             p++;
2120
2121           q = p;
2122           while (*q && (*q != '\n') && (*q != '\r'))
2123             q++;
2124
2125           if (q > p)
2126             {
2127               q--;
2128               while (q > p && g_ascii_isspace (*q))
2129                 q--;
2130
2131               if (q > p)
2132                 {
2133                   uris = g_slist_prepend (uris, g_strndup (p, q - p + 1));
2134                   n_uris++;
2135                 }
2136             }
2137         }
2138       p = strchr (p, '\n');
2139       if (p)
2140         p++;
2141     }
2142
2143   result = g_new (gchar *, n_uris + 1);
2144
2145   result[n_uris--] = NULL;
2146   for (u = uris; u; u = u->next)
2147     result[n_uris--] = u->data;
2148
2149   g_slist_free (uris);
2150
2151   return result;
2152 }
2153
2154 /**
2155  * g_filename_display_basename:
2156  * @filename: an absolute pathname in the GLib file name encoding
2157  *
2158  * Returns the display basename for the particular filename, guaranteed
2159  * to be valid UTF-8. The display name might not be identical to the filename,
2160  * for instance there might be problems converting it to UTF-8, and some files
2161  * can be translated in the display.
2162  *
2163  * If GLib can not make sense of the encoding of @filename, as a last resort it 
2164  * replaces unknown characters with U+FFFD, the Unicode replacement character.
2165  * You can search the result for the UTF-8 encoding of this character (which is
2166  * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2167  * encoding.
2168  *
2169  * You must pass the whole absolute pathname to this functions so that
2170  * translation of well known locations can be done.
2171  *
2172  * This function is preferred over g_filename_display_name() if you know the
2173  * whole path, as it allows translation.
2174  *
2175  * Return value: a newly allocated string containing
2176  *   a rendition of the basename of the filename in valid UTF-8
2177  *
2178  * Since: 2.6
2179  **/
2180 gchar *
2181 g_filename_display_basename (const gchar *filename)
2182 {
2183   char *basename;
2184   char *display_name;
2185
2186   g_return_val_if_fail (filename != NULL, NULL);
2187   
2188   basename = g_path_get_basename (filename);
2189   display_name = g_filename_display_name (basename);
2190   g_free (basename);
2191   return display_name;
2192 }
2193
2194 /**
2195  * g_filename_display_name:
2196  * @filename: a pathname hopefully in the GLib file name encoding
2197  * 
2198  * Converts a filename into a valid UTF-8 string. The conversion is 
2199  * not necessarily reversible, so you should keep the original around 
2200  * and use the return value of this function only for display purposes.
2201  * Unlike g_filename_to_utf8(), the result is guaranteed to be non-%NULL 
2202  * even if the filename actually isn't in the GLib file name encoding.
2203  *
2204  * If GLib can not make sense of the encoding of @filename, as a last resort it 
2205  * replaces unknown characters with U+FFFD, the Unicode replacement character.
2206  * You can search the result for the UTF-8 encoding of this character (which is
2207  * "\357\277\275" in octal notation) to find out if @filename was in an invalid
2208  * encoding.
2209  *
2210  * If you know the whole pathname of the file you should use
2211  * g_filename_display_basename(), since that allows location-based
2212  * translation of filenames.
2213  *
2214  * Return value: a newly allocated string containing
2215  *   a rendition of the filename in valid UTF-8
2216  *
2217  * Since: 2.6
2218  **/
2219 gchar *
2220 g_filename_display_name (const gchar *filename)
2221 {
2222   gint i;
2223   const gchar **charsets;
2224   gchar *display_name = NULL;
2225   gboolean is_utf8;
2226  
2227   is_utf8 = g_get_filename_charsets (&charsets);
2228
2229   if (is_utf8)
2230     {
2231       if (g_utf8_validate (filename, -1, NULL))
2232         display_name = g_strdup (filename);
2233     }
2234   
2235   if (!display_name)
2236     {
2237       /* Try to convert from the filename charsets to UTF-8.
2238        * Skip the first charset if it is UTF-8.
2239        */
2240       for (i = is_utf8 ? 1 : 0; charsets[i]; i++)
2241         {
2242           display_name = g_convert (filename, -1, "UTF-8", charsets[i], 
2243                                     NULL, NULL, NULL);
2244
2245           if (display_name)
2246             break;
2247         }
2248     }
2249   
2250   /* if all conversions failed, we replace invalid UTF-8
2251    * by a question mark
2252    */
2253   if (!display_name) 
2254     display_name = _g_utf8_make_valid (filename);
2255
2256   return display_name;
2257 }