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