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