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