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