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