Reshuffle some functions between gutils and gfileutils
[platform/upstream/glib.git] / glib / gutils.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29  */
30
31 #include "config.h"
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <locale.h>
40 #include <string.h>
41 #include <ctype.h>              /* For tolower() */
42 #include <errno.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #ifdef HAVE_PWD_H
46 #include <pwd.h>
47 #endif
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_CRT_EXTERNS_H 
53 #include <crt_externs.h> /* for _NSGetEnviron */
54 #endif
55
56 /* implement gutils's inline functions
57  */
58 #define G_IMPLEMENT_INLINES 1
59 #define __G_UTILS_C__
60 #include "gutils.h"
61
62 #include "glib-init.h"
63 #include "genviron.h"
64 #include "gfileutils.h"
65 #include "ghash.h"
66 #include "gslist.h"
67 #include "gprintfint.h"
68 #include "gthread.h"
69 #include "gthreadprivate.h"
70 #include "gtestutils.h"
71 #include "gunicode.h"
72 #include "gstrfuncs.h"
73 #include "garray.h"
74 #include "glibintl.h"
75
76 #ifdef G_PLATFORM_WIN32
77 #include "garray.h"
78 #include "gconvert.h"
79 #include "gwin32.h"
80 #endif
81
82
83 /**
84  * SECTION:misc_utils
85  * @title: Miscellaneous Utility Functions
86  * @short_description: a selection of portable utility functions
87  *
88  * These are portable utility functions.
89  */
90
91 #ifdef G_PLATFORM_WIN32
92 #  include <windows.h>
93 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
94 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
95 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
96 #  endif
97 #  include <lmcons.h>           /* For UNLEN */
98 #endif /* G_PLATFORM_WIN32 */
99
100 #ifdef G_OS_WIN32
101 #  include <direct.h>
102 #  include <shlobj.h>
103    /* older SDK (e.g. msvc 5.0) does not have these*/
104 #  ifndef CSIDL_MYMUSIC
105 #    define CSIDL_MYMUSIC 13
106 #  endif
107 #  ifndef CSIDL_MYVIDEO
108 #    define CSIDL_MYVIDEO 14
109 #  endif
110 #  ifndef CSIDL_INTERNET_CACHE
111 #    define CSIDL_INTERNET_CACHE 32
112 #  endif
113 #  ifndef CSIDL_COMMON_APPDATA
114 #    define CSIDL_COMMON_APPDATA 35
115 #  endif
116 #  ifndef CSIDL_MYPICTURES
117 #    define CSIDL_MYPICTURES 0x27
118 #  endif
119 #  ifndef CSIDL_COMMON_DOCUMENTS
120 #    define CSIDL_COMMON_DOCUMENTS 46
121 #  endif
122 #  ifndef CSIDL_PROFILE
123 #    define CSIDL_PROFILE 40
124 #  endif
125 #  include <process.h>
126 #endif
127
128 #ifdef HAVE_CARBON
129 #include <CoreServices/CoreServices.h>
130 #endif
131
132 #ifdef HAVE_CODESET
133 #include <langinfo.h>
134 #endif
135
136 #ifdef G_PLATFORM_WIN32
137
138 gchar *
139 _glib_get_dll_directory (void)
140 {
141   gchar *retval;
142   gchar *p;
143   wchar_t wc_fn[MAX_PATH];
144
145 #ifdef DLL_EXPORT
146   if (glib_dll == NULL)
147     return NULL;
148 #endif
149
150   /* This code is different from that in
151    * g_win32_get_package_installation_directory_of_module() in that
152    * here we return the actual folder where the GLib DLL is. We don't
153    * do the check for it being in a "bin" or "lib" subfolder and then
154    * returning the parent of that.
155    *
156    * In a statically built GLib, glib_dll will be NULL and we will
157    * thus look up the application's .exe file's location.
158    */
159   if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
160     return NULL;
161
162   retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
163
164   p = strrchr (retval, G_DIR_SEPARATOR);
165   if (p == NULL)
166     {
167       /* Wtf? */
168       return NULL;
169     }
170   *p = '\0';
171
172   return retval;
173 }
174
175 #endif
176
177 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
178 /**
179  * g_memmove: 
180  * @dest: the destination address to copy the bytes to.
181  * @src: the source address to copy the bytes from.
182  * @len: the number of bytes to copy.
183  *
184  * Copies a block of memory @len bytes long, from @src to @dest.
185  * The source and destination areas may overlap.
186  *
187  * In order to use this function, you must include 
188  * <filename>string.h</filename> yourself, because this macro will 
189  * typically simply resolve to memmove() and GLib does not include 
190  * <filename>string.h</filename> for you.
191  */
192 void 
193 g_memmove (gpointer      dest, 
194            gconstpointer src, 
195            gulong        len)
196 {
197   gchar* destptr = dest;
198   const gchar* srcptr = src;
199   if (src + len < dest || dest + len < src)
200     {
201       bcopy (src, dest, len);
202       return;
203     }
204   else if (dest <= src)
205     {
206       while (len--)
207         *(destptr++) = *(srcptr++);
208     }
209   else
210     {
211       destptr += len;
212       srcptr += len;
213       while (len--)
214         *(--destptr) = *(--srcptr);
215     }
216 }
217 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
218
219 #ifdef G_OS_WIN32
220 #undef g_atexit
221 #endif
222
223 /**
224  * g_atexit:
225  * @func: (scope async): the function to call on normal program termination.
226  * 
227  * Specifies a function to be called at normal program termination.
228  *
229  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
230  * macro that maps to a call to the atexit() function in the C
231  * library. This means that in case the code that calls g_atexit(),
232  * i.e. atexit(), is in a DLL, the function will be called when the
233  * DLL is detached from the program. This typically makes more sense
234  * than that the function is called when the GLib DLL is detached,
235  * which happened earlier when g_atexit() was a function in the GLib
236  * DLL.
237  *
238  * The behaviour of atexit() in the context of dynamically loaded
239  * modules is not formally specified and varies wildly.
240  *
241  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
242  * loaded module which is unloaded before the program terminates might
243  * well cause a crash at program exit.
244  *
245  * Some POSIX systems implement atexit() like Windows, and have each
246  * dynamically loaded module maintain an own atexit chain that is
247  * called when the module is unloaded.
248  *
249  * On other POSIX systems, before a dynamically loaded module is
250  * unloaded, the registered atexit functions (if any) residing in that
251  * module are called, regardless where the code that registered them
252  * resided. This is presumably the most robust approach.
253  *
254  * As can be seen from the above, for portability it's best to avoid
255  * calling g_atexit() (or atexit()) except in the main executable of a
256  * program.
257  */
258 void
259 g_atexit (GVoidFunc func)
260 {
261   gint result;
262   const gchar *error = NULL;
263
264   /* keep this in sync with glib.h */
265
266 #ifdef  G_NATIVE_ATEXIT
267   result = ATEXIT (func);
268   if (result)
269     error = g_strerror (errno);
270 #elif defined (HAVE_ATEXIT)
271 #  ifdef NeXT /* @#%@! NeXTStep */
272   result = !atexit ((void (*)(void)) func);
273   if (result)
274     error = g_strerror (errno);
275 #  else
276   result = atexit ((void (*)(void)) func);
277   if (result)
278     error = g_strerror (errno);
279 #  endif /* NeXT */
280 #elif defined (HAVE_ON_EXIT)
281   result = on_exit ((void (*)(int, void *)) func, NULL);
282   if (result)
283     error = g_strerror (errno);
284 #else
285   result = 0;
286   error = "no implementation";
287 #endif /* G_NATIVE_ATEXIT */
288
289   if (error)
290     g_error ("Could not register atexit() function: %s", error);
291 }
292
293 /* Based on execvp() from GNU Libc.
294  * Some of this code is cut-and-pasted into gspawn.c
295  */
296
297 static gchar*
298 my_strchrnul (const gchar *str, 
299               gchar        c)
300 {
301   gchar *p = (gchar*)str;
302   while (*p && (*p != c))
303     ++p;
304
305   return p;
306 }
307
308 #ifdef G_OS_WIN32
309
310 static gchar *inner_find_program_in_path (const gchar *program);
311
312 gchar*
313 g_find_program_in_path (const gchar *program)
314 {
315   const gchar *last_dot = strrchr (program, '.');
316
317   if (last_dot == NULL ||
318       strchr (last_dot, '\\') != NULL ||
319       strchr (last_dot, '/') != NULL)
320     {
321       const gint program_length = strlen (program);
322       gchar *pathext = g_build_path (";",
323                                      ".exe;.cmd;.bat;.com",
324                                      g_getenv ("PATHEXT"),
325                                      NULL);
326       gchar *p;
327       gchar *decorated_program;
328       gchar *retval;
329
330       p = pathext;
331       do
332         {
333           gchar *q = my_strchrnul (p, ';');
334
335           decorated_program = g_malloc (program_length + (q-p) + 1);
336           memcpy (decorated_program, program, program_length);
337           memcpy (decorated_program+program_length, p, q-p);
338           decorated_program [program_length + (q-p)] = '\0';
339           
340           retval = inner_find_program_in_path (decorated_program);
341           g_free (decorated_program);
342
343           if (retval != NULL)
344             {
345               g_free (pathext);
346               return retval;
347             }
348           p = q;
349         } while (*p++ != '\0');
350       g_free (pathext);
351       return NULL;
352     }
353   else
354     return inner_find_program_in_path (program);
355 }
356
357 #endif
358
359 /**
360  * g_find_program_in_path:
361  * @program: a program name in the GLib file name encoding
362  * 
363  * Locates the first executable named @program in the user's path, in the
364  * same way that execvp() would locate it. Returns an allocated string
365  * with the absolute path name, or %NULL if the program is not found in
366  * the path. If @program is already an absolute path, returns a copy of
367  * @program if @program exists and is executable, and %NULL otherwise.
368  *  
369  * On Windows, if @program does not have a file type suffix, tries
370  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
371  * the <envar>PATHEXT</envar> environment variable. 
372  * 
373  * On Windows, it looks for the file in the same way as CreateProcess() 
374  * would. This means first in the directory where the executing
375  * program was loaded from, then in the current directory, then in the
376  * Windows 32-bit system directory, then in the Windows directory, and
377  * finally in the directories in the <envar>PATH</envar> environment 
378  * variable. If the program is found, the return value contains the 
379  * full name including the type suffix.
380  *
381  * Return value: absolute path, or %NULL
382  **/
383 #ifdef G_OS_WIN32
384 static gchar *
385 inner_find_program_in_path (const gchar *program)
386 #else
387 gchar*
388 g_find_program_in_path (const gchar *program)
389 #endif
390 {
391   const gchar *path, *p;
392   gchar *name, *freeme;
393 #ifdef G_OS_WIN32
394   const gchar *path_copy;
395   gchar *filename = NULL, *appdir = NULL;
396   gchar *sysdir = NULL, *windir = NULL;
397   int n;
398   wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
399     wwindir[MAXPATHLEN];
400 #endif
401   gsize len;
402   gsize pathlen;
403
404   g_return_val_if_fail (program != NULL, NULL);
405
406   /* If it is an absolute path, or a relative path including subdirectories,
407    * don't look in PATH.
408    */
409   if (g_path_is_absolute (program)
410       || strchr (program, G_DIR_SEPARATOR) != NULL
411 #ifdef G_OS_WIN32
412       || strchr (program, '/') != NULL
413 #endif
414       )
415     {
416       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
417           !g_file_test (program, G_FILE_TEST_IS_DIR))
418         return g_strdup (program);
419       else
420         return NULL;
421     }
422   
423   path = g_getenv ("PATH");
424 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
425   if (path == NULL)
426     {
427       /* There is no `PATH' in the environment.  The default
428        * search path in GNU libc is the current directory followed by
429        * the path `confstr' returns for `_CS_PATH'.
430        */
431       
432       /* In GLib we put . last, for security, and don't use the
433        * unportable confstr(); UNIX98 does not actually specify
434        * what to search if PATH is unset. POSIX may, dunno.
435        */
436       
437       path = "/bin:/usr/bin:.";
438     }
439 #else
440   n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
441   if (n > 0 && n < MAXPATHLEN)
442     filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
443   
444   n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
445   if (n > 0 && n < MAXPATHLEN)
446     sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
447   
448   n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
449   if (n > 0 && n < MAXPATHLEN)
450     windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
451   
452   if (filename)
453     {
454       appdir = g_path_get_dirname (filename);
455       g_free (filename);
456     }
457   
458   path = g_strdup (path);
459
460   if (windir)
461     {
462       const gchar *tem = path;
463       path = g_strconcat (windir, ";", path, NULL);
464       g_free ((gchar *) tem);
465       g_free (windir);
466     }
467   
468   if (sysdir)
469     {
470       const gchar *tem = path;
471       path = g_strconcat (sysdir, ";", path, NULL);
472       g_free ((gchar *) tem);
473       g_free (sysdir);
474     }
475   
476   {
477     const gchar *tem = path;
478     path = g_strconcat (".;", path, NULL);
479     g_free ((gchar *) tem);
480   }
481   
482   if (appdir)
483     {
484       const gchar *tem = path;
485       path = g_strconcat (appdir, ";", path, NULL);
486       g_free ((gchar *) tem);
487       g_free (appdir);
488     }
489
490   path_copy = path;
491 #endif
492   
493   len = strlen (program) + 1;
494   pathlen = strlen (path);
495   freeme = name = g_malloc (pathlen + len + 1);
496   
497   /* Copy the file name at the top, including '\0'  */
498   memcpy (name + pathlen + 1, program, len);
499   name = name + pathlen;
500   /* And add the slash before the filename  */
501   *name = G_DIR_SEPARATOR;
502   
503   p = path;
504   do
505     {
506       char *startp;
507
508       path = p;
509       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
510
511       if (p == path)
512         /* Two adjacent colons, or a colon at the beginning or the end
513          * of `PATH' means to search the current directory.
514          */
515         startp = name + 1;
516       else
517         startp = memcpy (name - (p - path), path, p - path);
518
519       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
520           !g_file_test (startp, G_FILE_TEST_IS_DIR))
521         {
522           gchar *ret;
523           ret = g_strdup (startp);
524           g_free (freeme);
525 #ifdef G_OS_WIN32
526           g_free ((gchar *) path_copy);
527 #endif
528           return ret;
529         }
530     }
531   while (*p++ != '\0');
532   
533   g_free (freeme);
534 #ifdef G_OS_WIN32
535   g_free ((gchar *) path_copy);
536 #endif
537
538   return NULL;
539 }
540
541 /**
542  * g_bit_nth_lsf:
543  * @mask: a #gulong containing flags
544  * @nth_bit: the index of the bit to start the search from
545  *
546  * Find the position of the first bit set in @mask, searching
547  * from (but not including) @nth_bit upwards. Bits are numbered
548  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
549  * usually). To start searching from the 0th bit, set @nth_bit to -1.
550  *
551  * Returns: the index of the first bit set which is higher than @nth_bit
552  */
553
554 /**
555  * g_bit_nth_msf:
556  * @mask: a #gulong containing flags
557  * @nth_bit: the index of the bit to start the search from
558  *
559  * Find the position of the first bit set in @mask, searching
560  * from (but not including) @nth_bit downwards. Bits are numbered
561  * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
562  * usually). To start searching from the last bit, set @nth_bit to
563  * -1 or GLIB_SIZEOF_LONG * 8.
564  *
565  * Returns: the index of the first bit set which is lower than @nth_bit
566  */
567
568 /**
569  * g_bit_storage:
570  * @number: a #guint
571  *
572  * Gets the number of bits used to hold @number,
573  * e.g. if @number is 4, 3 bits are needed.
574  *
575  * Returns: the number of bits used to hold @number
576  */
577
578 G_LOCK_DEFINE_STATIC (g_utils_global);
579
580 static  gchar   *g_tmp_dir = NULL;
581 static  gchar   *g_user_name = NULL;
582 static  gchar   *g_real_name = NULL;
583 static  gchar   *g_home_dir = NULL;
584 static  gchar   *g_host_name = NULL;
585
586 #ifdef G_OS_WIN32
587 /* System codepage versions of the above, kept at file level so that they,
588  * too, are produced only once.
589  */
590 static  gchar   *g_tmp_dir_cp = NULL;
591 static  gchar   *g_user_name_cp = NULL;
592 static  gchar   *g_real_name_cp = NULL;
593 static  gchar   *g_home_dir_cp = NULL;
594 #endif
595
596 static  gchar   *g_user_data_dir = NULL;
597 static  gchar  **g_system_data_dirs = NULL;
598 static  gchar   *g_user_cache_dir = NULL;
599 static  gchar   *g_user_config_dir = NULL;
600 static  gchar  **g_system_config_dirs = NULL;
601
602 static  gchar  **g_user_special_dirs = NULL;
603
604 /* fifteen minutes of fame for everybody */
605 #define G_USER_DIRS_EXPIRE      15 * 60
606
607 #ifdef G_OS_WIN32
608
609 static gchar *
610 get_special_folder (int csidl)
611 {
612   wchar_t path[MAX_PATH+1];
613   HRESULT hr;
614   LPITEMIDLIST pidl = NULL;
615   BOOL b;
616   gchar *retval = NULL;
617
618   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
619   if (hr == S_OK)
620     {
621       b = SHGetPathFromIDListW (pidl, path);
622       if (b)
623         retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
624       CoTaskMemFree (pidl);
625     }
626   return retval;
627 }
628
629 static char *
630 get_windows_directory_root (void)
631 {
632   wchar_t wwindowsdir[MAX_PATH];
633
634   if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
635     {
636       /* Usually X:\Windows, but in terminal server environments
637        * might be an UNC path, AFAIK.
638        */
639       char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
640       char *p;
641
642       if (windowsdir == NULL)
643         return g_strdup ("C:\\");
644
645       p = (char *) g_path_skip_root (windowsdir);
646       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
647         p--;
648       *p = '\0';
649       return windowsdir;
650     }
651   else
652     return g_strdup ("C:\\");
653 }
654
655 #endif
656
657 /* HOLDS: g_utils_global_lock */
658 static void
659 g_get_any_init_do (void)
660 {
661   gchar hostname[100];
662
663   g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
664   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
665     g_tmp_dir = g_strdup (g_getenv ("TMP"));
666   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
667     g_tmp_dir = g_strdup (g_getenv ("TEMP"));
668
669 #ifdef G_OS_WIN32
670   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
671     g_tmp_dir = get_windows_directory_root ();
672 #else  
673 #ifdef P_tmpdir
674   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
675     {
676       gsize k;    
677       g_tmp_dir = g_strdup (P_tmpdir);
678       k = strlen (g_tmp_dir);
679       if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
680         g_tmp_dir[k - 1] = '\0';
681     }
682 #endif
683   
684   if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
685     {
686       g_tmp_dir = g_strdup ("/tmp");
687     }
688 #endif  /* !G_OS_WIN32 */
689   
690 #ifdef G_OS_WIN32
691   /* We check $HOME first for Win32, though it is a last resort for Unix
692    * where we prefer the results of getpwuid().
693    */
694   g_home_dir = g_strdup (g_getenv ("HOME"));
695
696   /* Only believe HOME if it is an absolute path and exists */
697   if (g_home_dir)
698     {
699       if (!(g_path_is_absolute (g_home_dir) &&
700             g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
701         {
702           g_free (g_home_dir);
703           g_home_dir = NULL;
704         }
705     }
706   
707   /* In case HOME is Unix-style (it happens), convert it to
708    * Windows style.
709    */
710   if (g_home_dir)
711     {
712       gchar *p;
713       while ((p = strchr (g_home_dir, '/')) != NULL)
714         *p = '\\';
715     }
716
717   if (!g_home_dir)
718     {
719       /* USERPROFILE is probably the closest equivalent to $HOME? */
720       if (g_getenv ("USERPROFILE") != NULL)
721         g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
722     }
723
724   if (!g_home_dir)
725     g_home_dir = get_special_folder (CSIDL_PROFILE);
726   
727   if (!g_home_dir)
728     g_home_dir = get_windows_directory_root ();
729 #endif /* G_OS_WIN32 */
730   
731 #ifdef HAVE_PWD_H
732   {
733     struct passwd *pw = NULL;
734     gpointer buffer = NULL;
735     gint error;
736     gchar *logname;
737
738 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
739     struct passwd pwd;
740 #    ifdef _SC_GETPW_R_SIZE_MAX  
741     /* This reurns the maximum length */
742     glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
743     
744     if (bufsize < 0)
745       bufsize = 64;
746 #    else /* _SC_GETPW_R_SIZE_MAX */
747     glong bufsize = 64;
748 #    endif /* _SC_GETPW_R_SIZE_MAX */
749
750     logname = (gchar *) g_getenv ("LOGNAME");
751         
752     do
753       {
754         g_free (buffer);
755         /* we allocate 6 extra bytes to work around a bug in 
756          * Mac OS < 10.3. See #156446
757          */
758         buffer = g_malloc (bufsize + 6);
759         errno = 0;
760         
761 #    ifdef HAVE_POSIX_GETPWUID_R
762         if (logname) {
763           error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
764           if (!pw || (pw->pw_uid != getuid ())) {
765             /* LOGNAME is lying, fall back to looking up the uid */
766             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
767           }
768         } else {
769           error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
770         }
771         error = error < 0 ? errno : error;
772 #    else /* HAVE_NONPOSIX_GETPWUID_R */
773    /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
774 #      if defined(_AIX) || defined(__hpux)
775         error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
776         pw = error == 0 ? &pwd : NULL;
777 #      else /* !_AIX */
778         if (logname) {
779           pw = getpwnam_r (logname, &pwd, buffer, bufsize);
780           if (!pw || (pw->pw_uid != getuid ())) {
781             /* LOGNAME is lying, fall back to looking up the uid */
782             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
783           }
784         } else {
785           pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
786         }
787         error = pw ? 0 : errno;
788 #      endif /* !_AIX */            
789 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
790         
791         if (!pw)
792           {
793             /* we bail out prematurely if the user id can't be found
794              * (should be pretty rare case actually), or if the buffer
795              * should be sufficiently big and lookups are still not
796              * successful.
797              */
798             if (error == 0 || error == ENOENT)
799               {
800                 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
801                            (gulong) getuid ());
802                 break;
803               }
804             if (bufsize > 32 * 1024)
805               {
806                 g_warning ("getpwuid_r(): failed due to: %s.",
807                            g_strerror (error));
808                 break;
809               }
810             
811             bufsize *= 2;
812           }
813       }
814     while (!pw);
815 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
816     
817     if (!pw)
818       {
819         setpwent ();
820         pw = getpwuid (getuid ());
821         endpwent ();
822       }
823     if (pw)
824       {
825         g_user_name = g_strdup (pw->pw_name);
826
827         if (pw->pw_gecos && *pw->pw_gecos != '\0') 
828           {
829             gchar **gecos_fields;
830             gchar **name_parts;
831
832             /* split the gecos field and substitute '&' */
833             gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
834             name_parts = g_strsplit (gecos_fields[0], "&", 0);
835             pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
836             g_real_name = g_strjoinv (pw->pw_name, name_parts);
837             g_strfreev (gecos_fields);
838             g_strfreev (name_parts);
839           }
840
841         if (!g_home_dir)
842           g_home_dir = g_strdup (pw->pw_dir);
843       }
844     g_free (buffer);
845   }
846   
847 #else /* !HAVE_PWD_H */
848   
849 #ifdef G_OS_WIN32
850   {
851     guint len = UNLEN+1;
852     wchar_t buffer[UNLEN+1];
853     
854     if (GetUserNameW (buffer, (LPDWORD) &len))
855       {
856         g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
857         g_real_name = g_strdup (g_user_name);
858       }
859   }
860 #endif /* G_OS_WIN32 */
861
862 #endif /* !HAVE_PWD_H */
863
864 #ifndef G_OS_WIN32
865   if (!g_home_dir)
866     g_home_dir = g_strdup (g_getenv ("HOME"));
867 #endif
868
869 #ifdef __EMX__
870   /* change '\\' in %HOME% to '/' */
871   g_strdelimit (g_home_dir, "\\",'/');
872 #endif
873   if (!g_user_name)
874     g_user_name = g_strdup ("somebody");
875   if (!g_real_name)
876     g_real_name = g_strdup ("Unknown");
877
878   {
879 #ifndef G_OS_WIN32
880     gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
881 #else
882     DWORD size = sizeof (hostname);
883     gboolean hostname_fail = (!GetComputerName (hostname, &size));
884 #endif
885     g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
886   }
887
888 #ifdef G_OS_WIN32
889   g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
890   g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
891   g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
892
893   if (!g_tmp_dir_cp)
894     g_tmp_dir_cp = g_strdup ("\\");
895   if (!g_user_name_cp)
896     g_user_name_cp = g_strdup ("somebody");
897   if (!g_real_name_cp)
898     g_real_name_cp = g_strdup ("Unknown");
899
900   /* home_dir might be NULL, unlike tmp_dir, user_name and
901    * real_name.
902    */
903   if (g_home_dir)
904     g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
905   else
906     g_home_dir_cp = NULL;
907 #endif /* G_OS_WIN32 */
908 }
909
910 static inline void
911 g_get_any_init (void)
912 {
913   if (!g_tmp_dir)
914     g_get_any_init_do ();
915 }
916
917 static inline void
918 g_get_any_init_locked (void)
919 {
920   G_LOCK (g_utils_global);
921   g_get_any_init ();
922   G_UNLOCK (g_utils_global);
923 }
924
925
926 /**
927  * g_get_user_name:
928  *
929  * Gets the user name of the current user. The encoding of the returned
930  * string is system-defined. On UNIX, it might be the preferred file name
931  * encoding, or something else, and there is no guarantee that it is even
932  * consistent on a machine. On Windows, it is always UTF-8.
933  *
934  * Returns: the user name of the current user.
935  */
936 const gchar *
937 g_get_user_name (void)
938 {
939   g_get_any_init_locked ();
940   return g_user_name;
941 }
942
943 /**
944  * g_get_real_name:
945  *
946  * Gets the real name of the user. This usually comes from the user's entry 
947  * in the <filename>passwd</filename> file. The encoding of the returned 
948  * string is system-defined. (On Windows, it is, however, always UTF-8.) 
949  * If the real user name cannot be determined, the string "Unknown" is 
950  * returned.
951  *
952  * Returns: the user's real name.
953  */
954 const gchar *
955 g_get_real_name (void)
956 {
957   g_get_any_init_locked ();
958   return g_real_name;
959 }
960
961 /**
962  * g_get_home_dir:
963  *
964  * Gets the current user's home directory as defined in the 
965  * password database.
966  *
967  * Note that in contrast to traditional UNIX tools, this function 
968  * prefers <filename>passwd</filename> entries over the <envar>HOME</envar> 
969  * environment variable. 
970  *
971  * One of the reasons for this decision is that applications in many 
972  * cases need special handling to deal with the case where 
973  * <envar>HOME</envar> is
974  * <simplelist>
975  *   <member>Not owned by the user</member>
976  *   <member>Not writeable</member>
977  *   <member>Not even readable</member>
978  * </simplelist>
979  * Since applications are in general <emphasis>not</emphasis> written 
980  * to deal with these situations it was considered better to make 
981  * g_get_home_dir() not pay attention to <envar>HOME</envar> and to 
982  * return the real home directory for the user. If applications
983  * want to pay attention to <envar>HOME</envar>, they can do:
984  * |[
985  *  const char *homedir = g_getenv ("HOME");
986  *   if (!homedir)
987  *      homedir = g_get_home_dir (<!-- -->);
988  * ]|
989  *
990  * Returns: the current user's home directory
991  */
992 const gchar *
993 g_get_home_dir (void)
994 {
995   g_get_any_init_locked ();
996   return g_home_dir;
997 }
998
999 /**
1000  * g_get_tmp_dir:
1001  *
1002  * Gets the directory to use for temporary files. This is found from 
1003  * inspecting the environment variables <envar>TMPDIR</envar>, 
1004  * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none 
1005  * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. 
1006  * The encoding of the returned string is system-defined. On Windows, 
1007  * it is always UTF-8. The return value is never %NULL or the empty string.
1008  *
1009  * Returns: the directory to use for temporary files.
1010  */
1011 const gchar *
1012 g_get_tmp_dir (void)
1013 {
1014   g_get_any_init_locked ();
1015   return g_tmp_dir;
1016 }
1017
1018 /**
1019  * g_get_host_name:
1020  *
1021  * Return a name for the machine. 
1022  *
1023  * The returned name is not necessarily a fully-qualified domain name,
1024  * or even present in DNS or some other name service at all. It need
1025  * not even be unique on your local network or site, but usually it
1026  * is. Callers should not rely on the return value having any specific
1027  * properties like uniqueness for security purposes. Even if the name
1028  * of the machine is changed while an application is running, the
1029  * return value from this function does not change. The returned
1030  * string is owned by GLib and should not be modified or freed. If no
1031  * name can be determined, a default fixed string "localhost" is
1032  * returned.
1033  *
1034  * Returns: the host name of the machine.
1035  *
1036  * Since: 2.8
1037  */
1038 const gchar *
1039 g_get_host_name (void)
1040 {
1041   g_get_any_init_locked ();
1042   return g_host_name;
1043 }
1044
1045 G_LOCK_DEFINE_STATIC (g_prgname);
1046 static gchar *g_prgname = NULL;
1047
1048 /**
1049  * g_get_prgname:
1050  *
1051  * Gets the name of the program. This name should <emphasis>not</emphasis> 
1052  * be localized, contrast with g_get_application_name().
1053  * (If you are using GDK or GTK+ the program name is set in gdk_init(), 
1054  * which is called by gtk_init(). The program name is found by taking 
1055  * the last component of <literal>argv[0]</literal>.)
1056  *
1057  * Returns: the name of the program. The returned string belongs 
1058  * to GLib and must not be modified or freed.
1059  */
1060 gchar*
1061 g_get_prgname (void)
1062 {
1063   gchar* retval;
1064
1065   G_LOCK (g_prgname);
1066 #ifdef G_OS_WIN32
1067   if (g_prgname == NULL)
1068     {
1069       static gboolean beenhere = FALSE;
1070
1071       if (!beenhere)
1072         {
1073           gchar *utf8_buf = NULL;
1074           wchar_t buf[MAX_PATH+1];
1075
1076           beenhere = TRUE;
1077           if (GetModuleFileNameW (GetModuleHandle (NULL),
1078                                   buf, G_N_ELEMENTS (buf)) > 0)
1079             utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1080
1081           if (utf8_buf)
1082             {
1083               g_prgname = g_path_get_basename (utf8_buf);
1084               g_free (utf8_buf);
1085             }
1086         }
1087     }
1088 #endif
1089   retval = g_prgname;
1090   G_UNLOCK (g_prgname);
1091
1092   return retval;
1093 }
1094
1095 /**
1096  * g_set_prgname:
1097  * @prgname: the name of the program.
1098  *
1099  * Sets the name of the program. This name should <emphasis>not</emphasis> 
1100  * be localized, contrast with g_set_application_name(). Note that for 
1101  * thread-safety reasons this function can only be called once.
1102  */
1103 void
1104 g_set_prgname (const gchar *prgname)
1105 {
1106   G_LOCK (g_prgname);
1107   g_free (g_prgname);
1108   g_prgname = g_strdup (prgname);
1109   G_UNLOCK (g_prgname);
1110 }
1111
1112 G_LOCK_DEFINE_STATIC (g_application_name);
1113 static gchar *g_application_name = NULL;
1114
1115 /**
1116  * g_get_application_name:
1117  * 
1118  * Gets a human-readable name for the application, as set by
1119  * g_set_application_name(). This name should be localized if
1120  * possible, and is intended for display to the user.  Contrast with
1121  * g_get_prgname(), which gets a non-localized name. If
1122  * g_set_application_name() has not been called, returns the result of
1123  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1124  * been called).
1125  * 
1126  * Return value: human-readable application name. may return %NULL
1127  *
1128  * Since: 2.2
1129  **/
1130 const gchar *
1131 g_get_application_name (void)
1132 {
1133   gchar* retval;
1134
1135   G_LOCK (g_application_name);
1136   retval = g_application_name;
1137   G_UNLOCK (g_application_name);
1138
1139   if (retval == NULL)
1140     return g_get_prgname ();
1141   
1142   return retval;
1143 }
1144
1145 /**
1146  * g_set_application_name:
1147  * @application_name: localized name of the application
1148  *
1149  * Sets a human-readable name for the application. This name should be
1150  * localized if possible, and is intended for display to the user.
1151  * Contrast with g_set_prgname(), which sets a non-localized name.
1152  * g_set_prgname() will be called automatically by gtk_init(),
1153  * but g_set_application_name() will not.
1154  *
1155  * Note that for thread safety reasons, this function can only
1156  * be called once.
1157  *
1158  * The application name will be used in contexts such as error messages,
1159  * or when displaying an application's name in the task list.
1160  * 
1161  * Since: 2.2
1162  **/
1163 void
1164 g_set_application_name (const gchar *application_name)
1165 {
1166   gboolean already_set = FALSE;
1167         
1168   G_LOCK (g_application_name);
1169   if (g_application_name)
1170     already_set = TRUE;
1171   else
1172     g_application_name = g_strdup (application_name);
1173   G_UNLOCK (g_application_name);
1174
1175   if (already_set)
1176     g_warning ("g_set_application_name() called multiple times");
1177 }
1178
1179 /**
1180  * g_get_user_data_dir:
1181  * 
1182  * Returns a base directory in which to access application data such
1183  * as icons that is customized for a particular user.  
1184  *
1185  * On UNIX platforms this is determined using the mechanisms described in
1186  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1187  * XDG Base Directory Specification</ulink>.
1188  * In this case the directory retrieved will be XDG_DATA_HOME.
1189  *
1190  * On Windows this is the folder to use for local (as opposed to
1191  * roaming) application data. See documentation for
1192  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1193  * what g_get_user_config_dir() returns.
1194  *
1195  * Return value: a string owned by GLib that must not be modified 
1196  *               or freed.
1197  * Since: 2.6
1198  **/
1199 const gchar *
1200 g_get_user_data_dir (void)
1201 {
1202   gchar *data_dir;  
1203
1204   G_LOCK (g_utils_global);
1205
1206   if (!g_user_data_dir)
1207     {
1208 #ifdef G_OS_WIN32
1209       data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1210 #else
1211       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1212
1213       if (data_dir && data_dir[0])
1214         data_dir = g_strdup (data_dir);
1215 #endif
1216       if (!data_dir || !data_dir[0])
1217         {
1218           g_get_any_init ();
1219
1220           if (g_home_dir)
1221             data_dir = g_build_filename (g_home_dir, ".local", 
1222                                          "share", NULL);
1223           else
1224             data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local", 
1225                                          "share", NULL);
1226         }
1227
1228       g_user_data_dir = data_dir;
1229     }
1230   else
1231     data_dir = g_user_data_dir;
1232
1233   G_UNLOCK (g_utils_global);
1234
1235   return data_dir;
1236 }
1237
1238 static void
1239 g_init_user_config_dir (void)
1240 {
1241   gchar *config_dir;
1242
1243   if (!g_user_config_dir)
1244     {
1245 #ifdef G_OS_WIN32
1246       config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1247 #else
1248       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1249
1250       if (config_dir && config_dir[0])
1251         config_dir = g_strdup (config_dir);
1252 #endif
1253       if (!config_dir || !config_dir[0])
1254         {
1255           g_get_any_init ();
1256
1257           if (g_home_dir)
1258             config_dir = g_build_filename (g_home_dir, ".config", NULL);
1259           else
1260             config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
1261         }
1262
1263       g_user_config_dir = config_dir;
1264     }
1265 }
1266
1267 /**
1268  * g_get_user_config_dir:
1269  * 
1270  * Returns a base directory in which to store user-specific application 
1271  * configuration information such as user preferences and settings. 
1272  *
1273  * On UNIX platforms this is determined using the mechanisms described in
1274  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1275  * XDG Base Directory Specification</ulink>.
1276  * In this case the directory retrieved will be XDG_CONFIG_HOME.
1277  *
1278  * On Windows this is the folder to use for local (as opposed to
1279  * roaming) application data. See documentation for
1280  * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1281  * what g_get_user_data_dir() returns.
1282  *
1283  * Return value: a string owned by GLib that must not be modified 
1284  *               or freed.
1285  * Since: 2.6
1286  **/
1287 const gchar *
1288 g_get_user_config_dir (void)
1289 {
1290   G_LOCK (g_utils_global);
1291
1292   g_init_user_config_dir ();
1293
1294   G_UNLOCK (g_utils_global);
1295
1296   return g_user_config_dir;
1297 }
1298
1299 /**
1300  * g_get_user_cache_dir:
1301  * 
1302  * Returns a base directory in which to store non-essential, cached
1303  * data specific to particular user.
1304  *
1305  * On UNIX platforms this is determined using the mechanisms described in
1306  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1307  * XDG Base Directory Specification</ulink>.
1308  * In this case the directory retrieved will be XDG_CACHE_HOME.
1309  *
1310  * On Windows is the directory that serves as a common repository for
1311  * temporary Internet files. A typical path is
1312  * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1313  * See documentation for CSIDL_INTERNET_CACHE.
1314  *
1315  * Return value: a string owned by GLib that must not be modified 
1316  *               or freed.
1317  * Since: 2.6
1318  **/
1319 const gchar *
1320 g_get_user_cache_dir (void)
1321 {
1322   gchar *cache_dir;  
1323
1324   G_LOCK (g_utils_global);
1325
1326   if (!g_user_cache_dir)
1327     {
1328 #ifdef G_OS_WIN32
1329       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1330 #else
1331       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1332
1333       if (cache_dir && cache_dir[0])
1334           cache_dir = g_strdup (cache_dir);
1335 #endif
1336       if (!cache_dir || !cache_dir[0])
1337         {
1338           g_get_any_init ();
1339         
1340           if (g_home_dir)
1341             cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1342           else
1343             cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
1344         }
1345       g_user_cache_dir = cache_dir;
1346     }
1347   else
1348     cache_dir = g_user_cache_dir;
1349
1350   G_UNLOCK (g_utils_global);
1351
1352   return cache_dir;
1353 }
1354
1355 /**
1356  * g_get_user_runtime_dir:
1357  *
1358  * Returns a directory that is unique to the current user on the local
1359  * system.
1360  *
1361  * On UNIX platforms this is determined using the mechanisms described in
1362  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1363  * XDG Base Directory Specification</ulink>.  This is the directory
1364  * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1365  * In the case that this variable is not set, GLib will issue a warning
1366  * message to stderr and return the value of g_get_user_cache_dir().
1367  *
1368  * On Windows this is the folder to use for local (as opposed to
1369  * roaming) application data. See documentation for
1370  * CSIDL_LOCAL_APPDATA.  Note that on Windows it thus is the same as
1371  * what g_get_user_config_dir() returns.
1372  *
1373  * Returns: a string owned by GLib that must not be modified or freed.
1374  *
1375  * Since: 2.28
1376  **/
1377 const gchar *
1378 g_get_user_runtime_dir (void)
1379 {
1380 #ifndef G_OS_WIN32
1381   static const gchar *runtime_dir;
1382   static gsize initialised;
1383
1384   if (g_once_init_enter (&initialised))
1385     {
1386       runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1387       
1388       g_once_init_leave (&initialised, 1);
1389     }
1390
1391   if (runtime_dir)
1392     return runtime_dir;
1393
1394   /* Both fallback for UNIX and the default
1395    * in Windows: use the user cache directory.
1396    */
1397 #endif
1398
1399   return g_get_user_cache_dir ();
1400 }
1401
1402 #ifdef HAVE_CARBON
1403
1404 static gchar *
1405 find_folder (OSType type)
1406 {
1407   gchar *filename = NULL;
1408   FSRef  found;
1409
1410   if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1411     {
1412       CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1413
1414       if (url)
1415         {
1416           CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1417
1418           if (path)
1419             {
1420               filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1421
1422               if (! filename)
1423                 {
1424                   filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1425
1426                   CFStringGetCString (path, filename,
1427                                       CFStringGetLength (path) * 3 + 1,
1428                                       kCFStringEncodingUTF8);
1429                 }
1430
1431               CFRelease (path);
1432             }
1433
1434           CFRelease (url);
1435         }
1436     }
1437
1438   return filename;
1439 }
1440
1441 static void
1442 load_user_special_dirs (void)
1443 {
1444   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1445   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1446   g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1447   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1448   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1449   g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1450   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1451   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1452 }
1453
1454 #endif /* HAVE_CARBON */
1455
1456 #if defined(G_OS_WIN32)
1457 static void
1458 load_user_special_dirs (void)
1459 {
1460   typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1461                                                     DWORD dwFlags,
1462                                                     HANDLE hToken,
1463                                                     PWSTR *ppszPath);
1464   t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1465
1466   static const GUID FOLDERID_Downloads =
1467     { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1468   static const GUID FOLDERID_Public =
1469     { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1470
1471   wchar_t *wcp;
1472
1473   p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1474                                                                     "SHGetKnownFolderPath");
1475
1476   g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1477   g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1478
1479   if (p_SHGetKnownFolderPath == NULL)
1480     {
1481       g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1482     }
1483   else
1484     {
1485       wcp = NULL;
1486       (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1487       if (wcp)
1488         {
1489           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1490           if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1491               g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1492           CoTaskMemFree (wcp);
1493         }
1494       else
1495           g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1496     }
1497
1498   g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1499   g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1500
1501   if (p_SHGetKnownFolderPath == NULL)
1502     {
1503       /* XXX */
1504       g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1505     }
1506   else
1507     {
1508       wcp = NULL;
1509       (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1510       if (wcp)
1511         {
1512           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1513           if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1514               g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1515           CoTaskMemFree (wcp);
1516         }
1517       else
1518           g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1519     }
1520   
1521   g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1522   g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1523 }
1524 #endif /* G_OS_WIN32 */
1525
1526 static void g_init_user_config_dir (void);
1527
1528 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1529
1530 /* adapted from xdg-user-dir-lookup.c
1531  *
1532  * Copyright (C) 2007 Red Hat Inc.
1533  *
1534  * Permission is hereby granted, free of charge, to any person
1535  * obtaining a copy of this software and associated documentation files
1536  * (the "Software"), to deal in the Software without restriction,
1537  * including without limitation the rights to use, copy, modify, merge,
1538  * publish, distribute, sublicense, and/or sell copies of the Software,
1539  * and to permit persons to whom the Software is furnished to do so,
1540  * subject to the following conditions: 
1541  *
1542  * The above copyright notice and this permission notice shall be
1543  * included in all copies or substantial portions of the Software. 
1544  *
1545  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1546  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1547  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1548  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1549  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1550  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1551  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1552  * SOFTWARE.
1553  */
1554 static void
1555 load_user_special_dirs (void)
1556 {
1557   gchar *config_file;
1558   gchar *data;
1559   gchar **lines;
1560   gint n_lines, i;
1561   
1562   g_init_user_config_dir ();
1563   config_file = g_build_filename (g_user_config_dir,
1564                                   "user-dirs.dirs",
1565                                   NULL);
1566   
1567   if (!g_file_get_contents (config_file, &data, NULL, NULL))
1568     {
1569       g_free (config_file);
1570       return;
1571     }
1572
1573   lines = g_strsplit (data, "\n", -1);
1574   n_lines = g_strv_length (lines);
1575   g_free (data);
1576   
1577   for (i = 0; i < n_lines; i++)
1578     {
1579       gchar *buffer = lines[i];
1580       gchar *d, *p;
1581       gint len;
1582       gboolean is_relative = FALSE;
1583       GUserDirectory directory;
1584
1585       /* Remove newline at end */
1586       len = strlen (buffer);
1587       if (len > 0 && buffer[len - 1] == '\n')
1588         buffer[len - 1] = 0;
1589       
1590       p = buffer;
1591       while (*p == ' ' || *p == '\t')
1592         p++;
1593       
1594       if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1595         {
1596           directory = G_USER_DIRECTORY_DESKTOP;
1597           p += strlen ("XDG_DESKTOP_DIR");
1598         }
1599       else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1600         {
1601           directory = G_USER_DIRECTORY_DOCUMENTS;
1602           p += strlen ("XDG_DOCUMENTS_DIR");
1603         }
1604       else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1605         {
1606           directory = G_USER_DIRECTORY_DOWNLOAD;
1607           p += strlen ("XDG_DOWNLOAD_DIR");
1608         }
1609       else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1610         {
1611           directory = G_USER_DIRECTORY_MUSIC;
1612           p += strlen ("XDG_MUSIC_DIR");
1613         }
1614       else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1615         {
1616           directory = G_USER_DIRECTORY_PICTURES;
1617           p += strlen ("XDG_PICTURES_DIR");
1618         }
1619       else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1620         {
1621           directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1622           p += strlen ("XDG_PUBLICSHARE_DIR");
1623         }
1624       else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1625         {
1626           directory = G_USER_DIRECTORY_TEMPLATES;
1627           p += strlen ("XDG_TEMPLATES_DIR");
1628         }
1629       else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1630         {
1631           directory = G_USER_DIRECTORY_VIDEOS;
1632           p += strlen ("XDG_VIDEOS_DIR");
1633         }
1634       else
1635         continue;
1636
1637       while (*p == ' ' || *p == '\t')
1638         p++;
1639
1640       if (*p != '=')
1641         continue;
1642       p++;
1643
1644       while (*p == ' ' || *p == '\t')
1645         p++;
1646
1647       if (*p != '"')
1648         continue;
1649       p++;
1650
1651       if (strncmp (p, "$HOME", 5) == 0)
1652         {
1653           p += 5;
1654           is_relative = TRUE;
1655         }
1656       else if (*p != '/')
1657         continue;
1658
1659       d = strrchr (p, '"');
1660       if (!d)
1661         continue;
1662       *d = 0;
1663
1664       d = p;
1665       
1666       /* remove trailing slashes */
1667       len = strlen (d);
1668       if (d[len - 1] == '/')
1669         d[len - 1] = 0;
1670       
1671       if (is_relative)
1672         {
1673           g_get_any_init ();
1674           g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
1675         }
1676       else
1677         g_user_special_dirs[directory] = g_strdup (d);
1678     }
1679
1680   g_strfreev (lines);
1681   g_free (config_file);
1682 }
1683
1684 #endif /* G_OS_UNIX && !HAVE_CARBON */
1685
1686
1687 /**
1688  * g_reload_user_special_dirs_cache:
1689  *
1690  * Resets the cache used for g_get_user_special_dir(), so
1691  * that the latest on-disk version is used. Call this only
1692  * if you just changed the data on disk yourself.
1693  *
1694  * Due to threadsafety issues this may cause leaking of strings
1695  * that were previously returned from g_get_user_special_dir()
1696  * that can't be freed. We ensure to only leak the data for
1697  * the directories that actually changed value though.
1698  *
1699  * Since: 2.22
1700  */
1701 void
1702 g_reload_user_special_dirs_cache (void)
1703 {
1704   int i;
1705
1706   G_LOCK (g_utils_global);
1707
1708   if (g_user_special_dirs != NULL)
1709     {
1710       /* save a copy of the pointer, to check if some memory can be preserved */
1711       char **old_g_user_special_dirs = g_user_special_dirs;
1712       char *old_val;
1713
1714       /* recreate and reload our cache */
1715       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1716       load_user_special_dirs ();
1717
1718       /* only leak changed directories */
1719       for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1720         {
1721           old_val = old_g_user_special_dirs[i];
1722           if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1723             {
1724               /* don't leak */
1725               g_free (g_user_special_dirs[i]);
1726               g_user_special_dirs[i] = old_val;
1727             }
1728           else
1729             g_free (old_val);
1730         }
1731
1732       /* free the old array */
1733       g_free (old_g_user_special_dirs);
1734     }
1735
1736   G_UNLOCK (g_utils_global);
1737 }
1738
1739 /**
1740  * g_get_user_special_dir:
1741  * @directory: the logical id of special directory
1742  *
1743  * Returns the full path of a special directory using its logical id.
1744  *
1745  * On Unix this is done using the XDG special user directories.
1746  * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1747  * falls back to <filename>$HOME/Desktop</filename> when XDG special
1748  * user directories have not been set up. 
1749  *
1750  * Depending on the platform, the user might be able to change the path
1751  * of the special directory without requiring the session to restart; GLib
1752  * will not reflect any change once the special directories are loaded.
1753  *
1754  * Return value: the path to the specified special directory, or %NULL
1755  *   if the logical id was not found. The returned string is owned by
1756  *   GLib and should not be modified or freed.
1757  *
1758  * Since: 2.14
1759  */
1760 const gchar *
1761 g_get_user_special_dir (GUserDirectory directory)
1762 {
1763   g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1764                         directory < G_USER_N_DIRECTORIES, NULL);
1765
1766   G_LOCK (g_utils_global);
1767
1768   if (G_UNLIKELY (g_user_special_dirs == NULL))
1769     {
1770       g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1771
1772       load_user_special_dirs ();
1773
1774       /* Special-case desktop for historical compatibility */
1775       if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1776         {
1777           g_get_any_init ();
1778
1779           g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
1780             g_build_filename (g_home_dir, "Desktop", NULL);
1781         }
1782     }
1783
1784   G_UNLOCK (g_utils_global);
1785
1786   return g_user_special_dirs[directory];
1787 }
1788
1789 #ifdef G_OS_WIN32
1790
1791 #undef g_get_system_data_dirs
1792
1793 static HMODULE
1794 get_module_for_address (gconstpointer address)
1795 {
1796   /* Holds the g_utils_global lock */
1797
1798   static gboolean beenhere = FALSE;
1799   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1800   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1801   HMODULE hmodule = NULL;
1802
1803   if (!address)
1804     return NULL;
1805
1806   if (!beenhere)
1807     {
1808       p_GetModuleHandleExA =
1809         (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1810                                                "GetModuleHandleExA");
1811       beenhere = TRUE;
1812     }
1813
1814   if (p_GetModuleHandleExA == NULL ||
1815       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1816                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1817                                 address, &hmodule))
1818     {
1819       MEMORY_BASIC_INFORMATION mbi;
1820       VirtualQuery (address, &mbi, sizeof (mbi));
1821       hmodule = (HMODULE) mbi.AllocationBase;
1822     }
1823
1824   return hmodule;
1825 }
1826
1827 static gchar *
1828 get_module_share_dir (gconstpointer address)
1829 {
1830   HMODULE hmodule;
1831   gchar *filename;
1832   gchar *retval;
1833
1834   hmodule = get_module_for_address (address);
1835   if (hmodule == NULL)
1836     return NULL;
1837
1838   filename = g_win32_get_package_installation_directory_of_module (hmodule);
1839   retval = g_build_filename (filename, "share", NULL);
1840   g_free (filename);
1841
1842   return retval;
1843 }
1844
1845 const gchar * const *
1846 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
1847 {
1848   GArray *data_dirs;
1849   HMODULE hmodule;
1850   static GHashTable *per_module_data_dirs = NULL;
1851   gchar **retval;
1852   gchar *p;
1853   gchar *exe_root;
1854       
1855   if (address_of_function)
1856     {
1857       G_LOCK (g_utils_global);
1858       hmodule = get_module_for_address (address_of_function);
1859       if (hmodule != NULL)
1860         {
1861           if (per_module_data_dirs == NULL)
1862             per_module_data_dirs = g_hash_table_new (NULL, NULL);
1863           else
1864             {
1865               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1866               
1867               if (retval != NULL)
1868                 {
1869                   G_UNLOCK (g_utils_global);
1870                   return (const gchar * const *) retval;
1871                 }
1872             }
1873         }
1874     }
1875
1876   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1877
1878   /* Documents and Settings\All Users\Application Data */
1879   p = get_special_folder (CSIDL_COMMON_APPDATA);
1880   if (p)
1881     g_array_append_val (data_dirs, p);
1882   
1883   /* Documents and Settings\All Users\Documents */
1884   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1885   if (p)
1886     g_array_append_val (data_dirs, p);
1887         
1888   /* Using the above subfolders of Documents and Settings perhaps
1889    * makes sense from a Windows perspective.
1890    *
1891    * But looking at the actual use cases of this function in GTK+
1892    * and GNOME software, what we really want is the "share"
1893    * subdirectory of the installation directory for the package
1894    * our caller is a part of.
1895    *
1896    * The address_of_function parameter, if non-NULL, points to a
1897    * function in the calling module. Use that to determine that
1898    * module's installation folder, and use its "share" subfolder.
1899    *
1900    * Additionally, also use the "share" subfolder of the installation
1901    * locations of GLib and the .exe file being run.
1902    *
1903    * To guard against none of the above being what is really wanted,
1904    * callers of this function should have Win32-specific code to look
1905    * up their installation folder themselves, and handle a subfolder
1906    * "share" of it in the same way as the folders returned from this
1907    * function.
1908    */
1909
1910   p = get_module_share_dir (address_of_function);
1911   if (p)
1912     g_array_append_val (data_dirs, p);
1913     
1914   if (glib_dll != NULL)
1915     {
1916       gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1917       p = g_build_filename (glib_root, "share", NULL);
1918       if (p)
1919         g_array_append_val (data_dirs, p);
1920       g_free (glib_root);
1921     }
1922   
1923   exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1924   p = g_build_filename (exe_root, "share", NULL);
1925   if (p)
1926     g_array_append_val (data_dirs, p);
1927   g_free (exe_root);
1928
1929   retval = (gchar **) g_array_free (data_dirs, FALSE);
1930
1931   if (address_of_function)
1932     {
1933       if (hmodule != NULL)
1934         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1935       G_UNLOCK (g_utils_global);
1936     }
1937
1938   return (const gchar * const *) retval;
1939 }
1940
1941 #endif
1942
1943 /**
1944  * g_get_system_data_dirs:
1945  * 
1946  * Returns an ordered list of base directories in which to access 
1947  * system-wide application data.
1948  *
1949  * On UNIX platforms this is determined using the mechanisms described in
1950  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1951  * XDG Base Directory Specification</ulink>
1952  * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1953  *
1954  * On Windows the first elements in the list are the Application Data
1955  * and Documents folders for All Users. (These can be determined only
1956  * on Windows 2000 or later and are not present in the list on other
1957  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1958  * CSIDL_COMMON_DOCUMENTS.
1959  *
1960  * Then follows the "share" subfolder in the installation folder for
1961  * the package containing the DLL that calls this function, if it can
1962  * be determined.
1963  * 
1964  * Finally the list contains the "share" subfolder in the installation
1965  * folder for GLib, and in the installation folder for the package the
1966  * application's .exe file belongs to.
1967  *
1968  * The installation folders above are determined by looking up the
1969  * folder where the module (DLL or EXE) in question is located. If the
1970  * folder's name is "bin", its parent is used, otherwise the folder
1971  * itself.
1972  *
1973  * Note that on Windows the returned list can vary depending on where
1974  * this function is called.
1975  *
1976  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must 
1977  *               not be modified or freed.
1978  * Since: 2.6
1979  **/
1980 const gchar * const * 
1981 g_get_system_data_dirs (void)
1982 {
1983   gchar **data_dir_vector;
1984
1985   G_LOCK (g_utils_global);
1986
1987   if (!g_system_data_dirs)
1988     {
1989 #ifdef G_OS_WIN32
1990       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1991 #else
1992       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1993
1994       if (!data_dirs || !data_dirs[0])
1995           data_dirs = "/usr/local/share/:/usr/share/";
1996
1997       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1998 #endif
1999
2000       g_system_data_dirs = data_dir_vector;
2001     }
2002   else
2003     data_dir_vector = g_system_data_dirs;
2004
2005   G_UNLOCK (g_utils_global);
2006
2007   return (const gchar * const *) data_dir_vector;
2008 }
2009
2010 /**
2011  * g_get_system_config_dirs:
2012  * 
2013  * Returns an ordered list of base directories in which to access 
2014  * system-wide configuration information.
2015  *
2016  * On UNIX platforms this is determined using the mechanisms described in
2017  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2018  * XDG Base Directory Specification</ulink>.
2019  * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2020  *
2021  * On Windows is the directory that contains application data for all users.
2022  * A typical path is C:\Documents and Settings\All Users\Application Data.
2023  * This folder is used for application data that is not user specific.
2024  * For example, an application can store a spell-check dictionary, a database
2025  * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2026  * This information will not roam and is available to anyone using the computer.
2027  *
2028  * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must 
2029  *               not be modified or freed.
2030  * Since: 2.6
2031  **/
2032 const gchar * const *
2033 g_get_system_config_dirs (void)
2034 {
2035   gchar *conf_dirs, **conf_dir_vector;
2036
2037   G_LOCK (g_utils_global);
2038
2039   if (!g_system_config_dirs)
2040     {
2041 #ifdef G_OS_WIN32
2042       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2043       if (conf_dirs)
2044         {
2045           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2046           g_free (conf_dirs);
2047         }
2048       else
2049         {
2050           /* Return empty list */
2051           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2052         }
2053 #else
2054       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2055
2056       if (!conf_dirs || !conf_dirs[0])
2057           conf_dirs = "/etc/xdg";
2058
2059       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2060 #endif
2061
2062       g_system_config_dirs = conf_dir_vector;
2063     }
2064   else
2065     conf_dir_vector = g_system_config_dirs;
2066   G_UNLOCK (g_utils_global);
2067
2068   return (const gchar * const *) conf_dir_vector;
2069 }
2070
2071 /**
2072  * g_nullify_pointer:
2073  * @nullify_location: the memory address of the pointer.
2074  *
2075  * Set the pointer at the specified location to %NULL.
2076  **/
2077 void
2078 g_nullify_pointer (gpointer *nullify_location)
2079 {
2080   g_return_if_fail (nullify_location != NULL);
2081
2082   *nullify_location = NULL;
2083 }
2084
2085 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2086 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2087 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2088 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2089 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2090 #define EXABYTE_FACTOR  (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2091
2092 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2093 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2094 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2095 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2096 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2097 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2098
2099 /**
2100  * g_format_size:
2101  * @size: a size in bytes
2102  *
2103  * Formats a size (for example the size of a file) into a human readable
2104  * string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
2105  * and are displayed rounded to the nearest tenth. E.g. the file size
2106  * 3292528 bytes will be converted into the string "3.2 MB".
2107  *
2108  * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2109  *
2110  * This string should be freed with g_free() when not needed any longer.
2111  *
2112  * See g_format_size_full() for more options about how the size might be
2113  * formatted.
2114  *
2115  * Returns: a newly-allocated formatted string containing a human readable
2116  *     file size
2117  *
2118  * Since: 2.30
2119  */
2120 gchar *
2121 g_format_size (guint64 size)
2122 {
2123   return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2124 }
2125
2126 /**
2127  * GFormatSizeFlags:
2128  * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2129  * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2130  *     of the returned string.  For example, "45.6 kB (45,612 bytes)".
2131  * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2132  *     suffixes. IEC units should only be used for reporting things with
2133  *     a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2134  *     Network and storage sizes should be reported in the normal SI units.
2135  *
2136  * Flags to modify the format of the string returned by g_format_size_full().
2137  */
2138
2139 /**
2140  * g_format_size_full:
2141  * @size: a size in bytes
2142  * @flags: #GFormatSizeFlags to modify the output
2143  *
2144  * Formats a size.
2145  *
2146  * This function is similar to g_format_size() but allows for flags
2147  * that modify the output. See #GFormatSizeFlags.
2148  *
2149  * Returns: a newly-allocated formatted string containing a human
2150  *     readable file size
2151  *
2152  * Since: 2.30
2153  */
2154 gchar *
2155 g_format_size_full (guint64          size,
2156                     GFormatSizeFlags flags)
2157 {
2158   GString *string;
2159
2160   string = g_string_new (NULL);
2161
2162   if (flags & G_FORMAT_SIZE_IEC_UNITS)
2163     {
2164       if (size < KIBIBYTE_FACTOR)
2165         {
2166           g_string_printf (string,
2167                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2168                            (guint) size);
2169           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2170         }
2171
2172       else if (size < MEBIBYTE_FACTOR)
2173         g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2174       else if (size < GIBIBYTE_FACTOR)
2175         g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2176
2177       else if (size < TEBIBYTE_FACTOR)
2178         g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2179
2180       else if (size < PEBIBYTE_FACTOR)
2181         g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2182
2183       else if (size < EXBIBYTE_FACTOR)
2184         g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2185
2186       else
2187         g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2188     }
2189   else
2190     {
2191       if (size < KILOBYTE_FACTOR)
2192         {
2193           g_string_printf (string,
2194                            g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2195                            (guint) size);
2196           flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2197         }
2198
2199       else if (size < MEGABYTE_FACTOR)
2200         g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2201
2202       else if (size < GIGABYTE_FACTOR)
2203         g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2204
2205       else if (size < TERABYTE_FACTOR)
2206         g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2207       else if (size < PETABYTE_FACTOR)
2208         g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2209
2210       else if (size < EXABYTE_FACTOR)
2211         g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2212
2213       else
2214         g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2215     }
2216
2217   if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2218     {
2219       /* First problem: we need to use the number of bytes to decide on
2220        * the plural form that is used for display, but the number of
2221        * bytes potentially exceeds the size of a guint (which is what
2222        * ngettext() takes).
2223        *
2224        * From a pragmatic standpoint, it seems that all known languages
2225        * base plural forms on one or both of the following:
2226        *
2227        *   - the lowest digits of the number
2228        *
2229        *   - if the number if greater than some small value
2230        *
2231        * Here's how we fake it:  Draw an arbitrary line at one thousand.
2232        * If the number is below that, then fine.  If it is above it,
2233        * then we take the modulus of the number by one thousand (in
2234        * order to keep the lowest digits) and add one thousand to that
2235        * (in order to ensure that 1001 is not treated the same as 1).
2236        */
2237       guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2238
2239       /* Second problem: we need to translate the string "%u byte" and
2240        * "%u bytes" for pluralisation, but the correct number format to
2241        * use for a gsize is different depending on which architecture
2242        * we're on.
2243        *
2244        * Solution: format the number separately and use "%s bytes" on
2245        * all platforms.
2246        */
2247       const gchar *translated_format;
2248       gchar *formatted_number;
2249
2250       /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2251       translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2252       /* XXX: Windows doesn't support the "'" format modifier, so we
2253        * must not use it there.  Instead, just display the number
2254        * without separation.  Bug #655336 is open until a solution is
2255        * found.
2256        */
2257 #ifndef G_OS_WIN32
2258       formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2259 #else
2260       formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2261 #endif
2262
2263       g_string_append (string, " (");
2264       g_string_append_printf (string, translated_format, formatted_number);
2265       g_free (formatted_number);
2266       g_string_append (string, ")");
2267     }
2268
2269   return g_string_free (string, FALSE);
2270 }
2271
2272 /**
2273  * g_format_size_for_display:
2274  * @size: a size in bytes
2275  *
2276  * Formats a size (for example the size of a file) into a human
2277  * readable string. Sizes are rounded to the nearest size prefix
2278  * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2279  * E.g. the file size 3292528 bytes will be converted into the
2280  * string "3.1 MB".
2281  *
2282  * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2283  *
2284  * This string should be freed with g_free() when not needed any longer.
2285  *
2286  * Returns: a newly-allocated formatted string containing a human
2287  *     readable file size
2288  *
2289  * Since: 2.16
2290  *
2291  * Deprecated:2.30: This function is broken due to its use of SI
2292  *     suffixes to denote IEC units. Use g_format_size() instead.
2293  */
2294 gchar *
2295 g_format_size_for_display (goffset size)
2296 {
2297   if (size < (goffset) KIBIBYTE_FACTOR)
2298     return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2299   else
2300     {
2301       gdouble displayed_size;
2302
2303       if (size < (goffset) MEBIBYTE_FACTOR)
2304         {
2305           displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2306           return g_strdup_printf (_("%.1f KB"), displayed_size);
2307         }
2308       else if (size < (goffset) GIBIBYTE_FACTOR)
2309         {
2310           displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2311           return g_strdup_printf (_("%.1f MB"), displayed_size);
2312         }
2313       else if (size < (goffset) TEBIBYTE_FACTOR)
2314         {
2315           displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2316           return g_strdup_printf (_("%.1f GB"), displayed_size);
2317         }
2318       else if (size < (goffset) PEBIBYTE_FACTOR)
2319         {
2320           displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2321           return g_strdup_printf (_("%.1f TB"), displayed_size);
2322         }
2323       else if (size < (goffset) EXBIBYTE_FACTOR)
2324         {
2325           displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2326           return g_strdup_printf (_("%.1f PB"), displayed_size);
2327         }
2328       else
2329         {
2330           displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2331           return g_strdup_printf (_("%.1f EB"), displayed_size);
2332         }
2333     }
2334 }
2335
2336 #ifdef G_OS_WIN32
2337
2338 /**
2339  * _glib_get_locale_dir:
2340  *
2341  * Return the path to the share\locale or lib\locale subfolder of the
2342  * GLib installation folder. The path is in the system codepage. We
2343  * have to use system codepage as bindtextdomain() doesn't have a
2344  * UTF-8 interface.
2345  */
2346 gchar *
2347 _glib_get_locale_dir (void)
2348 {
2349   gchar *install_dir = NULL, *locale_dir;
2350   gchar *retval = NULL;
2351
2352   if (glib_dll != NULL)
2353     install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
2354
2355   if (install_dir)
2356     {
2357       /*
2358        * Append "/share/locale" or "/lib/locale" depending on whether
2359        * autoconfigury detected GNU gettext or not.
2360        */
2361       const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
2362       while (*--p != '/')
2363         ;
2364       while (*--p != '/')
2365         ;
2366
2367       locale_dir = g_build_filename (install_dir, p, NULL);
2368
2369       retval = g_win32_locale_filename_from_utf8 (locale_dir);
2370
2371       g_free (install_dir);
2372       g_free (locale_dir);
2373     }
2374
2375   if (retval)
2376     return retval;
2377   else
2378     return g_strdup ("");
2379 }
2380
2381 #undef GLIB_LOCALE_DIR
2382
2383 #endif /* G_OS_WIN32 */
2384
2385 static void
2386 ensure_gettext_initialized (void)
2387 {
2388   static gsize initialised;
2389
2390   if (g_once_init_enter (&initialised))
2391     {
2392 #ifdef G_OS_WIN32
2393       gchar *tmp = _glib_get_locale_dir ();
2394       bindtextdomain (GETTEXT_PACKAGE, tmp);
2395       g_free (tmp);
2396 #else
2397       bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
2398 #endif
2399 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2400       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2401 #    endif
2402       g_once_init_leave (&initialised, TRUE);
2403     }
2404 }
2405
2406 /**
2407  * glib_gettext:
2408  * @str: The string to be translated
2409  *
2410  * Returns the translated string from the glib translations.
2411  * This is an internal function and should only be used by
2412  * the internals of glib (such as libgio).
2413  *
2414  * Returns: the transation of @str to the current locale
2415  */
2416 const gchar *
2417 glib_gettext (const gchar *str)
2418 {
2419   ensure_gettext_initialized();
2420
2421   return g_dgettext (GETTEXT_PACKAGE, str);
2422 }
2423
2424 /**
2425  * glib_pgettext:
2426  * @msgctxtid: a combined message context and message id, separated
2427  *   by a \004 character
2428  * @msgidoffset: the offset of the message id in @msgctxid
2429  *
2430  * This function is a variant of glib_gettext() which supports
2431  * a disambiguating message context. See g_dpgettext() for full
2432  * details.
2433  *
2434  * This is an internal function and should only be used by
2435  * the internals of glib (such as libgio).
2436  *
2437  * Returns: the transation of @str to the current locale
2438  */
2439 const gchar *
2440 glib_pgettext(const gchar *msgctxtid,
2441               gsize        msgidoffset)
2442 {
2443   ensure_gettext_initialized();
2444
2445   return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
2446 }
2447
2448 #if defined (G_OS_WIN32) && !defined (_WIN64)
2449
2450 /* Binary compatibility versions. Not for newly compiled code. */
2451
2452 #undef g_find_program_in_path
2453
2454 gchar*
2455 g_find_program_in_path (const gchar *program)
2456 {
2457   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2458   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2459   gchar *retval;
2460
2461   g_free (utf8_program);
2462   if (utf8_retval == NULL)
2463     return NULL;
2464   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2465   g_free (utf8_retval);
2466
2467   return retval;
2468 }
2469
2470 #undef g_get_user_name
2471
2472 const gchar *
2473 g_get_user_name (void)
2474 {
2475   g_get_any_init_locked ();
2476   return g_user_name_cp;
2477 }
2478
2479 #undef g_get_real_name
2480
2481 const gchar *
2482 g_get_real_name (void)
2483 {
2484   g_get_any_init_locked ();
2485   return g_real_name_cp;
2486 }
2487
2488 #undef g_get_home_dir
2489
2490 const gchar *
2491 g_get_home_dir (void)
2492 {
2493   g_get_any_init_locked ();
2494   return g_home_dir_cp;
2495 }
2496
2497 #undef g_get_tmp_dir
2498
2499 const gchar *
2500 g_get_tmp_dir (void)
2501 {
2502   g_get_any_init_locked ();
2503   return g_tmp_dir_cp;
2504 }
2505
2506 #endif