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