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