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