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