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