Update NEWS
[platform/upstream/glib.git] / glib / gutils.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29  */
30
31 #include "config.h"
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <locale.h>
40 #include <string.h>
41 #include <ctype.h>              /* For tolower() */
42 #include <errno.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #ifdef HAVE_PWD_H
46 #include <pwd.h>
47 #endif
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_CRT_EXTERNS_H 
53 #include <crt_externs.h> /* for _NSGetEnviron */
54 #endif
55
56 /* implement gutils's inline functions
57  */
58 #define G_IMPLEMENT_INLINES 1
59 #define __G_UTILS_C__
60 #include "gutils.h"
61
62 #include "gfileutils.h"
63 #include "ghash.h"
64 #include "gslist.h"
65 #include "gprintfint.h"
66 #include "gthread.h"
67 #include "gthreadprivate.h"
68 #include "gtestutils.h"
69 #include "gunicode.h"
70 #include "gstrfuncs.h"
71 #include "glibintl.h"
72
73 #ifdef G_PLATFORM_WIN32
74 #include "garray.h"
75 #include "gconvert.h"
76 #include "gwin32.h"
77 #endif
78
79 #ifdef  MAXPATHLEN
80 #define G_PATH_LENGTH   MAXPATHLEN
81 #elif   defined (PATH_MAX)
82 #define G_PATH_LENGTH   PATH_MAX
83 #elif   defined (_PC_PATH_MAX)
84 #define G_PATH_LENGTH   sysconf(_PC_PATH_MAX)
85 #else   
86 #define G_PATH_LENGTH   2048
87 #endif
88
89 #ifdef G_PLATFORM_WIN32
90 #  define STRICT                /* Strict typing, please */
91 #  include <windows.h>
92 #  undef STRICT
93 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
94 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
95 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
96 #  endif
97 #  include <lmcons.h>           /* For UNLEN */
98 #endif /* G_PLATFORM_WIN32 */
99
100 #ifdef G_OS_WIN32
101 #  include <direct.h>
102 #  include <shlobj.h>
103    /* older SDK (e.g. msvc 5.0) does not have these*/
104 #  ifndef CSIDL_MYMUSIC
105 #    define CSIDL_MYMUSIC 13
106 #  endif
107 #  ifndef CSIDL_MYVIDEO
108 #    define CSIDL_MYVIDEO 14
109 #  endif
110 #  ifndef CSIDL_INTERNET_CACHE
111 #    define CSIDL_INTERNET_CACHE 32
112 #  endif
113 #  ifndef CSIDL_COMMON_APPDATA
114 #    define CSIDL_COMMON_APPDATA 35
115 #  endif
116 #  ifndef CSIDL_MYPICTURES
117 #    define CSIDL_MYPICTURES 0x27
118 #  endif
119 #  ifndef CSIDL_COMMON_DOCUMENTS
120 #    define CSIDL_COMMON_DOCUMENTS 46
121 #  endif
122 #  ifndef CSIDL_PROFILE
123 #    define CSIDL_PROFILE 40
124 #  endif
125 #  include <process.h>
126 #endif
127
128 #ifdef HAVE_CARBON
129 #include <CoreServices/CoreServices.h>
130 #endif
131
132 #ifdef HAVE_CODESET
133 #include <langinfo.h>
134 #endif
135
136 const guint glib_major_version = GLIB_MAJOR_VERSION;
137 const guint glib_minor_version = GLIB_MINOR_VERSION;
138 const guint glib_micro_version = GLIB_MICRO_VERSION;
139 const guint glib_interface_age = GLIB_INTERFACE_AGE;
140 const guint glib_binary_age = GLIB_BINARY_AGE;
141
142 #ifdef G_PLATFORM_WIN32
143
144 static HMODULE glib_dll = NULL;
145
146 #ifdef DLL_EXPORT
147
148 BOOL WINAPI
149 DllMain (HINSTANCE hinstDLL,
150          DWORD     fdwReason,
151          LPVOID    lpvReserved)
152 {
153   if (fdwReason == DLL_PROCESS_ATTACH)
154       glib_dll = hinstDLL;
155
156   return TRUE;
157 }
158
159 #endif
160
161 gchar *
162 _glib_get_dll_directory (void)
163 {
164   gchar *retval;
165   gchar *p;
166   wchar_t wc_fn[MAX_PATH];
167
168 #ifdef DLL_EXPORT
169   if (glib_dll == NULL)
170     return NULL;
171 #endif
172
173   /* This code is different from that in
174    * g_win32_get_package_installation_directory_of_module() in that
175    * here we return the actual folder where the GLib DLL is. We don't
176    * do the check for it being in a "bin" or "lib" subfolder and then
177    * returning the parent of that.
178    *
179    * In a statically built GLib, glib_dll will be NULL and we will
180    * thus look up the application's .exe file's location.
181    */
182   if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
183     return NULL;
184
185   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
186
187   p = strrchr (retval, G_DIR_SEPARATOR);
188   if (p == NULL)
189     {
190       /* Wtf? */
191       return NULL;
192     }
193   *p = '\0';
194
195   return retval;
196 }
197
198 #endif
199
200 /**
201  * glib_check_version:
202  * @required_major: the required major version.
203  * @required_minor: the required minor version.
204  * @required_micro: the required micro version.
205  *
206  * Checks that the GLib library in use is compatible with the
207  * given version. Generally you would pass in the constants
208  * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
209  * as the three arguments to this function; that produces
210  * a check that the library in use is compatible with
211  * the version of GLib the application or module was compiled
212  * against.
213  *
214  * Compatibility is defined by two things: first the version
215  * of the running library is newer than the version
216  * @required_major.required_minor.@required_micro. Second
217  * the running library must be binary compatible with the
218  * version @required_major.required_minor.@required_micro
219  * (same major version.)
220  *
221  * Return value: %NULL if the GLib library is compatible with the
222  *   given version, or a string describing the version mismatch.
223  *   The returned string is owned by GLib and must not be modified
224  *   or freed.
225  *
226  * Since: 2.6
227  **/
228 const gchar *
229 glib_check_version (guint required_major,
230                     guint required_minor,
231                     guint required_micro)
232 {
233   gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
234   gint required_effective_micro = 100 * required_minor + required_micro;
235
236   if (required_major > GLIB_MAJOR_VERSION)
237     return "GLib version too old (major mismatch)";
238   if (required_major < GLIB_MAJOR_VERSION)
239     return "GLib version too new (major mismatch)";
240   if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
241     return "GLib version too new (micro mismatch)";
242   if (required_effective_micro > glib_effective_micro)
243     return "GLib version too old (micro mismatch)";
244   return NULL;
245 }
246
247 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
248 /**
249  * g_memmove: 
250  * @dest: the destination address to copy the bytes to.
251  * @src: the source address to copy the bytes from.
252  * @len: the number of bytes to copy.
253  *
254  * Copies a block of memory @len bytes long, from @src to @dest.
255  * The source and destination areas may overlap.
256  *
257  * In order to use this function, you must include 
258  * <filename>string.h</filename> yourself, because this macro will 
259  * typically simply resolve to memmove() and GLib does not include 
260  * <filename>string.h</filename> for you.
261  */
262 void 
263 g_memmove (gpointer      dest, 
264            gconstpointer src, 
265            gulong        len)
266 {
267   gchar* destptr = dest;
268   const gchar* srcptr = src;
269   if (src + len < dest || dest + len < src)
270     {
271       bcopy (src, dest, len);
272       return;
273     }
274   else if (dest <= src)
275     {
276       while (len--)
277         *(destptr++) = *(srcptr++);
278     }
279   else
280     {
281       destptr += len;
282       srcptr += len;
283       while (len--)
284         *(--destptr) = *(--srcptr);
285     }
286 }
287 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
288
289 #ifdef G_OS_WIN32
290 #undef g_atexit
291 #endif
292
293 /**
294  * g_atexit:
295  * @func: the function to call on normal program termination.
296  * 
297  * Specifies a function to be called at normal program termination.
298  *
299  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
300  * macro that maps to a call to the atexit() function in the C
301  * library. This means that in case the code that calls g_atexit(),
302  * i.e. atexit(), is in a DLL, the function will be called when the
303  * DLL is detached from the program. This typically makes more sense
304  * than that the function is called when the GLib DLL is detached,
305  * which happened earlier when g_atexit() was a function in the GLib
306  * DLL.
307  *
308  * The behaviour of atexit() in the context of dynamically loaded
309  * modules is not formally specified and varies wildly.
310  *
311  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
312  * loaded module which is unloaded before the program terminates might
313  * well cause a crash at program exit.
314  *
315  * Some POSIX systems implement atexit() like Windows, and have each
316  * dynamically loaded module maintain an own atexit chain that is
317  * called when the module is unloaded.
318  *
319  * On other POSIX systems, before a dynamically loaded module is
320  * unloaded, the registered atexit functions (if any) residing in that
321  * module are called, regardless where the code that registered them
322  * resided. This is presumably the most robust approach.
323  *
324  * As can be seen from the above, for portability it's best to avoid
325  * calling g_atexit() (or atexit()) except in the main executable of a
326  * program.
327  */
328 void
329 g_atexit (GVoidFunc func)
330 {
331   gint result;
332   const gchar *error = NULL;
333
334   /* keep this in sync with glib.h */
335
336 #ifdef  G_NATIVE_ATEXIT
337   result = ATEXIT (func);
338   if (result)
339     error = g_strerror (errno);
340 #elif defined (HAVE_ATEXIT)
341 #  ifdef NeXT /* @#%@! NeXTStep */
342   result = !atexit ((void (*)(void)) func);
343   if (result)
344     error = g_strerror (errno);
345 #  else
346   result = atexit ((void (*)(void)) func);
347   if (result)
348     error = g_strerror (errno);
349 #  endif /* NeXT */
350 #elif defined (HAVE_ON_EXIT)
351   result = on_exit ((void (*)(int, void *)) func, NULL);
352   if (result)
353     error = g_strerror (errno);
354 #else
355   result = 0;
356   error = "no implementation";
357 #endif /* G_NATIVE_ATEXIT */
358
359   if (error)
360     g_error ("Could not register atexit() function: %s", error);
361 }
362
363 /* Based on execvp() from GNU Libc.
364  * Some of this code is cut-and-pasted into gspawn.c
365  */
366
367 static gchar*
368 my_strchrnul (const gchar *str, 
369               gchar        c)
370 {
371   gchar *p = (gchar*)str;
372   while (*p && (*p != c))
373     ++p;
374
375   return p;
376 }
377
378 #ifdef G_OS_WIN32
379
380 static gchar *inner_find_program_in_path (const gchar *program);
381
382 gchar*
383 g_find_program_in_path (const gchar *program)
384 {
385   const gchar *last_dot = strrchr (program, '.');
386
387   if (last_dot == NULL ||
388       strchr (last_dot, '\\') != NULL ||
389       strchr (last_dot, '/') != NULL)
390     {
391       const gint program_length = strlen (program);
392       gchar *pathext = g_build_path (";",
393                                      ".exe;.cmd;.bat;.com",
394                                      g_getenv ("PATHEXT"),
395                                      NULL);
396       gchar *p;
397       gchar *decorated_program;
398       gchar *retval;
399
400       p = pathext;
401       do
402         {
403           gchar *q = my_strchrnul (p, ';');
404
405           decorated_program = g_malloc (program_length + (q-p) + 1);
406           memcpy (decorated_program, program, program_length);
407           memcpy (decorated_program+program_length, p, q-p);
408           decorated_program [program_length + (q-p)] = '\0';
409           
410           retval = inner_find_program_in_path (decorated_program);
411           g_free (decorated_program);
412
413           if (retval != NULL)
414             {
415               g_free (pathext);
416               return retval;
417             }
418           p = q;
419         } while (*p++ != '\0');
420       g_free (pathext);
421       return NULL;
422     }
423   else
424     return inner_find_program_in_path (program);
425 }
426
427 #endif
428
429 /**
430  * g_find_program_in_path:
431  * @program: a program name in the GLib file name encoding
432  * 
433  * Locates the first executable named @program in the user's path, in the
434  * same way that execvp() would locate it. Returns an allocated string
435  * with the absolute path name, or %NULL if the program is not found in
436  * the path. If @program is already an absolute path, returns a copy of
437  * @program if @program exists and is executable, and %NULL otherwise.
438  *  
439  * On Windows, if @program does not have a file type suffix, tries
440  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
441  * the <envar>PATHEXT</envar> environment variable. 
442  * 
443  * On Windows, it looks for the file in the same way as CreateProcess() 
444  * would. This means first in the directory where the executing
445  * program was loaded from, then in the current directory, then in the
446  * Windows 32-bit system directory, then in the Windows directory, and
447  * finally in the directories in the <envar>PATH</envar> environment 
448  * variable. If the program is found, the return value contains the 
449  * full name including the type suffix.
450  *
451  * Return value: absolute path, or %NULL
452  **/
453 #ifdef G_OS_WIN32
454 static gchar *
455 inner_find_program_in_path (const gchar *program)
456 #else
457 gchar*
458 g_find_program_in_path (const gchar *program)
459 #endif
460 {
461   const gchar *path, *p;
462   gchar *name, *freeme;
463 #ifdef G_OS_WIN32
464   const gchar *path_copy;
465   gchar *filename = NULL, *appdir = NULL;
466   gchar *sysdir = NULL, *windir = NULL;
467   int n;
468   wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
469     wwindir[MAXPATHLEN];
470 #endif
471   gsize len;
472   gsize pathlen;
473
474   g_return_val_if_fail (program != NULL, NULL);
475
476   /* If it is an absolute path, or a relative path including subdirectories,
477    * don't look in PATH.
478    */
479   if (g_path_is_absolute (program)
480       || strchr (program, G_DIR_SEPARATOR) != NULL
481 #ifdef G_OS_WIN32
482       || strchr (program, '/') != NULL
483 #endif
484       )
485     {
486       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
487           !g_file_test (program, G_FILE_TEST_IS_DIR))
488         return g_strdup (program);
489       else
490         return NULL;
491     }
492   
493   path = g_getenv ("PATH");
494 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
495   if (path == NULL)
496     {
497       /* There is no `PATH' in the environment.  The default
498        * search path in GNU libc is the current directory followed by
499        * the path `confstr' returns for `_CS_PATH'.
500        */
501       
502       /* In GLib we put . last, for security, and don't use the
503        * unportable confstr(); UNIX98 does not actually specify
504        * what to search if PATH is unset. POSIX may, dunno.
505        */
506       
507       path = "/bin:/usr/bin:.";
508     }
509 #else
510   n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
511   if (n > 0 && n < MAXPATHLEN)
512     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
513   
514   n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
515   if (n > 0 && n < MAXPATHLEN)
516     sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
517   
518   n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
519   if (n > 0 && n < MAXPATHLEN)
520     windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
521   
522   if (filename)
523     {
524       appdir = g_path_get_dirname (filename);
525       g_free (filename);
526     }
527   
528   path = g_strdup (path);
529
530   if (windir)
531     {
532       const gchar *tem = path;
533       path = g_strconcat (windir, ";", path, NULL);
534       g_free ((gchar *) tem);
535       g_free (windir);
536     }
537   
538   if (sysdir)
539     {
540       const gchar *tem = path;
541       path = g_strconcat (sysdir, ";", path, NULL);
542       g_free ((gchar *) tem);
543       g_free (sysdir);
544     }
545   
546   {
547     const gchar *tem = path;
548     path = g_strconcat (".;", path, NULL);
549     g_free ((gchar *) tem);
550   }
551   
552   if (appdir)
553     {
554       const gchar *tem = path;
555       path = g_strconcat (appdir, ";", path, NULL);
556       g_free ((gchar *) tem);
557       g_free (appdir);
558     }
559
560   path_copy = path;
561 #endif
562   
563   len = strlen (program) + 1;
564   pathlen = strlen (path);
565   freeme = name = g_malloc (pathlen + len + 1);
566   
567   /* Copy the file name at the top, including '\0'  */
568   memcpy (name + pathlen + 1, program, len);
569   name = name + pathlen;
570   /* And add the slash before the filename  */
571   *name = G_DIR_SEPARATOR;
572   
573   p = path;
574   do
575     {
576       char *startp;
577
578       path = p;
579       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
580
581       if (p == path)
582         /* Two adjacent colons, or a colon at the beginning or the end
583          * of `PATH' means to search the current directory.
584          */
585         startp = name + 1;
586       else
587         startp = memcpy (name - (p - path), path, p - path);
588
589       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
590           !g_file_test (startp, G_FILE_TEST_IS_DIR))
591         {
592           gchar *ret;
593           ret = g_strdup (startp);
594           g_free (freeme);
595 #ifdef G_OS_WIN32
596           g_free ((gchar *) path_copy);
597 #endif
598           return ret;
599         }
600     }
601   while (*p++ != '\0');
602   
603   g_free (freeme);
604 #ifdef G_OS_WIN32
605   g_free ((gchar *) path_copy);
606 #endif
607
608   return NULL;
609 }
610
611 static gboolean
612 debug_key_matches (const gchar *key,
613                    const gchar *token,
614                    guint        length)
615 {
616   for (; length; length--, key++, token++)
617     {
618       char k = (*key   == '_') ? '-' : tolower (*key  );
619       char t = (*token == '_') ? '-' : tolower (*token);
620
621       if (k != t)
622         return FALSE;
623     }
624
625   return *key == '\0';
626 }
627
628 /**
629  * g_parse_debug_string:
630  * @string: a list of debug options separated by colons, spaces, or
631  * commas, or %NULL.
632  * @keys: pointer to an array of #GDebugKey which associate 
633  *     strings with bit flags.
634  * @nkeys: the number of #GDebugKey<!-- -->s in the array.
635  *
636  * Parses a string containing debugging options
637  * into a %guint containing bit flags. This is used 
638  * within GDK and GTK+ to parse the debug options passed on the
639  * command line or through environment variables.
640  *
641  * If @string is equal to "all", all flags are set.  If @string
642  * is equal to "help", all the available keys in @keys are printed
643  * out to standard error.
644  *
645  * Returns: the combined set of bit flags.
646  */
647 guint        
648 g_parse_debug_string  (const gchar     *string, 
649                        const GDebugKey *keys, 
650                        guint            nkeys)
651 {
652   guint i;
653   guint result = 0;
654   
655   if (string == NULL)
656     return 0;
657
658   /* this function is used by gmem.c/gslice.c initialization code,
659    * so introducing malloc dependencies here would require adaptions
660    * of those code portions.
661    */
662   
663   if (!g_ascii_strcasecmp (string, "all"))
664     {
665       for (i=0; i<nkeys; i++)
666         result |= keys[i].value;
667     }
668   else if (!g_ascii_strcasecmp (string, "help"))
669     {
670       /* using stdio directly for the reason stated above */
671       fprintf (stderr, "Supported debug values: ");
672       for (i=0; i<nkeys; i++)
673         fprintf (stderr, " %s", keys[i].key);
674       fprintf (stderr, "\n");
675     }
676   else
677     {
678       const gchar *p = string;
679       const gchar *q;
680       
681       while (*p)
682         {
683           q = strpbrk (p, ":;, \t");
684           if (!q)
685             q = p + strlen(p);
686           
687           for (i = 0; i < nkeys; i++)
688             if (debug_key_matches (keys[i].key, p, q - p))
689               result |= keys[i].value;
690           
691           p = q;
692           if (*p)
693             p++;
694         }
695     }
696   
697   return result;
698 }
699
700 /**
701  * g_basename:
702  * @file_name: the name of the file.
703  * 
704  * Gets the name of the file without any leading directory components.  
705  * It returns a pointer into the given file name string.
706  * 
707  * Return value: the name of the file without any leading directory components.
708  *
709  * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
710  * g_path_get_basename() allocates new memory for the returned string, unlike
711  * this function which returns a pointer into the argument.
712  **/
713 G_CONST_RETURN gchar*
714 g_basename (const gchar    *file_name)
715 {
716   register gchar *base;
717   
718   g_return_val_if_fail (file_name != NULL, NULL);
719   
720   base = strrchr (file_name, G_DIR_SEPARATOR);
721
722 #ifdef G_OS_WIN32
723   {
724     gchar *q = strrchr (file_name, '/');
725     if (base == NULL || (q != NULL && q > base))
726         base = q;
727   }
728 #endif
729
730   if (base)
731     return base + 1;
732
733 #ifdef G_OS_WIN32
734   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
735     return (gchar*) file_name + 2;
736 #endif /* G_OS_WIN32 */
737   
738   return (gchar*) file_name;
739 }
740
741 /**
742  * g_path_get_basename:
743  * @file_name: the name of the file.
744  *
745  * Gets the last component of the filename. If @file_name ends with a 
746  * directory separator it gets the component before the last slash. If 
747  * @file_name consists only of directory separators (and on Windows, 
748  * possibly a drive letter), a single separator is returned. If
749  * @file_name is empty, it gets ".".
750  *
751  * Return value: a newly allocated string containing the last component of 
752  *   the filename.
753  */
754 gchar*
755 g_path_get_basename (const gchar   *file_name)
756 {
757   register gssize base;             
758   register gssize last_nonslash;    
759   gsize len;    
760   gchar *retval;
761  
762   g_return_val_if_fail (file_name != NULL, NULL);
763
764   if (file_name[0] == '\0')
765     /* empty string */
766     return g_strdup (".");
767   
768   last_nonslash = strlen (file_name) - 1;
769
770   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
771     last_nonslash--;
772
773   if (last_nonslash == -1)
774     /* string only containing slashes */
775     return g_strdup (G_DIR_SEPARATOR_S);
776
777 #ifdef G_OS_WIN32
778   if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
779     /* string only containing slashes and a drive */
780     return g_strdup (G_DIR_SEPARATOR_S);
781 #endif /* G_OS_WIN32 */
782
783   base = last_nonslash;
784
785   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
786     base--;
787
788 #ifdef G_OS_WIN32
789   if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
790     base = 1;
791 #endif /* G_OS_WIN32 */
792
793   len = last_nonslash - base;
794   retval = g_malloc (len + 1);
795   memcpy (retval, file_name + base + 1, len);
796   retval [len] = '\0';
797   return retval;
798 }
799
800 /**
801  * g_path_is_absolute:
802  * @file_name: a file name.
803  *
804  * Returns %TRUE if the given @file_name is an absolute file name.
805  * Note that this is a somewhat vague concept on Windows.
806  *
807  * On POSIX systems, an absolute file name is well-defined. It always
808  * starts from the single root directory. For example "/usr/local".
809  *
810  * On Windows, the concepts of current drive and drive-specific
811  * current directory introduce vagueness. This function interprets as
812  * an absolute file name one that either begins with a directory
813  * separator such as "\Users\tml" or begins with the root on a drive,
814  * for example "C:\Windows". The first case also includes UNC paths
815  * such as "\\myserver\docs\foo". In all cases, either slashes or
816  * backslashes are accepted.
817  *
818  * Note that a file name relative to the current drive root does not
819  * truly specify a file uniquely over time and across processes, as
820  * the current drive is a per-process value and can be changed.
821  *
822  * File names relative the current directory on some specific drive,
823  * such as "D:foo/bar", are not interpreted as absolute by this
824  * function, but they obviously are not relative to the normal current
825  * directory as returned by getcwd() or g_get_current_dir()
826  * either. Such paths should be avoided, or need to be handled using
827  * Windows-specific code.
828  *
829  * Returns: %TRUE if @file_name is absolute. 
830  */
831 gboolean
832 g_path_is_absolute (const gchar *file_name)
833 {
834   g_return_val_if_fail (file_name != NULL, FALSE);
835   
836   if (G_IS_DIR_SEPARATOR (file_name[0]))
837     return TRUE;
838
839 #ifdef G_OS_WIN32
840   /* Recognize drive letter on native Windows */
841   if (g_ascii_isalpha (file_name[0]) && 
842       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
843     return TRUE;
844 #endif /* G_OS_WIN32 */
845
846   return FALSE;
847 }
848
849 /**
850  * g_path_skip_root:
851  * @file_name: a file name.
852  *
853  * Returns a pointer into @file_name after the root component, i.e. after
854  * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
855  * path it returns %NULL.
856  *
857  * Returns: a pointer into @file_name after the root component.
858  */
859 G_CONST_RETURN gchar*
860 g_path_skip_root (const gchar *file_name)
861 {
862   g_return_val_if_fail (file_name != NULL, NULL);
863   
864 #ifdef G_PLATFORM_WIN32
865   /* Skip \\server\share or //server/share */
866   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
867       G_IS_DIR_SEPARATOR (file_name[1]) &&
868       file_name[2] &&
869       !G_IS_DIR_SEPARATOR (file_name[2]))
870     {
871       gchar *p;
872
873       p = strchr (file_name + 2, G_DIR_SEPARATOR);
874 #ifdef G_OS_WIN32
875       {
876         gchar *q = strchr (file_name + 2, '/');
877         if (p == NULL || (q != NULL && q < p))
878           p = q;
879       }
880 #endif
881       if (p &&
882           p > file_name + 2 &&
883           p[1])
884         {
885           file_name = p + 1;
886
887           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
888             file_name++;
889
890           /* Possibly skip a backslash after the share name */
891           if (G_IS_DIR_SEPARATOR (file_name[0]))
892             file_name++;
893
894           return (gchar *)file_name;
895         }
896     }
897 #endif
898   
899   /* Skip initial slashes */
900   if (G_IS_DIR_SEPARATOR (file_name[0]))
901     {
902       while (G_IS_DIR_SEPARATOR (file_name[0]))
903         file_name++;
904       return (gchar *)file_name;
905     }
906
907 #ifdef G_OS_WIN32
908   /* Skip X:\ */
909   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
910     return (gchar *)file_name + 3;
911 #endif
912
913   return NULL;
914 }
915
916 /**
917  * g_path_get_dirname:
918  * @file_name: the name of the file.
919  *
920  * Gets the directory components of a file name.  If the file name has no
921  * directory components "." is returned.  The returned string should be
922  * freed when no longer needed.
923  * 
924  * Returns: the directory components of the file.
925  */
926 gchar*
927 g_path_get_dirname (const gchar    *file_name)
928 {
929   register gchar *base;
930   register gsize len;    
931   
932   g_return_val_if_fail (file_name != NULL, NULL);
933   
934   base = strrchr (file_name, G_DIR_SEPARATOR);
935 #ifdef G_OS_WIN32
936   {
937     gchar *q = strrchr (file_name, '/');
938     if (base == NULL || (q != NULL && q > base))
939         base = q;
940   }
941 #endif
942   if (!base)
943     {
944 #ifdef G_OS_WIN32
945       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
946         {
947           gchar drive_colon_dot[4];
948
949           drive_colon_dot[0] = file_name[0];
950           drive_colon_dot[1] = ':';
951           drive_colon_dot[2] = '.';
952           drive_colon_dot[3] = '\0';
953
954           return g_strdup (drive_colon_dot);
955         }
956 #endif
957     return g_strdup (".");
958     }
959
960   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
961     base--;
962
963 #ifdef G_OS_WIN32
964   /* base points to the char before the last slash.
965    *
966    * In case file_name is the root of a drive (X:\) or a child of the
967    * root of a drive (X:\foo), include the slash.
968    *
969    * In case file_name is the root share of an UNC path
970    * (\\server\share), add a slash, returning \\server\share\ .
971    *
972    * In case file_name is a direct child of a share in an UNC path
973    * (\\server\share\foo), include the slash after the share name,
974    * returning \\server\share\ .
975    */
976   if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
977     base++;
978   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
979            G_IS_DIR_SEPARATOR (file_name[1]) &&
980            file_name[2] &&
981            !G_IS_DIR_SEPARATOR (file_name[2]) &&
982            base >= file_name + 2)
983     {
984       const gchar *p = file_name + 2;
985       while (*p && !G_IS_DIR_SEPARATOR (*p))
986         p++;
987       if (p == base + 1)
988         {
989           len = (guint) strlen (file_name) + 1;
990           base = g_new (gchar, len + 1);
991           strcpy (base, file_name);
992           base[len-1] = G_DIR_SEPARATOR;
993           base[len] = 0;
994           return base;
995         }
996       if (G_IS_DIR_SEPARATOR (*p))
997         {
998           p++;
999           while (*p && !G_IS_DIR_SEPARATOR (*p))
1000             p++;
1001           if (p == base + 1)
1002             base++;
1003         }
1004     }
1005 #endif
1006
1007   len = (guint) 1 + base - file_name;
1008   
1009   base = g_new (gchar, len + 1);
1010   g_memmove (base, file_name, len);
1011   base[len] = 0;
1012   
1013   return base;
1014 }
1015
1016 /**
1017  * g_get_current_dir:
1018  *
1019  * Gets the current directory.
1020  * The returned string should be freed when no longer needed. The encoding 
1021  * of the returned string is system defined. On Windows, it is always UTF-8.
1022  * 
1023  * Returns: the current directory.
1024  */
1025 gchar*
1026 g_get_current_dir (void)
1027 {
1028 #ifdef G_OS_WIN32
1029
1030   gchar *dir = NULL;
1031   wchar_t dummy[2], *wdir;
1032   int len;
1033
1034   len = GetCurrentDirectoryW (2, dummy);
1035   wdir = g_new (wchar_t, len);
1036
1037   if (GetCurrentDirectoryW (len, wdir) == len - 1)
1038     dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1039   
1040   g_free (wdir);
1041
1042   if (dir == NULL)
1043     dir = g_strdup ("\\");
1044
1045   return dir;
1046
1047 #else
1048
1049   gchar *buffer = NULL;
1050   gchar *dir = NULL;
1051   static gulong max_len = 0;
1052
1053   if (max_len == 0) 
1054     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1055   
1056   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1057    * and, if that wasn't bad enough, hangs in doing so.
1058    */
1059 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1060   buffer = g_new (gchar, max_len + 1);
1061   *buffer = 0;
1062   dir = getwd (buffer);
1063 #else   /* !sun || !HAVE_GETCWD */
1064   while (max_len < G_MAXULONG / 2)
1065     {
1066       g_free (buffer);
1067       buffer = g_new (gchar, max_len + 1);
1068       *buffer = 0;
1069       dir = getcwd (buffer, max_len);
1070
1071       if (dir || errno != ERANGE)
1072         break;
1073
1074       max_len *= 2;
1075     }
1076 #endif  /* !sun || !HAVE_GETCWD */
1077   
1078   if (!dir || !*buffer)
1079     {
1080       /* hm, should we g_error() out here?
1081        * this can happen if e.g. "./" has mode \0000
1082        */
1083       buffer[0] = G_DIR_SEPARATOR;
1084       buffer[1] = 0;
1085     }
1086
1087   dir = g_strdup (buffer);
1088   g_free (buffer);
1089   
1090   return dir;
1091 #endif /* !Win32 */
1092 }
1093
1094 /**
1095  * g_getenv:
1096  * @variable: the environment variable to get, in the GLib file name encoding.
1097  * 
1098  * Returns the value of an environment variable. The name and value
1099  * are in the GLib file name encoding. On UNIX, this means the actual
1100  * bytes which might or might not be in some consistent character set
1101  * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1102  * environment variable's value contains references to other
1103  * environment variables, they are expanded.
1104  * 
1105  * Return value: the value of the environment variable, or %NULL if
1106  * the environment variable is not found. The returned string may be
1107  * overwritten by the next call to g_getenv(), g_setenv() or
1108  * g_unsetenv().
1109  **/
1110 G_CONST_RETURN gchar*
1111 g_getenv (const gchar *variable)
1112 {
1113 #ifndef G_OS_WIN32
1114
1115   g_return_val_if_fail (variable != NULL, NULL);
1116
1117   return getenv (variable);
1118
1119 #else /* G_OS_WIN32 */
1120
1121   GQuark quark;
1122   gchar *value;
1123   wchar_t dummy[2], *wname, *wvalue;
1124   int len;
1125
1126   g_return_val_if_fail (variable != NULL, NULL);
1127   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1128
1129   /* On Windows NT, it is relatively typical that environment
1130    * variables contain references to other environment variables. If
1131    * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1132    * environment variables would be stored in the Registry as
1133    * REG_EXPAND_SZ type values, and would then get automatically
1134    * expanded before a program sees them. But there is broken software
1135    * that stores environment variables as REG_SZ values even if they
1136    * contain references to other environment variables.)
1137    */
1138
1139   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1140
1141   len = GetEnvironmentVariableW (wname, dummy, 2);
1142
1143   if (len == 0)
1144     {
1145       g_free (wname);
1146       return NULL;
1147     }
1148   else if (len == 1)
1149     len = 2;
1150
1151   wvalue = g_new (wchar_t, len);
1152
1153   if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1154     {
1155       g_free (wname);
1156       g_free (wvalue);
1157       return NULL;
1158     }
1159
1160   if (wcschr (wvalue, L'%') != NULL)
1161     {
1162       wchar_t *tem = wvalue;
1163
1164       len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1165
1166       if (len > 0)
1167         {
1168           wvalue = g_new (wchar_t, len);
1169
1170           if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1171             {
1172               g_free (wvalue);
1173               wvalue = tem;
1174             }
1175           else
1176             g_free (tem);
1177         }
1178     }
1179
1180   value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1181
1182   g_free (wname);
1183   g_free (wvalue);
1184
1185   quark = g_quark_from_string (value);
1186   g_free (value);
1187   
1188   return g_quark_to_string (quark);
1189
1190 #endif /* G_OS_WIN32 */
1191 }
1192
1193 /* _g_getenv_nomalloc
1194  * this function does a getenv() without doing any kind of allocation
1195  * through glib. it's suitable for chars <= 127 only (both, for the
1196  * variable name and the contents) and for contents < 1024 chars in
1197  * length. also, it aliases "" to a NULL return value.
1198  **/
1199 const gchar*
1200 _g_getenv_nomalloc (const gchar *variable,
1201                     gchar        buffer[1024])
1202 {
1203   const gchar *retval = getenv (variable);
1204   if (retval && retval[0])
1205     {
1206       gint l = strlen (retval);
1207       if (l < 1024)
1208         {
1209           strncpy (buffer, retval, l);
1210           buffer[l] = 0;
1211           return buffer;
1212         }
1213     }
1214   return NULL;
1215 }
1216
1217 /**
1218  * g_setenv:
1219  * @variable: the environment variable to set, must not contain '='.
1220  * @value: the value for to set the variable to.
1221  * @overwrite: whether to change the variable if it already exists.
1222  *
1223  * Sets an environment variable. Both the variable's name and value
1224  * should be in the GLib file name encoding. On UNIX, this means that
1225  * they can be any sequence of bytes. On Windows, they should be in
1226  * UTF-8.
1227  *
1228  * Note that on some systems, when variables are overwritten, the memory 
1229  * used for the previous variables and its value isn't reclaimed.
1230  *
1231  * Returns: %FALSE if the environment variable couldn't be set.
1232  *
1233  * Since: 2.4
1234  */
1235 gboolean
1236 g_setenv (const gchar *variable, 
1237           const gchar *value, 
1238           gboolean     overwrite)
1239 {
1240 #ifndef G_OS_WIN32
1241
1242   gint result;
1243 #ifndef HAVE_SETENV
1244   gchar *string;
1245 #endif
1246
1247   g_return_val_if_fail (variable != NULL, FALSE);
1248   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1249
1250 #ifdef HAVE_SETENV
1251   result = setenv (variable, value, overwrite);
1252 #else
1253   if (!overwrite && getenv (variable) != NULL)
1254     return TRUE;
1255   
1256   /* This results in a leak when you overwrite existing
1257    * settings. It would be fairly easy to fix this by keeping
1258    * our own parallel array or hash table.
1259    */
1260   string = g_strconcat (variable, "=", value, NULL);
1261   result = putenv (string);
1262 #endif
1263   return result == 0;
1264
1265 #else /* G_OS_WIN32 */
1266
1267   gboolean retval;
1268   wchar_t *wname, *wvalue, *wassignment;
1269   gchar *tem;
1270
1271   g_return_val_if_fail (variable != NULL, FALSE);
1272   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1273   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1274   g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1275
1276   if (!overwrite && g_getenv (variable) != NULL)
1277     return TRUE;
1278
1279   /* We want to (if possible) set both the environment variable copy
1280    * kept by the C runtime and the one kept by the system.
1281    *
1282    * We can't use only the C runtime's putenv or _wputenv() as that
1283    * won't work for arbitrary Unicode strings in a "non-Unicode" app
1284    * (with main() and not wmain()). In a "main()" app the C runtime
1285    * initializes the C runtime's environment table by converting the
1286    * real (wide char) environment variables to system codepage, thus
1287    * breaking those that aren't representable in the system codepage.
1288    *
1289    * As the C runtime's putenv() will also set the system copy, we do
1290    * the putenv() first, then call SetEnvironmentValueW ourselves.
1291    */
1292
1293   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1294   wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1295   tem = g_strconcat (variable, "=", value, NULL);
1296   wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1297     
1298   g_free (tem);
1299   _wputenv (wassignment);
1300   g_free (wassignment);
1301
1302   retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1303
1304   g_free (wname);
1305   g_free (wvalue);
1306
1307   return retval;
1308
1309 #endif /* G_OS_WIN32 */
1310 }
1311
1312 #ifdef HAVE__NSGETENVIRON
1313 #define environ (*_NSGetEnviron())
1314 #elif !defined(G_OS_WIN32)
1315
1316 /* According to the Single Unix Specification, environ is not in 
1317  * any system header, although unistd.h often declares it.
1318  */
1319 extern char **environ;
1320 #endif
1321
1322 /**
1323  * g_unsetenv:
1324  * @variable: the environment variable to remove, must not contain '='.
1325  * 
1326  * Removes an environment variable from the environment.
1327  *
1328  * Note that on some systems, when variables are overwritten, the memory 
1329  * used for the previous variables and its value isn't reclaimed.
1330  * Furthermore, this function can't be guaranteed to operate in a 
1331  * threadsafe way.
1332  *
1333  * Since: 2.4 
1334  **/
1335 void
1336 g_unsetenv (const gchar *variable)
1337 {
1338 #ifndef G_OS_WIN32
1339
1340 #ifdef HAVE_UNSETENV
1341   g_return_if_fail (variable != NULL);
1342   g_return_if_fail (strchr (variable, '=') == NULL);
1343
1344   unsetenv (variable);
1345 #else /* !HAVE_UNSETENV */
1346   int len;
1347   gchar **e, **f;
1348
1349   g_return_if_fail (variable != NULL);
1350   g_return_if_fail (strchr (variable, '=') == NULL);
1351
1352   len = strlen (variable);
1353   
1354   /* Mess directly with the environ array.
1355    * This seems to be the only portable way to do this.
1356    *
1357    * Note that we remove *all* environment entries for
1358    * the variable name, not just the first.
1359    */
1360   e = f = environ;
1361   while (*e != NULL) 
1362     {
1363       if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=') 
1364         {
1365           *f = *e;
1366           f++;
1367         }
1368       e++;
1369     }
1370   *f = NULL;
1371 #endif /* !HAVE_UNSETENV */
1372
1373 #else  /* G_OS_WIN32 */
1374
1375   wchar_t *wname, *wassignment;
1376   gchar *tem;
1377
1378   g_return_if_fail (variable != NULL);
1379   g_return_if_fail (strchr (variable, '=') == NULL);
1380   g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1381
1382   wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1383   tem = g_strconcat (variable, "=", NULL);
1384   wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1385     
1386   g_free (tem);
1387   _wputenv (wassignment);
1388   g_free (wassignment);
1389
1390   SetEnvironmentVariableW (wname, NULL);
1391
1392   g_free (wname);
1393
1394 #endif /* G_OS_WIN32 */
1395 }
1396
1397 /**
1398  * g_listenv:
1399  *
1400  * Gets the names of all variables set in the environment.
1401  * 
1402  * Returns: a %NULL-terminated list of strings which must be freed
1403  * with g_strfreev().
1404  *
1405  * Programs that want to be portable to Windows should typically use
1406  * this function and g_getenv() instead of using the environ array
1407  * from the C library directly. On Windows, the strings in the environ
1408  * array are in system codepage encoding, while in most of the typical
1409  * use cases for environment variables in GLib-using programs you want
1410  * the UTF-8 encoding that this function and g_getenv() provide.
1411  *
1412  * Since: 2.8
1413  */
1414 gchar **
1415 g_listenv (void)
1416 {
1417 #ifndef G_OS_WIN32
1418   gchar **result, *eq;
1419   gint len, i, j;
1420
1421   len = g_strv_length (environ);
1422   result = g_new0 (gchar *, len + 1);
1423   
1424   j = 0;
1425   for (i = 0; i < len; i++)
1426     {
1427       eq = strchr (environ[i], '=');
1428       if (eq)
1429         result[j++] = g_strndup (environ[i], eq - environ[i]);
1430     }
1431
1432   result[j] = NULL;
1433
1434   return result;
1435 #else
1436   gchar **result, *eq;
1437   gint len = 0, j;
1438   wchar_t *p, *q;
1439
1440   p = (wchar_t *) GetEnvironmentStringsW ();
1441   if (p != NULL)
1442     {
1443       q = p;
1444       while (*q)
1445         {
1446           q += wcslen (q) + 1;
1447           len++;
1448         }
1449     }
1450   result = g_new0 (gchar *, len + 1);
1451
1452   j = 0;
1453   q = p;
1454   while (*q)
1455     {
1456       result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1457       if (result[j] != NULL)
1458         {
1459           eq = strchr (result[j], '=');
1460           if (eq && eq > result[j])
1461             {
1462               *eq = '\0';
1463               j++;
1464             }
1465           else
1466             g_free (result[j]);
1467         }
1468       q += wcslen (q) + 1;
1469     }
1470   result[j] = NULL;
1471   FreeEnvironmentStringsW (p);
1472
1473   return result;
1474 #endif
1475 }
1476
1477 /**
1478  * g_get_environ:
1479  * 
1480  * Gets the list of environment variables for the current process.  The
1481  * list is %NULL terminated and each item in the list is of the form
1482  * 'NAME=VALUE'.
1483  *
1484  * This is equivalent to direct access to the 'environ' global variable,
1485  * except portable.
1486  *
1487  * The return value is freshly allocated and it should be freed with
1488  * g_strfreev() when it is no longer needed.
1489  *
1490  * Returns: the list of environment variables
1491  *
1492  * Since: 2.28
1493  */
1494 gchar **
1495 g_get_environ (void)
1496 {
1497 #ifndef G_OS_WIN32
1498   return g_strdupv (environ);
1499 #else
1500   gunichar2 *strings;
1501   gchar **result;
1502   gint i, n;
1503
1504   strings = GetEnvironmentStringsW ();
1505   for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1506   result = g_new (char *, n + 1);
1507   for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1508     result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1509   FreeEnvironmentStringsW (strings);
1510   result[i] = NULL;
1511
1512   return result;
1513 #endif
1514 }
1515
1516 G_LOCK_DEFINE_STATIC (g_utils_global);
1517
1518 static  gchar   *g_tmp_dir = NULL;
1519 static  gchar   *g_user_name = NULL;
1520 static  gchar   *g_real_name = NULL;
1521 static  gchar   *g_home_dir = NULL;
1522 static  gchar   *g_host_name = NULL;
1523
1524 #ifdef G_OS_WIN32
1525 /* System codepage versions of the above, kept at file level so that they,
1526  * too, are produced only once.
1527  */
1528 static  gchar   *g_tmp_dir_cp = NULL;
1529 static  gchar   *g_user_name_cp = NULL;
1530 static  gchar   *g_real_name_cp = NULL;
1531 static  gchar   *g_home_dir_cp = NULL;
1532 #endif
1533
1534 static  gchar   *g_user_data_dir = NULL;
1535 static  gchar  **g_system_data_dirs = NULL;
1536 static  gchar   *g_user_cache_dir = NULL;
1537 static  gchar   *g_user_config_dir = NULL;
1538 static  gchar  **g_system_config_dirs = NULL;
1539
1540 static  gchar  **g_user_special_dirs = NULL;
1541
1542 /* fifteen minutes of fame for everybody */
1543 #define G_USER_DIRS_EXPIRE      15 * 60
1544
1545 #ifdef G_OS_WIN32
1546
1547 static gchar *
1548 get_special_folder (int csidl)
1549 {
1550   wchar_t path[MAX_PATH+1];
1551   HRESULT hr;
1552   LPITEMIDLIST pidl = NULL;
1553   BOOL b;
1554   gchar *retval = NULL;
1555
1556   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1557   if (hr == S_OK)
1558     {
1559       b = SHGetPathFromIDListW (pidl, path);
1560       if (b)
1561         retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1562       CoTaskMemFree (pidl);
1563     }
1564   return retval;
1565 }
1566
1567 static char *
1568 get_windows_directory_root (void)
1569 {
1570   wchar_t wwindowsdir[MAX_PATH];
1571
1572   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1573     {
1574       /* Usually X:\Windows, but in terminal server environments
1575        * might be an UNC path, AFAIK.
1576        */
1577       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1578       char *p;
1579
1580       if (windowsdir == NULL)
1581         return g_strdup ("C:\\");
1582
1583       p = (char *) g_path_skip_root (windowsdir);
1584       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1585         p--;
1586       *p = '\0';
1587       return windowsdir;
1588     }
1589   else
1590     return g_strdup ("C:\\");
1591 }
1592
1593 #endif
1594
1595 /* HOLDS: g_utils_global_lock */
1596 static void
1597 g_get_any_init_do (void)
1598 {
1599   gchar hostname[100];
1600
1601   g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1602   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1603     g_tmp_dir = g_strdup (g_getenv ("TMP"));
1604   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1605     g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1606
1607 #ifdef G_OS_WIN32
1608   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1609     g_tmp_dir = get_windows_directory_root ();
1610 #else  
1611 #ifdef P_tmpdir
1612   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1613     {
1614       gsize k;    
1615       g_tmp_dir = g_strdup (P_tmpdir);
1616       k = strlen (g_tmp_dir);
1617       if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1618         g_tmp_dir[k - 1] = '\0';
1619     }
1620 #endif
1621   
1622   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1623     {
1624       g_tmp_dir = g_strdup ("/tmp");
1625     }
1626 #endif  /* !G_OS_WIN32 */
1627   
1628 #ifdef G_OS_WIN32
1629   /* We check $HOME first for Win32, though it is a last resort for Unix
1630    * where we prefer the results of getpwuid().
1631    */
1632   g_home_dir = g_strdup (g_getenv ("HOME"));
1633
1634   /* Only believe HOME if it is an absolute path and exists */
1635   if (g_home_dir)
1636     {
1637       if (!(g_path_is_absolute (g_home_dir) &&
1638             g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1639         {
1640           g_free (g_home_dir);
1641           g_home_dir = NULL;
1642         }
1643     }
1644   
1645   /* In case HOME is Unix-style (it happens), convert it to
1646    * Windows style.
1647    */
1648   if (g_home_dir)
1649     {
1650       gchar *p;
1651       while ((p = strchr (g_home_dir, '/')) != NULL)
1652         *p = '\\';
1653     }
1654
1655   if (!g_home_dir)
1656     {
1657       /* USERPROFILE is probably the closest equivalent to $HOME? */
1658       if (g_getenv ("USERPROFILE") != NULL)
1659         g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1660     }
1661
1662   if (!g_home_dir)
1663     g_home_dir = get_special_folder (CSIDL_PROFILE);
1664   
1665   if (!g_home_dir)
1666     g_home_dir = get_windows_directory_root ();
1667 #endif /* G_OS_WIN32 */
1668   
1669 #ifdef HAVE_PWD_H
1670   {
1671     struct passwd *pw = NULL;
1672     gpointer buffer = NULL;
1673     gint error;
1674     gchar *logname;
1675
1676 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1677     struct passwd pwd;
1678 #    ifdef _SC_GETPW_R_SIZE_MAX  
1679     /* This reurns the maximum length */
1680     glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1681     
1682     if (bufsize < 0)
1683       bufsize = 64;
1684 #    else /* _SC_GETPW_R_SIZE_MAX */
1685     glong bufsize = 64;
1686 #    endif /* _SC_GETPW_R_SIZE_MAX */
1687
1688     logname = (gchar *) g_getenv ("LOGNAME");
1689         
1690     do
1691       {
1692         g_free (buffer);
1693         /* we allocate 6 extra bytes to work around a bug in 
1694          * Mac OS < 10.3. See #156446
1695          */
1696         buffer = g_malloc (bufsize + 6);
1697         errno = 0;
1698         
1699 #    ifdef HAVE_POSIX_GETPWUID_R
1700         if (logname) {
1701           error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1702           if (!pw || (pw->pw_uid != getuid ())) {
1703             /* LOGNAME is lying, fall back to looking up the uid */
1704             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1705           }
1706         } else {
1707           error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1708         }
1709         error = error < 0 ? errno : error;
1710 #    else /* HAVE_NONPOSIX_GETPWUID_R */
1711    /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1712 #      if defined(_AIX) || defined(__hpux)
1713         error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1714         pw = error == 0 ? &pwd : NULL;
1715 #      else /* !_AIX */
1716         if (logname) {
1717           pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1718           if (!pw || (pw->pw_uid != getuid ())) {
1719             /* LOGNAME is lying, fall back to looking up the uid */
1720             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1721           }
1722         } else {
1723           pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1724         }
1725         error = pw ? 0 : errno;
1726 #      endif /* !_AIX */            
1727 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
1728         
1729         if (!pw)
1730           {
1731             /* we bail out prematurely if the user id can't be found
1732              * (should be pretty rare case actually), or if the buffer
1733              * should be sufficiently big and lookups are still not
1734              * successfull.
1735              */
1736             if (error == 0 || error == ENOENT)
1737               {
1738                 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1739                            (gulong) getuid ());
1740                 break;
1741               }
1742             if (bufsize > 32 * 1024)
1743               {
1744                 g_warning ("getpwuid_r(): failed due to: %s.",
1745                            g_strerror (error));
1746                 break;
1747               }
1748             
1749             bufsize *= 2;
1750           }
1751       }
1752     while (!pw);
1753 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1754     
1755     if (!pw)
1756       {
1757         setpwent ();
1758         pw = getpwuid (getuid ());
1759         endpwent ();
1760       }
1761     if (pw)
1762       {
1763         g_user_name = g_strdup (pw->pw_name);
1764
1765         if (pw->pw_gecos && *pw->pw_gecos != '\0') 
1766           {
1767             gchar **gecos_fields;
1768             gchar **name_parts;
1769
1770             /* split the gecos field and substitute '&' */
1771             gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1772             name_parts = g_strsplit (gecos_fields[0], "&", 0);
1773             pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1774             g_real_name = g_strjoinv (pw->pw_name, name_parts);
1775             g_strfreev (gecos_fields);
1776             g_strfreev (name_parts);
1777           }
1778
1779         if (!g_home_dir)
1780           g_home_dir = g_strdup (pw->pw_dir);
1781       }
1782     g_free (buffer);
1783   }
1784   
1785 #else /* !HAVE_PWD_H */
1786   
1787 #ifdef G_OS_WIN32
1788   {
1789     guint len = UNLEN+1;
1790     wchar_t buffer[UNLEN+1];
1791     
1792     if (GetUserNameW (buffer, (LPDWORD) &len))
1793       {
1794         g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1795         g_real_name = g_strdup (g_user_name);
1796       }
1797   }
1798 #endif /* G_OS_WIN32 */
1799
1800 #endif /* !HAVE_PWD_H */
1801
1802 #ifndef G_OS_WIN32
1803   if (!g_home_dir)
1804     g_home_dir = g_strdup (g_getenv ("HOME"));
1805 #endif
1806
1807 #ifdef __EMX__
1808   /* change '\\' in %HOME% to '/' */
1809   g_strdelimit (g_home_dir, "\\",'/');
1810 #endif
1811   if (!g_user_name)
1812     g_user_name = g_strdup ("somebody");
1813   if (!g_real_name)
1814     g_real_name = g_strdup ("Unknown");
1815
1816   {
1817 #ifndef G_OS_WIN32
1818     gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1819 #else
1820     DWORD size = sizeof (hostname);
1821     gboolean hostname_fail = (!GetComputerName (hostname, &size));
1822 #endif
1823     g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1824   }
1825
1826 #ifdef G_OS_WIN32
1827   g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1828   g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1829   g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1830
1831   if (!g_tmp_dir_cp)
1832     g_tmp_dir_cp = g_strdup ("\\");
1833   if (!g_user_name_cp)
1834     g_user_name_cp = g_strdup ("somebody");
1835   if (!g_real_name_cp)
1836     g_real_name_cp = g_strdup ("Unknown");
1837
1838   /* home_dir might be NULL, unlike tmp_dir, user_name and
1839    * real_name.
1840    */
1841   if (g_home_dir)
1842     g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1843   else
1844     g_home_dir_cp = NULL;
1845 #endif /* G_OS_WIN32 */
1846 }
1847
1848 static inline void
1849 g_get_any_init (void)
1850 {
1851   if (!g_tmp_dir)
1852     g_get_any_init_do ();
1853 }
1854
1855 static inline void
1856 g_get_any_init_locked (void)
1857 {
1858   G_LOCK (g_utils_global);
1859   g_get_any_init ();
1860   G_UNLOCK (g_utils_global);
1861 }
1862
1863
1864 /**
1865  * g_get_user_name:
1866  *
1867  * Gets the user name of the current user. The encoding of the returned
1868  * string is system-defined. On UNIX, it might be the preferred file name
1869  * encoding, or something else, and there is no guarantee that it is even
1870  * consistent on a machine. On Windows, it is always UTF-8.
1871  *
1872  * Returns: the user name of the current user.
1873  */
1874 G_CONST_RETURN gchar*
1875 g_get_user_name (void)
1876 {
1877   g_get_any_init_locked ();
1878   return g_user_name;
1879 }
1880
1881 /**
1882  * g_get_real_name:
1883  *
1884  * Gets the real name of the user. This usually comes from the user's entry 
1885  * in the <filename>passwd</filename> file. The encoding of the returned 
1886  * string is system-defined. (On Windows, it is, however, always UTF-8.) 
1887  * If the real user name cannot be determined, the string "Unknown" is 
1888  * returned.
1889  *
1890  * Returns: the user's real name.
1891  */
1892 G_CONST_RETURN gchar*
1893 g_get_real_name (void)
1894 {
1895   g_get_any_init_locked ();
1896   return g_real_name;
1897 }
1898
1899 /**
1900  * g_get_home_dir:
1901  *
1902  * Gets the current user's home directory as defined in the 
1903  * password database.
1904  *
1905  * Note that in contrast to traditional UNIX tools, this function 
1906  * prefers <filename>passwd</filename> entries over the <envar>HOME</envar> 
1907  * environment variable. 
1908  *
1909  * One of the reasons for this decision is that applications in many 
1910  * cases need special handling to deal with the case where 
1911  * <envar>HOME</envar> is
1912  * <simplelist>
1913  *   <member>Not owned by the user</member>
1914  *   <member>Not writeable</member>
1915  *   <member>Not even readable</member>
1916  * </simplelist>
1917  * Since applications are in general <emphasis>not</emphasis> written 
1918  * to deal with these situations it was considered better to make 
1919  * g_get_home_dir() not pay attention to <envar>HOME</envar> and to 
1920  * return the real home directory for the user. If applications
1921  * want to pay attention to <envar>HOME</envar>, they can do:
1922  * |[
1923  *  const char *homedir = g_getenv ("HOME");
1924  *   if (!homedir)
1925  *      homedir = g_get_home_dir (<!-- -->);
1926  * ]|
1927  *
1928  * Returns: the current user's home directory
1929  */
1930 G_CONST_RETURN gchar*
1931 g_get_home_dir (void)
1932 {
1933   g_get_any_init_locked ();
1934   return g_home_dir;
1935 }
1936
1937 /**
1938  * g_get_tmp_dir:
1939  *
1940  * Gets the directory to use for temporary files. This is found from 
1941  * inspecting the environment variables <envar>TMPDIR</envar>, 
1942  * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none 
1943  * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. 
1944  * The encoding of the returned string is system-defined. On Windows, 
1945  * it is always UTF-8. The return value is never %NULL or the empty string.
1946  *
1947  * Returns: the directory to use for temporary files.
1948  */
1949 G_CONST_RETURN gchar*
1950 g_get_tmp_dir (void)
1951 {
1952   g_get_any_init_locked ();
1953   return g_tmp_dir;
1954 }
1955
1956 /**
1957  * g_get_host_name:
1958  *
1959  * Return a name for the machine. 
1960  *
1961  * The returned name is not necessarily a fully-qualified domain name,
1962  * or even present in DNS or some other name service at all. It need
1963  * not even be unique on your local network or site, but usually it
1964  * is. Callers should not rely on the return value having any specific
1965  * properties like uniqueness for security purposes. Even if the name
1966  * of the machine is changed while an application is running, the
1967  * return value from this function does not change. The returned
1968  * string is owned by GLib and should not be modified or freed. If no
1969  * name can be determined, a default fixed string "localhost" is
1970  * returned.
1971  *
1972  * Returns: the host name of the machine.
1973  *
1974  * Since: 2.8
1975  */
1976 const gchar *
1977 g_get_host_name (void)
1978 {
1979   g_get_any_init_locked ();
1980   return g_host_name;
1981 }
1982
1983 G_LOCK_DEFINE_STATIC (g_prgname);
1984 static gchar *g_prgname = NULL;
1985
1986 /**
1987  * g_get_prgname:
1988  *
1989  * Gets the name of the program. This name should <emphasis>not</emphasis> 
1990  * be localized, contrast with g_get_application_name().
1991  * (If you are using GDK or GTK+ the program name is set in gdk_init(), 
1992  * which is called by gtk_init(). The program name is found by taking 
1993  * the last component of <literal>argv[0]</literal>.)
1994  *
1995  * Returns: the name of the program. The returned string belongs 
1996  * to GLib and must not be modified or freed.
1997  */
1998 gchar*
1999 g_get_prgname (void)
2000 {
2001   gchar* retval;
2002
2003   G_LOCK (g_prgname);
2004 #ifdef G_OS_WIN32
2005   if (g_prgname == NULL)
2006     {
2007       static gboolean beenhere = FALSE;
2008
2009       if (!beenhere)
2010         {
2011           gchar *utf8_buf = NULL;
2012           wchar_t buf[MAX_PATH+1];
2013
2014           beenhere = TRUE;
2015           if (GetModuleFileNameW (GetModuleHandle (NULL),
2016                                   buf, G_N_ELEMENTS (buf)) > 0)
2017             utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2018
2019           if (utf8_buf)
2020             {
2021               g_prgname = g_path_get_basename (utf8_buf);
2022               g_free (utf8_buf);
2023             }
2024         }
2025     }
2026 #endif
2027   retval = g_prgname;
2028   G_UNLOCK (g_prgname);
2029
2030   return retval;
2031 }
2032
2033 /**
2034  * g_set_prgname:
2035  * @prgname: the name of the program.
2036  *
2037  * Sets the name of the program. This name should <emphasis>not</emphasis> 
2038  * be localized, contrast with g_set_application_name(). Note that for 
2039  * thread-safety reasons this function can only be called once.
2040  */
2041 void
2042 g_set_prgname (const gchar *prgname)
2043 {
2044   G_LOCK (g_prgname);
2045   g_free (g_prgname);
2046   g_prgname = g_strdup (prgname);
2047   G_UNLOCK (g_prgname);
2048 }
2049
2050 G_LOCK_DEFINE_STATIC (g_application_name);
2051 static gchar *g_application_name = NULL;
2052
2053 /**
2054  * g_get_application_name:
2055  * 
2056  * Gets a human-readable name for the application, as set by
2057  * g_set_application_name(). This name should be localized if
2058  * possible, and is intended for display to the user.  Contrast with
2059  * g_get_prgname(), which gets a non-localized name. If
2060  * g_set_application_name() has not been called, returns the result of
2061  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2062  * been called).
2063  * 
2064  * Return value: human-readable application name. may return %NULL
2065  *
2066  * Since: 2.2
2067  **/
2068 G_CONST_RETURN gchar*
2069 g_get_application_name (void)
2070 {
2071   gchar* retval;
2072
2073   G_LOCK (g_application_name);
2074   retval = g_application_name;
2075   G_UNLOCK (g_application_name);
2076
2077   if (retval == NULL)
2078     return g_get_prgname ();
2079   
2080   return retval;
2081 }
2082
2083 /**
2084  * g_set_application_name:
2085  * @application_name: localized name of the application
2086  *
2087  * Sets a human-readable name for the application. This name should be
2088  * localized if possible, and is intended for display to the user.
2089  * Contrast with g_set_prgname(), which sets a non-localized name.
2090  * g_set_prgname() will be called automatically by gtk_init(),
2091  * but g_set_application_name() will not.
2092  *
2093  * Note that for thread safety reasons, this function can only
2094  * be called once.
2095  *
2096  * The application name will be used in contexts such as error messages,
2097  * or when displaying an application's name in the task list.
2098  * 
2099  * Since: 2.2
2100  **/
2101 void
2102 g_set_application_name (const gchar *application_name)
2103 {
2104   gboolean already_set = FALSE;
2105         
2106   G_LOCK (g_application_name);
2107   if (g_application_name)
2108     already_set = TRUE;
2109   else
2110     g_application_name = g_strdup (application_name);
2111   G_UNLOCK (g_application_name);
2112
2113   if (already_set)
2114     g_warning ("g_set_application_name() called multiple times");
2115 }
2116
2117 /**
2118  * g_get_user_data_dir:
2119  * 
2120  * Returns a base directory in which to access application data such
2121  * as icons that is customized for a particular user.  
2122  *
2123  * On UNIX platforms this is determined using the mechanisms described in
2124  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2125  * XDG Base Directory Specification</ulink>.
2126  * In this case the directory retrieved will be XDG_DATA_HOME.
2127  *
2128  * On Windows this is the folder to use for local (as opposed to
2129  * roaming) application data. See documentation for
2130  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2131  * what g_get_user_config_dir() returns.
2132  *
2133  * Return value: a string owned by GLib that must not be modified 
2134  *               or freed.
2135  * Since: 2.6
2136  **/
2137 G_CONST_RETURN gchar*
2138 g_get_user_data_dir (void)
2139 {
2140   gchar *data_dir;  
2141
2142   G_LOCK (g_utils_global);
2143
2144   if (!g_user_data_dir)
2145     {
2146 #ifdef G_OS_WIN32
2147       data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2148 #else
2149       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2150
2151       if (data_dir && data_dir[0])
2152         data_dir = g_strdup (data_dir);
2153 #endif
2154       if (!data_dir || !data_dir[0])
2155         {
2156           g_get_any_init ();
2157
2158           if (g_home_dir)
2159             data_dir = g_build_filename (g_home_dir, ".local", 
2160                                          "share", NULL);
2161           else
2162             data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local", 
2163                                          "share", NULL);
2164         }
2165
2166       g_user_data_dir = data_dir;
2167     }
2168   else
2169     data_dir = g_user_data_dir;
2170
2171   G_UNLOCK (g_utils_global);
2172
2173   return data_dir;
2174 }
2175
2176 static void
2177 g_init_user_config_dir (void)
2178 {
2179   gchar *config_dir;
2180
2181   if (!g_user_config_dir)
2182     {
2183 #ifdef G_OS_WIN32
2184       config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2185 #else
2186       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2187
2188       if (config_dir && config_dir[0])
2189         config_dir = g_strdup (config_dir);
2190 #endif
2191       if (!config_dir || !config_dir[0])
2192         {
2193           g_get_any_init ();
2194
2195           if (g_home_dir)
2196             config_dir = g_build_filename (g_home_dir, ".config", NULL);
2197           else
2198             config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2199         }
2200
2201       g_user_config_dir = config_dir;
2202     }
2203 }
2204
2205 /**
2206  * g_get_user_config_dir:
2207  * 
2208  * Returns a base directory in which to store user-specific application 
2209  * configuration information such as user preferences and settings. 
2210  *
2211  * On UNIX platforms this is determined using the mechanisms described in
2212  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2213  * XDG Base Directory Specification</ulink>.
2214  * In this case the directory retrieved will be XDG_CONFIG_HOME.
2215  *
2216  * On Windows this is the folder to use for local (as opposed to
2217  * roaming) application data. See documentation for
2218  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2219  * what g_get_user_data_dir() returns.
2220  *
2221  * Return value: a string owned by GLib that must not be modified 
2222  *               or freed.
2223  * Since: 2.6
2224  **/
2225 G_CONST_RETURN gchar*
2226 g_get_user_config_dir (void)
2227 {
2228   G_LOCK (g_utils_global);
2229
2230   g_init_user_config_dir ();
2231
2232   G_UNLOCK (g_utils_global);
2233
2234   return g_user_config_dir;
2235 }
2236
2237 /**
2238  * g_get_user_cache_dir:
2239  * 
2240  * Returns a base directory in which to store non-essential, cached
2241  * data specific to particular user.
2242  *
2243  * On UNIX platforms this is determined using the mechanisms described in
2244  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2245  * XDG Base Directory Specification</ulink>.
2246  * In this case the directory retrieved will be XDG_CACHE_HOME.
2247  *
2248  * On Windows is the directory that serves as a common repository for
2249  * temporary Internet files. A typical path is
2250  * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2251  * See documentation for CSIDL_INTERNET_CACHE.
2252  *
2253  * Return value: a string owned by GLib that must not be modified 
2254  *               or freed.
2255  * Since: 2.6
2256  **/
2257 G_CONST_RETURN gchar*
2258 g_get_user_cache_dir (void)
2259 {
2260   gchar *cache_dir;  
2261
2262   G_LOCK (g_utils_global);
2263
2264   if (!g_user_cache_dir)
2265     {
2266 #ifdef G_OS_WIN32
2267       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2268 #else
2269       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2270
2271       if (cache_dir && cache_dir[0])
2272           cache_dir = g_strdup (cache_dir);
2273 #endif
2274       if (!cache_dir || !cache_dir[0])
2275         {
2276           g_get_any_init ();
2277         
2278           if (g_home_dir)
2279             cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2280           else
2281             cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2282         }
2283       g_user_cache_dir = cache_dir;
2284     }
2285   else
2286     cache_dir = g_user_cache_dir;
2287
2288   G_UNLOCK (g_utils_global);
2289
2290   return cache_dir;
2291 }
2292
2293 /**
2294  * g_get_user_runtime_dir:
2295  *
2296  * Returns a directory that is unique to the current user on the local
2297  * system.
2298  *
2299  * On UNIX platforms this is determined using the mechanisms described in
2300  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2301  * XDG Base Directory Specification</ulink>.  This is the directory
2302  * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2303  * In the case that this variable is not set, GLib will issue a warning
2304  * message to stderr and return the value of g_get_user_cache_dir().
2305  *
2306  * On Windows this is the folder to use for local (as opposed to
2307  * roaming) application data. See documentation for
2308  * CSIDL_LOCAL_APPDATA.  Note that on Windows it thus is the same as
2309  * what g_get_user_config_dir() returns.
2310  *
2311  * Returns: a string owned by GLib that must not be modified or freed.
2312  *
2313  * Since: 2.28
2314  **/
2315 const gchar *
2316 g_get_user_runtime_dir (void)
2317 {
2318 #ifndef G_OS_WIN32
2319   static const gchar *runtime_dir;
2320   static gsize initialised;
2321
2322   if (g_once_init_enter (&initialised))
2323     {
2324       runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2325       
2326       if (runtime_dir == NULL)
2327         g_warning ("XDG_RUNTIME_DIR variable not set.  "
2328                    "Falling back to XDG cache dir.");
2329
2330       g_once_init_leave (&initialised, 1);
2331     }
2332
2333   if (runtime_dir)
2334     return runtime_dir;
2335
2336   /* Both fallback for UNIX and the default
2337    * in Windows: use the user cache directory.
2338    */
2339 #endif
2340
2341   return g_get_user_cache_dir ();
2342 }
2343
2344 #ifdef HAVE_CARBON
2345
2346 static gchar *
2347 find_folder (OSType type)
2348 {
2349   gchar *filename = NULL;
2350   FSRef  found;
2351
2352   if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2353     {
2354       CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2355
2356       if (url)
2357         {
2358           CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2359
2360           if (path)
2361             {
2362               filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2363
2364               if (! filename)
2365                 {
2366                   filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2367
2368                   CFStringGetCString (path, filename,
2369                                       CFStringGetLength (path) * 3 + 1,
2370                                       kCFStringEncodingUTF8);
2371                 }
2372
2373               CFRelease (path);
2374             }
2375
2376           CFRelease (url);
2377         }
2378     }
2379
2380   return filename;
2381 }
2382
2383 static void
2384 load_user_special_dirs (void)
2385 {
2386   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2387   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2388   g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2389   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2390   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2391   g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2392   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2393   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2394 }
2395
2396 #endif /* HAVE_CARBON */
2397
2398 #if defined(G_OS_WIN32)
2399 static void
2400 load_user_special_dirs (void)
2401 {
2402   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2403                                                     DWORD dwFlags,
2404                                                     HANDLE hToken,
2405                                                     PWSTR *ppszPath);
2406   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2407
2408   static const GUID FOLDERID_Downloads =
2409     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2410   static const GUID FOLDERID_Public =
2411     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2412
2413   wchar_t *wcp;
2414
2415   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2416                                                                     "SHGetKnownFolderPath");
2417
2418   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2419   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2420
2421   if (p_SHGetKnownFolderPath == NULL)
2422     {
2423       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2424     }
2425   else
2426     {
2427       wcp = NULL;
2428       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2429       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2430       if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2431         g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2432       CoTaskMemFree (wcp);
2433     }
2434
2435   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2436   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2437
2438   if (p_SHGetKnownFolderPath == NULL)
2439     {
2440       /* XXX */
2441       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2442     }
2443   else
2444     {
2445       wcp = NULL;
2446       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2447       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2448       if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2449         g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2450       CoTaskMemFree (wcp);
2451     }
2452   
2453   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2454   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2455 }
2456 #endif /* G_OS_WIN32 */
2457
2458 static void g_init_user_config_dir (void);
2459
2460 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2461
2462 /* adapted from xdg-user-dir-lookup.c
2463  *
2464  * Copyright (C) 2007 Red Hat Inc.
2465  *
2466  * Permission is hereby granted, free of charge, to any person
2467  * obtaining a copy of this software and associated documentation files
2468  * (the "Software"), to deal in the Software without restriction,
2469  * including without limitation the rights to use, copy, modify, merge,
2470  * publish, distribute, sublicense, and/or sell copies of the Software,
2471  * and to permit persons to whom the Software is furnished to do so,
2472  * subject to the following conditions: 
2473  *
2474  * The above copyright notice and this permission notice shall be
2475  * included in all copies or substantial portions of the Software. 
2476  *
2477  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2478  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2479  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2480  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2481  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2482  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2483  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2484  * SOFTWARE.
2485  */
2486 static void
2487 load_user_special_dirs (void)
2488 {
2489   gchar *config_file;
2490   gchar *data;
2491   gchar **lines;
2492   gint n_lines, i;
2493   
2494   g_init_user_config_dir ();
2495   config_file = g_build_filename (g_user_config_dir,
2496                                   "user-dirs.dirs",
2497                                   NULL);
2498   
2499   if (!g_file_get_contents (config_file, &data, NULL, NULL))
2500     {
2501       g_free (config_file);
2502       return;
2503     }
2504
2505   lines = g_strsplit (data, "\n", -1);
2506   n_lines = g_strv_length (lines);
2507   g_free (data);
2508   
2509   for (i = 0; i < n_lines; i++)
2510     {
2511       gchar *buffer = lines[i];
2512       gchar *d, *p;
2513       gint len;
2514       gboolean is_relative = FALSE;
2515       GUserDirectory directory;
2516
2517       /* Remove newline at end */
2518       len = strlen (buffer);
2519       if (len > 0 && buffer[len - 1] == '\n')
2520         buffer[len - 1] = 0;
2521       
2522       p = buffer;
2523       while (*p == ' ' || *p == '\t')
2524         p++;
2525       
2526       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2527         {
2528           directory = G_USER_DIRECTORY_DESKTOP;
2529           p += strlen ("XDG_DESKTOP_DIR");
2530         }
2531       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2532         {
2533           directory = G_USER_DIRECTORY_DOCUMENTS;
2534           p += strlen ("XDG_DOCUMENTS_DIR");
2535         }
2536       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2537         {
2538           directory = G_USER_DIRECTORY_DOWNLOAD;
2539           p += strlen ("XDG_DOWNLOAD_DIR");
2540         }
2541       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2542         {
2543           directory = G_USER_DIRECTORY_MUSIC;
2544           p += strlen ("XDG_MUSIC_DIR");
2545         }
2546       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2547         {
2548           directory = G_USER_DIRECTORY_PICTURES;
2549           p += strlen ("XDG_PICTURES_DIR");
2550         }
2551       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2552         {
2553           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2554           p += strlen ("XDG_PUBLICSHARE_DIR");
2555         }
2556       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2557         {
2558           directory = G_USER_DIRECTORY_TEMPLATES;
2559           p += strlen ("XDG_TEMPLATES_DIR");
2560         }
2561       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2562         {
2563           directory = G_USER_DIRECTORY_VIDEOS;
2564           p += strlen ("XDG_VIDEOS_DIR");
2565         }
2566       else
2567         continue;
2568
2569       while (*p == ' ' || *p == '\t')
2570         p++;
2571
2572       if (*p != '=')
2573         continue;
2574       p++;
2575
2576       while (*p == ' ' || *p == '\t')
2577         p++;
2578
2579       if (*p != '"')
2580         continue;
2581       p++;
2582
2583       if (strncmp (p, "$HOME", 5) == 0)
2584         {
2585           p += 5;
2586           is_relative = TRUE;
2587         }
2588       else if (*p != '/')
2589         continue;
2590
2591       d = strrchr (p, '"');
2592       if (!d)
2593         continue;
2594       *d = 0;
2595
2596       d = p;
2597       
2598       /* remove trailing slashes */
2599       len = strlen (d);
2600       if (d[len - 1] == '/')
2601         d[len - 1] = 0;
2602       
2603       if (is_relative)
2604         {
2605           g_get_any_init ();
2606           g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2607         }
2608       else
2609         g_user_special_dirs[directory] = g_strdup (d);
2610     }
2611
2612   g_strfreev (lines);
2613   g_free (config_file);
2614 }
2615
2616 #endif /* G_OS_UNIX && !HAVE_CARBON */
2617
2618
2619 /**
2620  * g_reload_user_special_dirs_cache:
2621  *
2622  * Resets the cache used for g_get_user_special_dir(), so
2623  * that the latest on-disk version is used. Call this only
2624  * if you just changed the data on disk yourself.
2625  *
2626  * Due to threadsafety issues this may cause leaking of strings
2627  * that were previously returned from g_get_user_special_dir()
2628  * that can't be freed. We ensure to only leak the data for
2629  * the directories that actually changed value though.
2630  *
2631  * Since: 2.22
2632  */
2633 void
2634 g_reload_user_special_dirs_cache (void)
2635 {
2636   int i;
2637
2638   G_LOCK (g_utils_global);
2639
2640   if (g_user_special_dirs != NULL)
2641     {
2642       /* save a copy of the pointer, to check if some memory can be preserved */
2643       char **old_g_user_special_dirs = g_user_special_dirs;
2644       char *old_val;
2645
2646       /* recreate and reload our cache */
2647       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2648       load_user_special_dirs ();
2649
2650       /* only leak changed directories */
2651       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2652         {
2653           old_val = old_g_user_special_dirs[i];
2654           if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2655             {
2656               /* don't leak */
2657               g_free (g_user_special_dirs[i]);
2658               g_user_special_dirs[i] = old_val;
2659             }
2660           else
2661             g_free (old_val);
2662         }
2663
2664       /* free the old array */
2665       g_free (old_g_user_special_dirs);
2666     }
2667
2668   G_UNLOCK (g_utils_global);
2669 }
2670
2671 /**
2672  * g_get_user_special_dir:
2673  * @directory: the logical id of special directory
2674  *
2675  * Returns the full path of a special directory using its logical id.
2676  *
2677  * On Unix this is done using the XDG special user directories.
2678  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2679  * falls back to <filename>$HOME/Desktop</filename> when XDG special
2680  * user directories have not been set up. 
2681  *
2682  * Depending on the platform, the user might be able to change the path
2683  * of the special directory without requiring the session to restart; GLib
2684  * will not reflect any change once the special directories are loaded.
2685  *
2686  * Return value: the path to the specified special directory, or %NULL
2687  *   if the logical id was not found. The returned string is owned by
2688  *   GLib and should not be modified or freed.
2689  *
2690  * Since: 2.14
2691  */
2692 G_CONST_RETURN gchar *
2693 g_get_user_special_dir (GUserDirectory directory)
2694 {
2695   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2696                         directory < G_USER_N_DIRECTORIES, NULL);
2697
2698   G_LOCK (g_utils_global);
2699
2700   if (G_UNLIKELY (g_user_special_dirs == NULL))
2701     {
2702       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2703
2704       load_user_special_dirs ();
2705
2706       /* Special-case desktop for historical compatibility */
2707       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2708         {
2709           g_get_any_init ();
2710
2711           g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2712             g_build_filename (g_home_dir, "Desktop", NULL);
2713         }
2714     }
2715
2716   G_UNLOCK (g_utils_global);
2717
2718   return g_user_special_dirs[directory];
2719 }
2720
2721 #ifdef G_OS_WIN32
2722
2723 #undef g_get_system_data_dirs
2724
2725 static HMODULE
2726 get_module_for_address (gconstpointer address)
2727 {
2728   /* Holds the g_utils_global lock */
2729
2730   static gboolean beenhere = FALSE;
2731   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2732   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2733   HMODULE hmodule = NULL;
2734
2735   if (!address)
2736     return NULL;
2737
2738   if (!beenhere)
2739     {
2740       p_GetModuleHandleExA =
2741         (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2742                                                "GetModuleHandleExA");
2743       beenhere = TRUE;
2744     }
2745
2746   if (p_GetModuleHandleExA == NULL ||
2747       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2748                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2749                                 address, &hmodule))
2750     {
2751       MEMORY_BASIC_INFORMATION mbi;
2752       VirtualQuery (address, &mbi, sizeof (mbi));
2753       hmodule = (HMODULE) mbi.AllocationBase;
2754     }
2755
2756   return hmodule;
2757 }
2758
2759 static gchar *
2760 get_module_share_dir (gconstpointer address)
2761 {
2762   HMODULE hmodule;
2763   gchar *filename;
2764   gchar *retval;
2765
2766   hmodule = get_module_for_address (address);
2767   if (hmodule == NULL)
2768     return NULL;
2769
2770   filename = g_win32_get_package_installation_directory_of_module (hmodule);
2771   retval = g_build_filename (filename, "share", NULL);
2772   g_free (filename);
2773
2774   return retval;
2775 }
2776
2777 G_CONST_RETURN gchar * G_CONST_RETURN *
2778 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2779 {
2780   GArray *data_dirs;
2781   HMODULE hmodule;
2782   static GHashTable *per_module_data_dirs = NULL;
2783   gchar **retval;
2784   gchar *p;
2785   gchar *exe_root;
2786       
2787   if (address_of_function)
2788     {
2789       G_LOCK (g_utils_global);
2790       hmodule = get_module_for_address (address_of_function);
2791       if (hmodule != NULL)
2792         {
2793           if (per_module_data_dirs == NULL)
2794             per_module_data_dirs = g_hash_table_new (NULL, NULL);
2795           else
2796             {
2797               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2798               
2799               if (retval != NULL)
2800                 {
2801                   G_UNLOCK (g_utils_global);
2802                   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2803                 }
2804             }
2805         }
2806     }
2807
2808   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2809
2810   /* Documents and Settings\All Users\Application Data */
2811   p = get_special_folder (CSIDL_COMMON_APPDATA);
2812   if (p)
2813     g_array_append_val (data_dirs, p);
2814   
2815   /* Documents and Settings\All Users\Documents */
2816   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2817   if (p)
2818     g_array_append_val (data_dirs, p);
2819         
2820   /* Using the above subfolders of Documents and Settings perhaps
2821    * makes sense from a Windows perspective.
2822    *
2823    * But looking at the actual use cases of this function in GTK+
2824    * and GNOME software, what we really want is the "share"
2825    * subdirectory of the installation directory for the package
2826    * our caller is a part of.
2827    *
2828    * The address_of_function parameter, if non-NULL, points to a
2829    * function in the calling module. Use that to determine that
2830    * module's installation folder, and use its "share" subfolder.
2831    *
2832    * Additionally, also use the "share" subfolder of the installation
2833    * locations of GLib and the .exe file being run.
2834    *
2835    * To guard against none of the above being what is really wanted,
2836    * callers of this function should have Win32-specific code to look
2837    * up their installation folder themselves, and handle a subfolder
2838    * "share" of it in the same way as the folders returned from this
2839    * function.
2840    */
2841
2842   p = get_module_share_dir (address_of_function);
2843   if (p)
2844     g_array_append_val (data_dirs, p);
2845     
2846   if (glib_dll != NULL)
2847     {
2848       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2849       p = g_build_filename (glib_root, "share", NULL);
2850       if (p)
2851         g_array_append_val (data_dirs, p);
2852       g_free (glib_root);
2853     }
2854   
2855   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2856   p = g_build_filename (exe_root, "share", NULL);
2857   if (p)
2858     g_array_append_val (data_dirs, p);
2859   g_free (exe_root);
2860
2861   retval = (gchar **) g_array_free (data_dirs, FALSE);
2862
2863   if (address_of_function)
2864     {
2865       if (hmodule != NULL)
2866         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2867       G_UNLOCK (g_utils_global);
2868     }
2869
2870   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2871 }
2872
2873 #endif
2874
2875 /**
2876  * g_get_system_data_dirs:
2877  * 
2878  * Returns an ordered list of base directories in which to access 
2879  * system-wide application data.
2880  *
2881  * On UNIX platforms this is determined using the mechanisms described in
2882  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2883  * XDG Base Directory Specification</ulink>
2884  * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2885  *
2886  * On Windows the first elements in the list are the Application Data
2887  * and Documents folders for All Users. (These can be determined only
2888  * on Windows 2000 or later and are not present in the list on other
2889  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2890  * CSIDL_COMMON_DOCUMENTS.
2891  *
2892  * Then follows the "share" subfolder in the installation folder for
2893  * the package containing the DLL that calls this function, if it can
2894  * be determined.
2895  * 
2896  * Finally the list contains the "share" subfolder in the installation
2897  * folder for GLib, and in the installation folder for the package the
2898  * application's .exe file belongs to.
2899  *
2900  * The installation folders above are determined by looking up the
2901  * folder where the module (DLL or EXE) in question is located. If the
2902  * folder's name is "bin", its parent is used, otherwise the folder
2903  * itself.
2904  *
2905  * Note that on Windows the returned list can vary depending on where
2906  * this function is called.
2907  *
2908  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2909  *               not be modified or freed.
2910  * Since: 2.6
2911  **/
2912 G_CONST_RETURN gchar * G_CONST_RETURN * 
2913 g_get_system_data_dirs (void)
2914 {
2915   gchar **data_dir_vector;
2916
2917   G_LOCK (g_utils_global);
2918
2919   if (!g_system_data_dirs)
2920     {
2921 #ifdef G_OS_WIN32
2922       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2923 #else
2924       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2925
2926       if (!data_dirs || !data_dirs[0])
2927           data_dirs = "/usr/local/share/:/usr/share/";
2928
2929       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2930 #endif
2931
2932       g_system_data_dirs = data_dir_vector;
2933     }
2934   else
2935     data_dir_vector = g_system_data_dirs;
2936
2937   G_UNLOCK (g_utils_global);
2938
2939   return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2940 }
2941
2942 /**
2943  * g_get_system_config_dirs:
2944  * 
2945  * Returns an ordered list of base directories in which to access 
2946  * system-wide configuration information.
2947  *
2948  * On UNIX platforms this is determined using the mechanisms described in
2949  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2950  * XDG Base Directory Specification</ulink>.
2951  * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2952  *
2953  * On Windows is the directory that contains application data for all users.
2954  * A typical path is C:\Documents and Settings\All Users\Application Data.
2955  * This folder is used for application data that is not user specific.
2956  * For example, an application can store a spell-check dictionary, a database
2957  * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2958  * This information will not roam and is available to anyone using the computer.
2959  *
2960  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2961  *               not be modified or freed.
2962  * Since: 2.6
2963  **/
2964 G_CONST_RETURN gchar * G_CONST_RETURN *
2965 g_get_system_config_dirs (void)
2966 {
2967   gchar *conf_dirs, **conf_dir_vector;
2968
2969   G_LOCK (g_utils_global);
2970
2971   if (!g_system_config_dirs)
2972     {
2973 #ifdef G_OS_WIN32
2974       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2975       if (conf_dirs)
2976         {
2977           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2978           g_free (conf_dirs);
2979         }
2980       else
2981         {
2982           /* Return empty list */
2983           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2984         }
2985 #else
2986       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2987
2988       if (!conf_dirs || !conf_dirs[0])
2989           conf_dirs = "/etc/xdg";
2990
2991       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2992 #endif
2993
2994       g_system_config_dirs = conf_dir_vector;
2995     }
2996   else
2997     conf_dir_vector = g_system_config_dirs;
2998   G_UNLOCK (g_utils_global);
2999
3000   return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
3001 }
3002
3003 #ifndef G_OS_WIN32
3004
3005 static GHashTable *alias_table = NULL;
3006
3007 /* read an alias file for the locales */
3008 static void
3009 read_aliases (gchar *file)
3010 {
3011   FILE *fp;
3012   char buf[256];
3013   
3014   if (!alias_table)
3015     alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3016   fp = fopen (file,"r");
3017   if (!fp)
3018     return;
3019   while (fgets (buf, 256, fp))
3020     {
3021       char *p, *q;
3022
3023       g_strstrip (buf);
3024
3025       /* Line is a comment */
3026       if ((buf[0] == '#') || (buf[0] == '\0'))
3027         continue;
3028
3029       /* Reads first column */
3030       for (p = buf, q = NULL; *p; p++) {
3031         if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3032           *p = '\0';
3033           q = p+1;
3034           while ((*q == '\t') || (*q == ' ')) {
3035             q++;
3036           }
3037           break;
3038         }
3039       }
3040       /* The line only had one column */
3041       if (!q || *q == '\0')
3042         continue;
3043       
3044       /* Read second column */
3045       for (p = q; *p; p++) {
3046         if ((*p == '\t') || (*p == ' ')) {
3047           *p = '\0';
3048           break;
3049         }
3050       }
3051
3052       /* Add to alias table if necessary */
3053       if (!g_hash_table_lookup (alias_table, buf)) {
3054         g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3055       }
3056     }
3057   fclose (fp);
3058 }
3059
3060 #endif
3061
3062 static char *
3063 unalias_lang (char *lang)
3064 {
3065 #ifndef G_OS_WIN32
3066   char *p;
3067   int i;
3068
3069   if (!alias_table)
3070     read_aliases ("/usr/share/locale/locale.alias");
3071
3072   i = 0;
3073   while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3074     {
3075       lang = p;
3076       if (i++ == 30)
3077         {
3078           static gboolean said_before = FALSE;
3079           if (!said_before)
3080             g_warning ("Too many alias levels for a locale, "
3081                        "may indicate a loop");
3082           said_before = TRUE;
3083           return lang;
3084         }
3085     }
3086 #endif
3087   return lang;
3088 }
3089
3090 /* Mask for components of locale spec. The ordering here is from
3091  * least significant to most significant
3092  */
3093 enum
3094 {
3095   COMPONENT_CODESET =   1 << 0,
3096   COMPONENT_TERRITORY = 1 << 1,
3097   COMPONENT_MODIFIER =  1 << 2
3098 };
3099
3100 /* Break an X/Open style locale specification into components
3101  */
3102 static guint
3103 explode_locale (const gchar *locale,
3104                 gchar      **language, 
3105                 gchar      **territory, 
3106                 gchar      **codeset, 
3107                 gchar      **modifier)
3108 {
3109   const gchar *uscore_pos;
3110   const gchar *at_pos;
3111   const gchar *dot_pos;
3112
3113   guint mask = 0;
3114
3115   uscore_pos = strchr (locale, '_');
3116   dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3117   at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3118
3119   if (at_pos)
3120     {
3121       mask |= COMPONENT_MODIFIER;
3122       *modifier = g_strdup (at_pos);
3123     }
3124   else
3125     at_pos = locale + strlen (locale);
3126
3127   if (dot_pos)
3128     {
3129       mask |= COMPONENT_CODESET;
3130       *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3131     }
3132   else
3133     dot_pos = at_pos;
3134
3135   if (uscore_pos)
3136     {
3137       mask |= COMPONENT_TERRITORY;
3138       *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3139     }
3140   else
3141     uscore_pos = dot_pos;
3142
3143   *language = g_strndup (locale, uscore_pos - locale);
3144
3145   return mask;
3146 }
3147
3148 /*
3149  * Compute all interesting variants for a given locale name -
3150  * by stripping off different components of the value.
3151  *
3152  * For simplicity, we assume that the locale is in
3153  * X/Open format: language[_territory][.codeset][@modifier]
3154  *
3155  * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3156  *       as well. We could just copy the code from glibc wholesale
3157  *       but it is big, ugly, and complicated, so I'm reluctant
3158  *       to do so when this should handle 99% of the time...
3159  */
3160 GSList *
3161 _g_compute_locale_variants (const gchar *locale)
3162 {
3163   GSList *retval = NULL;
3164
3165   gchar *language = NULL;
3166   gchar *territory = NULL;
3167   gchar *codeset = NULL;
3168   gchar *modifier = NULL;
3169
3170   guint mask;
3171   guint i;
3172
3173   g_return_val_if_fail (locale != NULL, NULL);
3174
3175   mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3176
3177   /* Iterate through all possible combinations, from least attractive
3178    * to most attractive.
3179    */
3180   for (i = 0; i <= mask; i++)
3181     if ((i & ~mask) == 0)
3182       {
3183         gchar *val = g_strconcat (language,
3184                                   (i & COMPONENT_TERRITORY) ? territory : "",
3185                                   (i & COMPONENT_CODESET) ? codeset : "",
3186                                   (i & COMPONENT_MODIFIER) ? modifier : "",
3187                                   NULL);
3188         retval = g_slist_prepend (retval, val);
3189       }
3190
3191   g_free (language);
3192   if (mask & COMPONENT_CODESET)
3193     g_free (codeset);
3194   if (mask & COMPONENT_TERRITORY)
3195     g_free (territory);
3196   if (mask & COMPONENT_MODIFIER)
3197     g_free (modifier);
3198
3199   return retval;
3200 }
3201
3202 /* The following is (partly) taken from the gettext package.
3203    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
3204
3205 static const gchar *
3206 guess_category_value (const gchar *category_name)
3207 {
3208   const gchar *retval;
3209
3210   /* The highest priority value is the `LANGUAGE' environment
3211      variable.  This is a GNU extension.  */
3212   retval = g_getenv ("LANGUAGE");
3213   if ((retval != NULL) && (retval[0] != '\0'))
3214     return retval;
3215
3216   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
3217      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
3218      systems this can be done by the `setlocale' function itself.  */
3219
3220   /* Setting of LC_ALL overwrites all other.  */
3221   retval = g_getenv ("LC_ALL");  
3222   if ((retval != NULL) && (retval[0] != '\0'))
3223     return retval;
3224
3225   /* Next comes the name of the desired category.  */
3226   retval = g_getenv (category_name);
3227   if ((retval != NULL) && (retval[0] != '\0'))
3228     return retval;
3229
3230   /* Last possibility is the LANG environment variable.  */
3231   retval = g_getenv ("LANG");
3232   if ((retval != NULL) && (retval[0] != '\0'))
3233     return retval;
3234
3235 #ifdef G_PLATFORM_WIN32
3236   /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3237    * LANG, which we already did above. Oh well. The main point of
3238    * calling g_win32_getlocale() is to get the thread's locale as used
3239    * by Windows and the Microsoft C runtime (in the "English_United
3240    * States" format) translated into the Unixish format.
3241    */
3242   {
3243     char *locale = g_win32_getlocale ();
3244     retval = g_intern_string (locale);
3245     g_free (locale);
3246     return retval;
3247   }
3248 #endif  
3249
3250   return NULL;
3251 }
3252
3253 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3254
3255 struct _GLanguageNamesCache {
3256   gchar *languages;
3257   gchar **language_names;
3258 };
3259
3260 static void
3261 language_names_cache_free (gpointer data)
3262 {
3263   GLanguageNamesCache *cache = data;
3264   g_free (cache->languages);
3265   g_strfreev (cache->language_names);
3266   g_free (cache);
3267 }
3268
3269 /**
3270  * g_get_language_names:
3271  * 
3272  * Computes a list of applicable locale names, which can be used to 
3273  * e.g. construct locale-dependent filenames or search paths. The returned 
3274  * list is sorted from most desirable to least desirable and always contains 
3275  * the default locale "C".
3276  *
3277  * For example, if LANGUAGE=de:en_US, then the returned list is
3278  * "de", "en_US", "en", "C".
3279  *
3280  * This function consults the environment variables <envar>LANGUAGE</envar>, 
3281  * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar> 
3282  * to find the list of locales specified by the user.
3283  * 
3284  * Return value: a %NULL-terminated array of strings owned by GLib 
3285  *    that must not be modified or freed.
3286  *
3287  * Since: 2.6
3288  **/
3289 G_CONST_RETURN gchar * G_CONST_RETURN * 
3290 g_get_language_names (void)
3291 {
3292   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3293   GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3294   const gchar *value;
3295
3296   if (!cache)
3297     {
3298       cache = g_new0 (GLanguageNamesCache, 1);
3299       g_static_private_set (&cache_private, cache, language_names_cache_free);
3300     }
3301
3302   value = guess_category_value ("LC_MESSAGES");
3303   if (!value)
3304     value = "C";
3305
3306   if (!(cache->languages && strcmp (cache->languages, value) == 0))
3307     {
3308       gchar **languages;
3309       gchar **alist, **a;
3310       GSList *list, *l;
3311       gint i;
3312
3313       g_free (cache->languages);
3314       g_strfreev (cache->language_names);
3315       cache->languages = g_strdup (value);
3316
3317       alist = g_strsplit (value, ":", 0);
3318       list = NULL;
3319       for (a = alist; *a; a++)
3320         {
3321           gchar *b = unalias_lang (*a);
3322           list = g_slist_concat (list, _g_compute_locale_variants (b));
3323         }
3324       g_strfreev (alist);
3325       list = g_slist_append (list, g_strdup ("C"));
3326
3327       cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3328       for (l = list, i = 0; l; l = l->next, i++)
3329         languages[i] = l->data;
3330       languages[i] = NULL;
3331
3332       g_slist_free (list);
3333     }
3334
3335   return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3336 }
3337
3338 /**
3339  * g_direct_hash:
3340  * @v: a #gpointer key
3341  *
3342  * Converts a gpointer to a hash value.
3343  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3344  * when using pointers as keys in a #GHashTable.
3345  *
3346  * Returns: a hash value corresponding to the key.
3347  */
3348 guint
3349 g_direct_hash (gconstpointer v)
3350 {
3351   return GPOINTER_TO_UINT (v);
3352 }
3353
3354 /**
3355  * g_direct_equal:
3356  * @v1: a key.
3357  * @v2: a key to compare with @v1.
3358  *
3359  * Compares two #gpointer arguments and returns %TRUE if they are equal.
3360  * It can be passed to g_hash_table_new() as the @key_equal_func
3361  * parameter, when using pointers as keys in a #GHashTable.
3362  * 
3363  * Returns: %TRUE if the two keys match.
3364  */
3365 gboolean
3366 g_direct_equal (gconstpointer v1,
3367                 gconstpointer v2)
3368 {
3369   return v1 == v2;
3370 }
3371
3372 /**
3373  * g_int_equal:
3374  * @v1: a pointer to a #gint key.
3375  * @v2: a pointer to a #gint key to compare with @v1.
3376  *
3377  * Compares the two #gint values being pointed to and returns 
3378  * %TRUE if they are equal.
3379  * It can be passed to g_hash_table_new() as the @key_equal_func
3380  * parameter, when using pointers to integers as keys in a #GHashTable.
3381  * 
3382  * Returns: %TRUE if the two keys match.
3383  */
3384 gboolean
3385 g_int_equal (gconstpointer v1,
3386              gconstpointer v2)
3387 {
3388   return *((const gint*) v1) == *((const gint*) v2);
3389 }
3390
3391 /**
3392  * g_int_hash:
3393  * @v: a pointer to a #gint key
3394  *
3395  * Converts a pointer to a #gint to a hash value.
3396  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3397  * when using pointers to integers values as keys in a #GHashTable.
3398  *
3399  * Returns: a hash value corresponding to the key.
3400  */
3401 guint
3402 g_int_hash (gconstpointer v)
3403 {
3404   return *(const gint*) v;
3405 }
3406
3407 /**
3408  * g_int64_equal:
3409  * @v1: a pointer to a #gint64 key.
3410  * @v2: a pointer to a #gint64 key to compare with @v1.
3411  *
3412  * Compares the two #gint64 values being pointed to and returns 
3413  * %TRUE if they are equal.
3414  * It can be passed to g_hash_table_new() as the @key_equal_func
3415  * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3416  * 
3417  * Returns: %TRUE if the two keys match.
3418  *
3419  * Since: 2.22
3420  */
3421 gboolean
3422 g_int64_equal (gconstpointer v1,
3423                gconstpointer v2)
3424 {
3425   return *((const gint64*) v1) == *((const gint64*) v2);
3426 }
3427
3428 /**
3429  * g_int64_hash:
3430  * @v: a pointer to a #gint64 key
3431  *
3432  * Converts a pointer to a #gint64 to a hash value.
3433  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3434  * when using pointers to 64-bit integers values as keys in a #GHashTable.
3435  *
3436  * Returns: a hash value corresponding to the key.
3437  *
3438  * Since: 2.22
3439  */
3440 guint
3441 g_int64_hash (gconstpointer v)
3442 {
3443   return (guint) *(const gint64*) v;
3444 }
3445
3446 /**
3447  * g_double_equal:
3448  * @v1: a pointer to a #gdouble key.
3449  * @v2: a pointer to a #gdouble key to compare with @v1.
3450  *
3451  * Compares the two #gdouble values being pointed to and returns 
3452  * %TRUE if they are equal.
3453  * It can be passed to g_hash_table_new() as the @key_equal_func
3454  * parameter, when using pointers to doubles as keys in a #GHashTable.
3455  * 
3456  * Returns: %TRUE if the two keys match.
3457  *
3458  * Since: 2.22
3459  */
3460 gboolean
3461 g_double_equal (gconstpointer v1,
3462                 gconstpointer v2)
3463 {
3464   return *((const gdouble*) v1) == *((const gdouble*) v2);
3465 }
3466
3467 /**
3468  * g_double_hash:
3469  * @v: a pointer to a #gdouble key
3470  *
3471  * Converts a pointer to a #gdouble to a hash value.
3472  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
3473  * when using pointers to doubles as keys in a #GHashTable.
3474  *
3475  * Returns: a hash value corresponding to the key.
3476  *
3477  * Since: 2.22
3478  */
3479 guint
3480 g_double_hash (gconstpointer v)
3481 {
3482   return (guint) *(const gdouble*) v;
3483 }
3484
3485 /**
3486  * g_nullify_pointer:
3487  * @nullify_location: the memory address of the pointer.
3488  * 
3489  * Set the pointer at the specified location to %NULL.
3490  **/
3491 void
3492 g_nullify_pointer (gpointer *nullify_location)
3493 {
3494   g_return_if_fail (nullify_location != NULL);
3495
3496   *nullify_location = NULL;
3497 }
3498
3499 /**
3500  * g_get_codeset:
3501  * 
3502  * Get the codeset for the current locale.
3503  * 
3504  * Return value: a newly allocated string containing the name
3505  * of the codeset. This string must be freed with g_free().
3506  **/
3507 gchar *
3508 g_get_codeset (void)
3509 {
3510   const gchar *charset;
3511
3512   g_get_charset (&charset);
3513
3514   return g_strdup (charset);
3515 }
3516
3517 /* This is called from g_thread_init(). It's used to
3518  * initialize some static data in a threadsafe way.
3519  */
3520 void
3521 _g_utils_thread_init (void)
3522 {
3523   g_get_language_names ();
3524 }
3525
3526 #ifdef G_OS_WIN32
3527
3528 /**
3529  * _glib_get_locale_dir:
3530  *
3531  * Return the path to the share\locale or lib\locale subfolder of the
3532  * GLib installation folder. The path is in the system codepage. We
3533  * have to use system codepage as bindtextdomain() doesn't have a
3534  * UTF-8 interface.
3535  */
3536 static gchar *
3537 _glib_get_locale_dir (void)
3538 {
3539   gchar *install_dir = NULL, *locale_dir;
3540   gchar *retval = NULL;
3541
3542   if (glib_dll != NULL)
3543     install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3544
3545   if (install_dir)
3546     {
3547       /*
3548        * Append "/share/locale" or "/lib/locale" depending on whether
3549        * autoconfigury detected GNU gettext or not.
3550        */
3551       const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3552       while (*--p != '/')
3553         ;
3554       while (*--p != '/')
3555         ;
3556
3557       locale_dir = g_build_filename (install_dir, p, NULL);
3558
3559       retval = g_win32_locale_filename_from_utf8 (locale_dir);
3560
3561       g_free (install_dir);
3562       g_free (locale_dir);
3563     }
3564
3565   if (retval)
3566     return retval;
3567   else
3568     return g_strdup ("");
3569 }
3570
3571 #undef GLIB_LOCALE_DIR
3572
3573 #endif /* G_OS_WIN32 */
3574
3575 /**
3576  * glib_gettext:
3577  * @str: The string to be translated
3578  *
3579  * Returns the translated string from the glib translations.
3580  * This is an internal function and should only be used by
3581  * the internals of glib (such as libgio).
3582  *
3583  * Returns: the transation of @str to the current locale
3584  */
3585 G_CONST_RETURN gchar *
3586 glib_gettext (const gchar *str)
3587 {
3588   static gboolean _glib_gettext_initialized = FALSE;
3589
3590   if (!_glib_gettext_initialized)
3591     {
3592 #ifdef G_OS_WIN32
3593       gchar *tmp = _glib_get_locale_dir ();
3594       bindtextdomain (GETTEXT_PACKAGE, tmp);
3595       g_free (tmp);
3596 #else
3597       bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3598 #endif
3599 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3600       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3601 #    endif
3602       _glib_gettext_initialized = TRUE;
3603     }
3604   
3605   return g_dgettext (GETTEXT_PACKAGE, str);
3606 }
3607
3608 #if defined (G_OS_WIN32) && !defined (_WIN64)
3609
3610 /* Binary compatibility versions. Not for newly compiled code. */
3611
3612 #undef g_find_program_in_path
3613
3614 gchar*
3615 g_find_program_in_path (const gchar *program)
3616 {
3617   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3618   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3619   gchar *retval;
3620
3621   g_free (utf8_program);
3622   if (utf8_retval == NULL)
3623     return NULL;
3624   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3625   g_free (utf8_retval);
3626
3627   return retval;
3628 }
3629
3630 #undef g_get_current_dir
3631
3632 gchar*
3633 g_get_current_dir (void)
3634 {
3635   gchar *utf8_dir = g_get_current_dir_utf8 ();
3636   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3637   g_free (utf8_dir);
3638   return dir;
3639 }
3640
3641 #undef g_getenv
3642
3643 G_CONST_RETURN gchar*
3644 g_getenv (const gchar *variable)
3645 {
3646   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3647   const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3648   gchar *value;
3649   GQuark quark;
3650
3651   g_free (utf8_variable);
3652   if (!utf8_value)
3653     return NULL;
3654   value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3655   quark = g_quark_from_string (value);
3656   g_free (value);
3657
3658   return g_quark_to_string (quark);
3659 }
3660
3661 #undef g_setenv
3662
3663 gboolean
3664 g_setenv (const gchar *variable, 
3665           const gchar *value, 
3666           gboolean     overwrite)
3667 {
3668   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3669   gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3670   gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3671
3672   g_free (utf8_variable);
3673   g_free (utf8_value);
3674
3675   return retval;
3676 }
3677
3678 #undef g_unsetenv
3679
3680 void
3681 g_unsetenv (const gchar *variable)
3682 {
3683   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3684
3685   g_unsetenv_utf8 (utf8_variable);
3686
3687   g_free (utf8_variable);
3688 }
3689
3690 #undef g_get_user_name
3691
3692 G_CONST_RETURN gchar*
3693 g_get_user_name (void)
3694 {
3695   g_get_any_init_locked ();
3696   return g_user_name_cp;
3697 }
3698
3699 #undef g_get_real_name
3700
3701 G_CONST_RETURN gchar*
3702 g_get_real_name (void)
3703 {
3704   g_get_any_init_locked ();
3705   return g_real_name_cp;
3706 }
3707
3708 #undef g_get_home_dir
3709
3710 G_CONST_RETURN gchar*
3711 g_get_home_dir (void)
3712 {
3713   g_get_any_init_locked ();
3714   return g_home_dir_cp;
3715 }
3716
3717 #undef g_get_tmp_dir
3718
3719 G_CONST_RETURN gchar*
3720 g_get_tmp_dir (void)
3721 {
3722   g_get_any_init_locked ();
3723   return g_tmp_dir_cp;
3724 }
3725
3726 #endif