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