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