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