bump version number to 2.11.0
[platform/upstream/glib.git] / glib / gutils.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1998  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
29  */
30
31 #include "config.h"
32
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <locale.h>
40 #include <string.h>
41 #include <errno.h>
42 #ifdef HAVE_PWD_H
43 #include <pwd.h>
44 #endif
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_PARAM_H
47 #include <sys/param.h>
48 #endif
49 #ifdef HAVE_CRT_EXTERNS_H 
50 #include <crt_externs.h> /* for _NSGetEnviron */
51 #endif
52
53 /* implement gutils's inline functions
54  */
55 #define G_IMPLEMENT_INLINES 1
56 #define __G_UTILS_C__
57 #include "glib.h"
58 #include "gprintfint.h"
59 #include "gthreadinit.h"
60 #include "galias.h"
61
62 #ifdef  MAXPATHLEN
63 #define G_PATH_LENGTH   MAXPATHLEN
64 #elif   defined (PATH_MAX)
65 #define G_PATH_LENGTH   PATH_MAX
66 #elif   defined (_PC_PATH_MAX)
67 #define G_PATH_LENGTH   sysconf(_PC_PATH_MAX)
68 #else   
69 #define G_PATH_LENGTH   2048
70 #endif
71
72 #ifdef G_PLATFORM_WIN32
73 #  define STRICT                /* Strict typing, please */
74 #  include <windows.h>
75 #  undef STRICT
76 #  ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
77 #    define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
78 #    define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
79 #  endif
80 #  include <lmcons.h>           /* For UNLEN */
81 #endif /* G_PLATFORM_WIN32 */
82
83 #ifdef G_OS_WIN32
84 #  include <direct.h>
85 #  include <shlobj.h>
86    /* older SDK (e.g. msvc 5.0) does not have these*/
87 #  ifndef CSIDL_INTERNET_CACHE
88 #    define CSIDL_INTERNET_CACHE 32
89 #  endif
90 #  ifndef CSIDL_COMMON_APPDATA
91 #    define CSIDL_COMMON_APPDATA 35
92 #  endif
93 #  ifndef CSIDL_COMMON_DOCUMENTS
94 #    define CSIDL_COMMON_DOCUMENTS 46
95 #  endif
96 #  ifndef CSIDL_PROFILE
97 #    define CSIDL_PROFILE 40
98 #  endif
99 #  include <process.h>
100 #endif
101
102 #ifdef HAVE_CODESET
103 #include <langinfo.h>
104 #endif
105
106 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
107 #include <libintl.h>
108 #endif
109
110 const guint glib_major_version = GLIB_MAJOR_VERSION;
111 const guint glib_minor_version = GLIB_MINOR_VERSION;
112 const guint glib_micro_version = GLIB_MICRO_VERSION;
113 const guint glib_interface_age = GLIB_INTERFACE_AGE;
114 const guint glib_binary_age = GLIB_BINARY_AGE;
115
116 #ifdef G_PLATFORM_WIN32
117
118 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
119
120 #endif
121
122 /**
123  * glib_check_version:
124  * @required_major: the required major version.
125  * @required_minor: the required minor version.
126  * @required_micro: the required micro version.
127  *
128  * Checks that the GLib library in use is compatible with the
129  * given version. Generally you would pass in the constants
130  * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
131  * as the three arguments to this function; that produces
132  * a check that the library in use is compatible with
133  * the version of GLib the application or module was compiled
134  * against.
135  *
136  * Compatibility is defined by two things: first the version
137  * of the running library is newer than the version
138  * @required_major.required_minor.@required_micro. Second
139  * the running library must be binary compatible with the
140  * version @required_major.required_minor.@required_micro
141  * (same major version.)
142  *
143  * Return value: %NULL if the GLib library is compatible with the
144  *   given version, or a string describing the version mismatch.
145  *   The returned string is owned by GLib and must not be modified
146  *   or freed.
147  *
148  * Since: 2.6
149  **/
150 const gchar *
151 glib_check_version (guint required_major,
152                     guint required_minor,
153                     guint required_micro)
154 {
155   gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
156   gint required_effective_micro = 100 * required_minor + required_micro;
157
158   if (required_major > GLIB_MAJOR_VERSION)
159     return "GLib version too old (major mismatch)";
160   if (required_major < GLIB_MAJOR_VERSION)
161     return "GLib version too new (major mismatch)";
162   if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
163     return "GLib version too new (micro mismatch)";
164   if (required_effective_micro > glib_effective_micro)
165     return "GLib version too old (micro mismatch)";
166   return NULL;
167 }
168
169 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
170 /**
171  * g_memmove: 
172  * @dest: the destination address to copy the bytes to.
173  * @src: the source address to copy the bytes from.
174  * @len: the number of bytes to copy.
175  *
176  * Copies a block of memory @len bytes long, from @src to @dest.
177  * The source and destination areas may overlap.
178  *
179  * In order to use this function, you must include 
180  * <filename>string.h</filename> yourself, because this macro will 
181  * typically simply resolve to memmove() and GLib does not include 
182  * <filename>string.h</filename> for you.
183  */
184 void 
185 g_memmove (gpointer      dest, 
186            gconstpointer src, 
187            gulong        len)
188 {
189   gchar* destptr = dest;
190   const gchar* srcptr = src;
191   if (src + len < dest || dest + len < src)
192     {
193       bcopy (src, dest, len);
194       return;
195     }
196   else if (dest <= src)
197     {
198       while (len--)
199         *(destptr++) = *(srcptr++);
200     }
201   else
202     {
203       destptr += len;
204       srcptr += len;
205       while (len--)
206         *(--destptr) = *(--srcptr);
207     }
208 }
209 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
210
211 #ifdef G_OS_WIN32
212 #undef g_atexit
213 #endif
214
215 /**
216  * g_atexit:
217  * @func: the function to call on normal program termination.
218  * 
219  * Specifies a function to be called at normal program termination.
220  *
221  * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
222  * macro that maps to a call to the atexit() function in the C
223  * library. This means that in case the code that calls g_atexit(),
224  * i.e. atexit(), is in a DLL, the function will be called when the
225  * DLL is detached from the program. This typically makes more sense
226  * than that the function is called when the GLib DLL is detached,
227  * which happened earlier when g_atexit() was a function in the GLib
228  * DLL.
229  *
230  * The behaviour of atexit() in the context of dynamically loaded
231  * modules is not formally specified and varies wildly.
232  *
233  * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
234  * loaded module which is unloaded before the program terminates might
235  * well cause a crash at program exit.
236  *
237  * Some POSIX systems implement atexit() like Windows, and have each
238  * dynamically loaded module maintain an own atexit chain that is
239  * called when the module is unloaded.
240  *
241  * On other POSIX systems, before a dynamically loaded module is
242  * unloaded, the registered atexit functions (if any) residing in that
243  * module are called, regardless where the code that registered them
244  * resided. This is presumably the most robust approach.
245  *
246  * As can be seen from the above, for portability it's best to avoid
247  * calling g_atexit() (or atexit()) except in the main executable of a
248  * program.
249  */
250 void
251 g_atexit (GVoidFunc func)
252 {
253   gint result;
254   const gchar *error = NULL;
255
256   /* keep this in sync with glib.h */
257
258 #ifdef  G_NATIVE_ATEXIT
259   result = ATEXIT (func);
260   if (result)
261     error = g_strerror (errno);
262 #elif defined (HAVE_ATEXIT)
263 #  ifdef NeXT /* @#%@! NeXTStep */
264   result = !atexit ((void (*)(void)) func);
265   if (result)
266     error = g_strerror (errno);
267 #  else
268   result = atexit ((void (*)(void)) func);
269   if (result)
270     error = g_strerror (errno);
271 #  endif /* NeXT */
272 #elif defined (HAVE_ON_EXIT)
273   result = on_exit ((void (*)(int, void *)) func, NULL);
274   if (result)
275     error = g_strerror (errno);
276 #else
277   result = 0;
278   error = "no implementation";
279 #endif /* G_NATIVE_ATEXIT */
280
281   if (error)
282     g_error ("Could not register atexit() function: %s", error);
283 }
284
285 /* Based on execvp() from GNU Libc.
286  * Some of this code is cut-and-pasted into gspawn.c
287  */
288
289 static gchar*
290 my_strchrnul (const gchar *str, 
291               gchar        c)
292 {
293   gchar *p = (gchar*)str;
294   while (*p && (*p != c))
295     ++p;
296
297   return p;
298 }
299
300 #ifdef G_OS_WIN32
301
302 static gchar *inner_find_program_in_path (const gchar *program);
303
304 gchar*
305 g_find_program_in_path (const gchar *program)
306 {
307   const gchar *last_dot = strrchr (program, '.');
308
309   if (last_dot == NULL ||
310       strchr (last_dot, '\\') != NULL ||
311       strchr (last_dot, '/') != NULL)
312     {
313       const gint program_length = strlen (program);
314       gchar *pathext = g_build_path (";",
315                                      ".exe;.cmd;.bat;.com",
316                                      g_getenv ("PATHEXT"),
317                                      NULL);
318       gchar *p;
319       gchar *decorated_program;
320       gchar *retval;
321
322       p = pathext;
323       do
324         {
325           gchar *q = my_strchrnul (p, ';');
326
327           decorated_program = g_malloc (program_length + (q-p) + 1);
328           memcpy (decorated_program, program, program_length);
329           memcpy (decorated_program+program_length, p, q-p);
330           decorated_program [program_length + (q-p)] = '\0';
331           
332           retval = inner_find_program_in_path (decorated_program);
333           g_free (decorated_program);
334
335           if (retval != NULL)
336             {
337               g_free (pathext);
338               return retval;
339             }
340           p = q;
341         } while (*p++ != '\0');
342       g_free (pathext);
343       return NULL;
344     }
345   else
346     return inner_find_program_in_path (program);
347 }
348
349 #endif
350
351 /**
352  * g_find_program_in_path:
353  * @program: a program name in the GLib file name encoding
354  * 
355  * Locates the first executable named @program in the user's path, in the
356  * same way that execvp() would locate it. Returns an allocated string
357  * with the absolute path name, or %NULL if the program is not found in
358  * the path. If @program is already an absolute path, returns a copy of
359  * @program if @program exists and is executable, and %NULL otherwise.
360  *  
361  * On Windows, if @program does not have a file type suffix, tries
362  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
363  * the <envar>PATHEXT</envar> environment variable. 
364  * 
365  * On Windows, it looks for the file in the same way as CreateProcess() 
366  * would. This means first in the directory where the executing
367  * program was loaded from, then in the current directory, then in the
368  * Windows 32-bit system directory, then in the Windows directory, and
369  * finally in the directories in the <envar>PATH</envar> environment 
370  * variable. If the program is found, the return value contains the 
371  * full name including the type suffix.
372  *
373  * Return value: absolute path, or %NULL
374  **/
375 #ifdef G_OS_WIN32
376 static gchar *
377 inner_find_program_in_path (const gchar *program)
378 #else
379 gchar*
380 g_find_program_in_path (const gchar *program)
381 #endif
382 {
383   const gchar *path, *p;
384   gchar *name, *freeme;
385 #ifdef G_OS_WIN32
386   const gchar *path_copy;
387   gchar *filename = NULL, *appdir = NULL;
388   gchar *sysdir = NULL, *windir = NULL;
389 #endif
390   size_t len;
391   size_t pathlen;
392
393   g_return_val_if_fail (program != NULL, NULL);
394
395   /* If it is an absolute path, or a relative path including subdirectories,
396    * don't look in PATH.
397    */
398   if (g_path_is_absolute (program)
399       || strchr (program, G_DIR_SEPARATOR) != NULL
400 #ifdef G_OS_WIN32
401       || strchr (program, '/') != NULL
402 #endif
403       )
404     {
405       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
406           !g_file_test (program, G_FILE_TEST_IS_DIR))
407         return g_strdup (program);
408       else
409         return NULL;
410     }
411   
412   path = g_getenv ("PATH");
413 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
414   if (path == NULL)
415     {
416       /* There is no `PATH' in the environment.  The default
417        * search path in GNU libc is the current directory followed by
418        * the path `confstr' returns for `_CS_PATH'.
419        */
420       
421       /* In GLib we put . last, for security, and don't use the
422        * unportable confstr(); UNIX98 does not actually specify
423        * what to search if PATH is unset. POSIX may, dunno.
424        */
425       
426       path = "/bin:/usr/bin:.";
427     }
428 #else
429   if (G_WIN32_HAVE_WIDECHAR_API ())
430     {
431       int n;
432       wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
433         wwindir[MAXPATHLEN];
434       
435       n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
436       if (n > 0 && n < MAXPATHLEN)
437         filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
438       
439       n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
440       if (n > 0 && n < MAXPATHLEN)
441         sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
442       
443       n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
444       if (n > 0 && n < MAXPATHLEN)
445         windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
446     }
447   else
448     {
449       int n;
450       gchar cpfilename[MAXPATHLEN], cpsysdir[MAXPATHLEN],
451         cpwindir[MAXPATHLEN];
452       
453       n = GetModuleFileNameA (NULL, cpfilename, MAXPATHLEN);
454       if (n > 0 && n < MAXPATHLEN)
455         filename = g_locale_to_utf8 (cpfilename, -1, NULL, NULL, NULL);
456       
457       n = GetSystemDirectoryA (cpsysdir, MAXPATHLEN);
458       if (n > 0 && n < MAXPATHLEN)
459         sysdir = g_locale_to_utf8 (cpsysdir, -1, NULL, NULL, NULL);
460       
461       n = GetWindowsDirectoryA (cpwindir, MAXPATHLEN);
462       if (n > 0 && n < MAXPATHLEN)
463         windir = g_locale_to_utf8 (cpwindir, -1, NULL, NULL, NULL);
464     }
465   
466   if (filename)
467     {
468       appdir = g_path_get_dirname (filename);
469       g_free (filename);
470     }
471   
472   path = g_strdup (path);
473
474   if (windir)
475     {
476       const gchar *tem = path;
477       path = g_strconcat (windir, ";", path, NULL);
478       g_free ((gchar *) tem);
479       g_free (windir);
480     }
481   
482   if (sysdir)
483     {
484       const gchar *tem = path;
485       path = g_strconcat (sysdir, ";", path, NULL);
486       g_free ((gchar *) tem);
487       g_free (sysdir);
488     }
489   
490   {
491     const gchar *tem = path;
492     path = g_strconcat (".;", path, NULL);
493     g_free ((gchar *) tem);
494   }
495   
496   if (appdir)
497     {
498       const gchar *tem = path;
499       path = g_strconcat (appdir, ";", path, NULL);
500       g_free ((gchar *) tem);
501       g_free (appdir);
502     }
503
504   path_copy = path;
505 #endif
506   
507   len = strlen (program) + 1;
508   pathlen = strlen (path);
509   freeme = name = g_malloc (pathlen + len + 1);
510   
511   /* Copy the file name at the top, including '\0'  */
512   memcpy (name + pathlen + 1, program, len);
513   name = name + pathlen;
514   /* And add the slash before the filename  */
515   *name = G_DIR_SEPARATOR;
516   
517   p = path;
518   do
519     {
520       char *startp;
521
522       path = p;
523       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
524
525       if (p == path)
526         /* Two adjacent colons, or a colon at the beginning or the end
527          * of `PATH' means to search the current directory.
528          */
529         startp = name + 1;
530       else
531         startp = memcpy (name - (p - path), path, p - path);
532
533       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
534           !g_file_test (startp, G_FILE_TEST_IS_DIR))
535         {
536           gchar *ret;
537           ret = g_strdup (startp);
538           g_free (freeme);
539 #ifdef G_OS_WIN32
540           g_free ((gchar *) path_copy);
541 #endif
542           return ret;
543         }
544     }
545   while (*p++ != '\0');
546   
547   g_free (freeme);
548 #ifdef G_OS_WIN32
549   g_free ((gchar *) path_copy);
550 #endif
551
552   return NULL;
553 }
554
555 /**
556  * g_parse_debug_string:
557  * @string: a list of debug options separated by ':' or "all" 
558  *     to set all flags.
559  * @keys: pointer to an array of #GDebugKey which associate 
560  *     strings with bit flags.
561  * @nkeys: the number of #GDebugKey<!-- -->s in the array.
562  *
563  * Parses a string containing debugging options separated 
564  * by ':' into a %guint containing bit flags. This is used 
565  * within GDK and GTK+ to parse the debug options passed on the
566  * command line or through environment variables.
567  *
568  * Returns: the combined set of bit flags.
569  */
570 guint        
571 g_parse_debug_string  (const gchar     *string, 
572                        const GDebugKey *keys, 
573                        guint            nkeys)
574 {
575   guint i;
576   guint result = 0;
577   
578   g_return_val_if_fail (string != NULL, 0);
579
580   /* this function is used by gmem.c/gslice.c initialization code,
581    * so introducing malloc dependencies here would require adaptions
582    * of those code portions.
583    */
584   
585   if (!g_ascii_strcasecmp (string, "all"))
586     {
587       for (i=0; i<nkeys; i++)
588         result |= keys[i].value;
589     }
590   else
591     {
592       const gchar *p = string;
593       const gchar *q;
594       
595       while (*p)
596         {
597           q = strchr (p, ':');
598           if (!q)
599             q = p + strlen(p);
600           
601           for (i = 0; i < nkeys; i++)
602             if (g_ascii_strncasecmp (keys[i].key, p, q - p) == 0 &&
603                 keys[i].key[q - p] == '\0')
604               result |= keys[i].value;
605           
606           p = q;
607           if (*p == ':')
608             p++;
609         }
610     }
611   
612   return result;
613 }
614
615 /**
616  * g_basename:
617  * @file_name: the name of the file.
618  * 
619  * Gets the name of the file without any leading directory components.  
620  * It returns a pointer into the given file name string.
621  * 
622  * Return value: the name of the file without any leading directory components.
623  *
624  * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
625  * g_path_get_basename() allocates new memory for the returned string, unlike
626  * this function which returns a pointer into the argument.
627  **/
628 G_CONST_RETURN gchar*
629 g_basename (const gchar    *file_name)
630 {
631   register gchar *base;
632   
633   g_return_val_if_fail (file_name != NULL, NULL);
634   
635   base = strrchr (file_name, G_DIR_SEPARATOR);
636
637 #ifdef G_OS_WIN32
638   {
639     gchar *q = strrchr (file_name, '/');
640     if (base == NULL || (q != NULL && q > base))
641         base = q;
642   }
643 #endif
644
645   if (base)
646     return base + 1;
647
648 #ifdef G_OS_WIN32
649   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
650     return (gchar*) file_name + 2;
651 #endif /* G_OS_WIN32 */
652   
653   return (gchar*) file_name;
654 }
655
656 /**
657  * g_path_get_basename:
658  * @file_name: the name of the file.
659  *
660  * Gets the last component of the filename. If @file_name ends with a 
661  * directory separator it gets the component before the last slash. If 
662  * @file_name consists only of directory separators (and on Windows, 
663  * possibly a drive letter), a single separator is returned. If
664  * @file_name is empty, it gets ".".
665  *
666  * Return value: a newly allocated string containing the last component of 
667  *   the filename.
668  */
669 gchar*
670 g_path_get_basename (const gchar   *file_name)
671 {
672   register gssize base;             
673   register gssize last_nonslash;    
674   gsize len;    
675   gchar *retval;
676  
677   g_return_val_if_fail (file_name != NULL, NULL);
678
679   if (file_name[0] == '\0')
680     /* empty string */
681     return g_strdup (".");
682   
683   last_nonslash = strlen (file_name) - 1;
684
685   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
686     last_nonslash--;
687
688   if (last_nonslash == -1)
689     /* string only containing slashes */
690     return g_strdup (G_DIR_SEPARATOR_S);
691
692 #ifdef G_OS_WIN32
693   if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
694     /* string only containing slashes and a drive */
695     return g_strdup (G_DIR_SEPARATOR_S);
696 #endif /* G_OS_WIN32 */
697
698   base = last_nonslash;
699
700   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
701     base--;
702
703 #ifdef G_OS_WIN32
704   if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
705     base = 1;
706 #endif /* G_OS_WIN32 */
707
708   len = last_nonslash - base;
709   retval = g_malloc (len + 1);
710   memcpy (retval, file_name + base + 1, len);
711   retval [len] = '\0';
712   return retval;
713 }
714
715 /**
716  * g_path_is_absolute:
717  * @file_name: a file name.
718  *
719  * Returns %TRUE if the given @file_name is an absolute file name,
720  * i.e. it contains a full path from the root directory such as "/usr/local"
721  * on UNIX or "C:\windows" on Windows systems.
722  *
723  * Returns: %TRUE if @file_name is an absolute path. 
724  */
725 gboolean
726 g_path_is_absolute (const gchar *file_name)
727 {
728   g_return_val_if_fail (file_name != NULL, FALSE);
729   
730   if (G_IS_DIR_SEPARATOR (file_name[0]))
731     return TRUE;
732
733 #ifdef G_OS_WIN32
734   /* Recognize drive letter on native Windows */
735   if (g_ascii_isalpha (file_name[0]) && 
736       file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
737     return TRUE;
738 #endif /* G_OS_WIN32 */
739
740   return FALSE;
741 }
742
743 /**
744  * g_path_skip_root:
745  * @file_name: a file name.
746  *
747  * Returns a pointer into @file_name after the root component, i.e. after
748  * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
749  * path it returns %NULL.
750  *
751  * Returns: a pointer into @file_name after the root component.
752  */
753 G_CONST_RETURN gchar*
754 g_path_skip_root (const gchar *file_name)
755 {
756   g_return_val_if_fail (file_name != NULL, NULL);
757   
758 #ifdef G_PLATFORM_WIN32
759   /* Skip \\server\share or //server/share */
760   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
761       G_IS_DIR_SEPARATOR (file_name[1]) &&
762       file_name[2] &&
763       !G_IS_DIR_SEPARATOR (file_name[2]))
764     {
765       gchar *p;
766
767       p = strchr (file_name + 2, G_DIR_SEPARATOR);
768 #ifdef G_OS_WIN32
769       {
770         gchar *q = strchr (file_name + 2, '/');
771         if (p == NULL || (q != NULL && q < p))
772           p = q;
773       }
774 #endif
775       if (p &&
776           p > file_name + 2 &&
777           p[1])
778         {
779           file_name = p + 1;
780
781           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
782             file_name++;
783
784           /* Possibly skip a backslash after the share name */
785           if (G_IS_DIR_SEPARATOR (file_name[0]))
786             file_name++;
787
788           return (gchar *)file_name;
789         }
790     }
791 #endif
792   
793   /* Skip initial slashes */
794   if (G_IS_DIR_SEPARATOR (file_name[0]))
795     {
796       while (G_IS_DIR_SEPARATOR (file_name[0]))
797         file_name++;
798       return (gchar *)file_name;
799     }
800
801 #ifdef G_OS_WIN32
802   /* Skip X:\ */
803   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
804     return (gchar *)file_name + 3;
805 #endif
806
807   return NULL;
808 }
809
810 /**
811  * g_path_get_dirname:
812  * @file_name: the name of the file.
813  *
814  * Gets the directory components of a file name.  If the file name has no
815  * directory components "." is returned.  The returned string should be
816  * freed when no longer needed.
817  * 
818  * Returns: the directory components of the file.
819  */
820 gchar*
821 g_path_get_dirname (const gchar    *file_name)
822 {
823   register gchar *base;
824   register gsize len;    
825   
826   g_return_val_if_fail (file_name != NULL, NULL);
827   
828   base = strrchr (file_name, G_DIR_SEPARATOR);
829 #ifdef G_OS_WIN32
830   {
831     gchar *q = strrchr (file_name, '/');
832     if (base == NULL || (q != NULL && q > base))
833         base = q;
834   }
835 #endif
836   if (!base)
837     {
838 #ifdef G_OS_WIN32
839       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
840         {
841           gchar drive_colon_dot[4];
842
843           drive_colon_dot[0] = file_name[0];
844           drive_colon_dot[1] = ':';
845           drive_colon_dot[2] = '.';
846           drive_colon_dot[3] = '\0';
847
848           return g_strdup (drive_colon_dot);
849         }
850 #endif
851     return g_strdup (".");
852     }
853
854   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
855     base--;
856
857 #ifdef G_OS_WIN32
858   /* base points to the char before the last slash.
859    *
860    * In case file_name is the root of a drive (X:\) or a child of the
861    * root of a drive (X:\foo), include the slash.
862    *
863    * In case file_name is the root share of an UNC path
864    * (\\server\share), add a slash, returning \\server\share\ .
865    *
866    * In case file_name is a direct child of a share in an UNC path
867    * (\\server\share\foo), include the slash after the share name,
868    * returning \\server\share\ .
869    */
870   if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
871     base++;
872   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
873            G_IS_DIR_SEPARATOR (file_name[1]) &&
874            file_name[2] &&
875            !G_IS_DIR_SEPARATOR (file_name[2]) &&
876            base >= file_name + 2)
877     {
878       const gchar *p = file_name + 2;
879       while (*p && !G_IS_DIR_SEPARATOR (*p))
880         p++;
881       if (p == base + 1)
882         {
883           len = (guint) strlen (file_name) + 1;
884           base = g_new (gchar, len + 1);
885           strcpy (base, file_name);
886           base[len-1] = G_DIR_SEPARATOR;
887           base[len] = 0;
888           return base;
889         }
890       if (G_IS_DIR_SEPARATOR (*p))
891         {
892           p++;
893           while (*p && !G_IS_DIR_SEPARATOR (*p))
894             p++;
895           if (p == base + 1)
896             base++;
897         }
898     }
899 #endif
900
901   len = (guint) 1 + base - file_name;
902   
903   base = g_new (gchar, len + 1);
904   g_memmove (base, file_name, len);
905   base[len] = 0;
906   
907   return base;
908 }
909
910 /**
911  * g_get_current_dir:
912  *
913  * Gets the current directory.
914  * The returned string should be freed when no longer needed. The encoding 
915  * of the returned string is system defined. On Windows, it is always UTF-8.
916  * 
917  * Returns: the current directory.
918  */
919 gchar*
920 g_get_current_dir (void)
921 {
922 #ifdef G_OS_WIN32
923
924   gchar *dir = NULL;
925
926   if (G_WIN32_HAVE_WIDECHAR_API ())
927     {
928       wchar_t dummy[2], *wdir;
929       int len;
930
931       len = GetCurrentDirectoryW (2, dummy);
932       wdir = g_new (wchar_t, len);
933
934       if (GetCurrentDirectoryW (len, wdir) == len - 1)
935         dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
936
937       g_free (wdir);
938     }
939   else
940     {
941       gchar dummy[2], *cpdir;
942       int len;
943
944       len = GetCurrentDirectoryA (2, dummy);
945       cpdir = g_new (gchar, len);
946
947       if (GetCurrentDirectoryA (len, cpdir) == len - 1)
948         dir = g_locale_to_utf8 (cpdir, -1, NULL, NULL, NULL);
949
950       g_free (cpdir);
951     }
952
953   if (dir == NULL)
954     dir = g_strdup ("\\");
955
956   return dir;
957
958 #else
959
960   gchar *buffer = NULL;
961   gchar *dir = NULL;
962   static gulong max_len = 0;
963
964   if (max_len == 0) 
965     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
966   
967   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
968    * and, if that wasn't bad enough, hangs in doing so.
969    */
970 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
971   buffer = g_new (gchar, max_len + 1);
972   *buffer = 0;
973   dir = getwd (buffer);
974 #else   /* !sun || !HAVE_GETCWD */
975   while (max_len < G_MAXULONG / 2)
976     {
977       buffer = g_new (gchar, max_len + 1);
978       *buffer = 0;
979       dir = getcwd (buffer, max_len);
980
981       if (dir || errno != ERANGE)
982         break;
983
984       g_free (buffer);
985       max_len *= 2;
986     }
987 #endif  /* !sun || !HAVE_GETCWD */
988   
989   if (!dir || !*buffer)
990     {
991       /* hm, should we g_error() out here?
992        * this can happen if e.g. "./" has mode \0000
993        */
994       buffer[0] = G_DIR_SEPARATOR;
995       buffer[1] = 0;
996     }
997
998   dir = g_strdup (buffer);
999   g_free (buffer);
1000   
1001   return dir;
1002 #endif /* !Win32 */
1003 }
1004
1005 /**
1006  * g_getenv:
1007  * @variable: the environment variable to get, in the GLib file name encoding.
1008  * 
1009  * Returns the value of an environment variable. The name and value
1010  * are in the GLib file name encoding. On UNIX, this means the actual
1011  * bytes which might or might not be in some consistent character set
1012  * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1013  * environment variable's value contains references to other
1014  * environment variables, they are expanded.
1015  * 
1016  * Return value: the value of the environment variable, or %NULL if
1017  * the environment variable is not found. The returned string may be
1018  * overwritten by the next call to g_getenv(), g_setenv() or
1019  * g_unsetenv().
1020  **/
1021 G_CONST_RETURN gchar*
1022 g_getenv (const gchar *variable)
1023 {
1024 #ifndef G_OS_WIN32
1025
1026   g_return_val_if_fail (variable != NULL, NULL);
1027
1028   return getenv (variable);
1029
1030 #else /* G_OS_WIN32 */
1031
1032   GQuark quark;
1033   gchar *value;
1034
1035   g_return_val_if_fail (variable != NULL, NULL);
1036   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1037
1038   /* On Windows NT, it is relatively typical that environment
1039    * variables contain references to other environment variables. If
1040    * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1041    * environment variables would be stored in the Registry as
1042    * REG_EXPAND_SZ type values, and would then get automatically
1043    * expanded before a program sees them. But there is broken software
1044    * that stores environment variables as REG_SZ values even if they
1045    * contain references to other environment variables.)
1046    */
1047
1048   if (G_WIN32_HAVE_WIDECHAR_API ())
1049     {
1050       wchar_t dummy[2], *wname, *wvalue;
1051       int len;
1052       
1053       wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1054
1055       len = GetEnvironmentVariableW (wname, dummy, 2);
1056
1057       if (len == 0)
1058         {
1059           g_free (wname);
1060           return NULL;
1061         }
1062       else if (len == 1)
1063         len = 2;
1064
1065       wvalue = g_new (wchar_t, len);
1066
1067       if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1068         {
1069           g_free (wname);
1070           g_free (wvalue);
1071           return NULL;
1072         }
1073
1074       if (wcschr (wvalue, L'%') != NULL)
1075         {
1076           wchar_t *tem = wvalue;
1077
1078           len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1079
1080           if (len > 0)
1081             {
1082               wvalue = g_new (wchar_t, len);
1083
1084               if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1085                 {
1086                   g_free (wvalue);
1087                   wvalue = tem;
1088                 }
1089               else
1090                 g_free (tem);
1091             }
1092         }
1093
1094       value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1095
1096       g_free (wname);
1097       g_free (wvalue);
1098     }
1099   else
1100     {
1101       gchar dummy[3], *cpname, *cpvalue;
1102       int len;
1103       
1104       cpname = g_locale_from_utf8 (variable, -1, NULL, NULL, NULL);
1105
1106       g_return_val_if_fail (cpname != NULL, NULL);
1107
1108       len = GetEnvironmentVariableA (cpname, dummy, 2);
1109
1110       if (len == 0)
1111         {
1112           g_free (cpname);
1113           return NULL;
1114         }
1115       else if (len == 1)
1116         len = 2;
1117
1118       cpvalue = g_new (gchar, len);
1119
1120       if (GetEnvironmentVariableA (cpname, cpvalue, len) != len - 1)
1121         {
1122           g_free (cpname);
1123           g_free (cpvalue);
1124           return NULL;
1125         }
1126
1127       if (strchr (cpvalue, '%') != NULL)
1128         {
1129           gchar *tem = cpvalue;
1130
1131           len = ExpandEnvironmentStringsA (cpvalue, dummy, 3);
1132
1133           if (len > 0)
1134             {
1135               cpvalue = g_new (gchar, len);
1136
1137               if (ExpandEnvironmentStringsA (tem, cpvalue, len) != len)
1138                 {
1139                   g_free (cpvalue);
1140                   cpvalue = tem;
1141                 }
1142               else
1143                 g_free (tem);
1144             }
1145         }
1146
1147       value = g_locale_to_utf8 (cpvalue, -1, NULL, NULL, NULL);
1148
1149       g_free (cpname);
1150       g_free (cpvalue);
1151     }
1152
1153   quark = g_quark_from_string (value);
1154   g_free (value);
1155   
1156   return g_quark_to_string (quark);
1157
1158 #endif /* G_OS_WIN32 */
1159 }
1160
1161 /* _g_getenv_nomalloc
1162  * this function does a getenv() without doing any kind of allocation
1163  * through glib. it's suitable for chars <= 127 only (both, for the
1164  * variable name and the contents) and for contents < 1024 chars in
1165  * length. also, it aliases "" to a NULL return value.
1166  **/
1167 const gchar*
1168 _g_getenv_nomalloc (const gchar *variable,
1169                     gchar        buffer[1024])
1170 {
1171   const gchar *retval = getenv (variable);
1172   if (retval && retval[0])
1173     {
1174       gint l = strlen (retval);
1175       if (l < 1024)
1176         {
1177           strncpy (buffer, retval, l);
1178           buffer[l] = 0;
1179           return buffer;
1180         }
1181     }
1182   return NULL;
1183 }
1184
1185 /**
1186  * g_setenv:
1187  * @variable: the environment variable to set, must not contain '='.
1188  * @value: the value for to set the variable to.
1189  * @overwrite: whether to change the variable if it already exists.
1190  *
1191  * Sets an environment variable. Both the variable's name and value
1192  * should be in the GLib file name encoding. On UNIX, this means that
1193  * they can be any sequence of bytes. On Windows, they should be in
1194  * UTF-8.
1195  *
1196  * Note that on some systems, when variables are overwritten, the memory 
1197  * used for the previous variables and its value isn't reclaimed.
1198  *
1199  * Returns: %FALSE if the environment variable couldn't be set.
1200  *
1201  * Since: 2.4
1202  */
1203 gboolean
1204 g_setenv (const gchar *variable, 
1205           const gchar *value, 
1206           gboolean     overwrite)
1207 {
1208 #ifndef G_OS_WIN32
1209
1210   gint result;
1211 #ifndef HAVE_SETENV
1212   gchar *string;
1213 #endif
1214
1215   g_return_val_if_fail (variable != NULL, FALSE);
1216   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1217
1218 #ifdef HAVE_SETENV
1219   result = setenv (variable, value, overwrite);
1220 #else
1221   if (!overwrite && getenv (variable) != NULL)
1222     return TRUE;
1223   
1224   /* This results in a leak when you overwrite existing
1225    * settings. It would be fairly easy to fix this by keeping
1226    * our own parallel array or hash table.
1227    */
1228   string = g_strconcat (variable, "=", value, NULL);
1229   result = putenv (string);
1230 #endif
1231   return result == 0;
1232
1233 #else /* G_OS_WIN32 */
1234
1235   gboolean retval;
1236
1237   g_return_val_if_fail (variable != NULL, FALSE);
1238   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1239   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1240   g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1241
1242   if (!overwrite && g_getenv (variable) != NULL)
1243     return TRUE;
1244
1245   /* We want to (if possible) set both the environment variable copy
1246    * kept by the C runtime and the one kept by the system.
1247    *
1248    * We can't use only the C runtime's putenv or _wputenv() as that
1249    * won't work for arbitrary Unicode strings in a "non-Unicode" app
1250    * (with main() and not wmain()). In a "main()" app the C runtime
1251    * initializes the C runtime's environment table by converting the
1252    * real (wide char) environment variables to system codepage, thus
1253    * breaking those that aren't representable in the system codepage.
1254    *
1255    * As the C runtime's putenv() will also set the system copy, we do
1256    * the putenv() first, then call SetEnvironmentValueW ourselves.
1257    */
1258
1259   if (G_WIN32_HAVE_WIDECHAR_API ())
1260     {
1261       wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1262       wchar_t *wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1263       gchar *tem = g_strconcat (variable, "=", value, NULL);
1264       wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1265       
1266       g_free (tem);
1267       _wputenv (wassignment);
1268       g_free (wassignment);
1269
1270       retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1271
1272       g_free (wname);
1273       g_free (wvalue);
1274     }
1275   else
1276     {
1277       /* In the non-Unicode case (Win9x), just putenv() is good
1278        * enough.
1279        */
1280       gchar *tem = g_strconcat (variable, "=", value, NULL);
1281       gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1282
1283       g_free (tem);
1284       
1285       retval = (putenv (cpassignment) == 0);
1286
1287       g_free (cpassignment);
1288     }
1289
1290   return retval;
1291
1292 #endif /* G_OS_WIN32 */
1293 }
1294
1295 #ifdef HAVE__NSGETENVIRON
1296 #define environ (*_NSGetEnviron())
1297 #elif !defined(G_OS_WIN32)
1298
1299 /* According to the Single Unix Specification, environ is not in 
1300  * any system header, although unistd.h often declares it.
1301  */
1302 extern char **environ;
1303 #endif
1304
1305 /**
1306  * g_unsetenv:
1307  * @variable: the environment variable to remove, must not contain '='.
1308  * 
1309  * Removes an environment variable from the environment.
1310  *
1311  * Note that on some systems, when variables are overwritten, the memory 
1312  * used for the previous variables and its value isn't reclaimed.
1313  * Furthermore, this function can't be guaranteed to operate in a 
1314  * threadsafe way.
1315  *
1316  * Since: 2.4 
1317  **/
1318 void
1319 g_unsetenv (const gchar *variable)
1320 {
1321 #ifndef G_OS_WIN32
1322
1323 #ifdef HAVE_UNSETENV
1324   g_return_if_fail (variable != NULL);
1325   g_return_if_fail (strchr (variable, '=') == NULL);
1326
1327   unsetenv (variable);
1328 #else /* !HAVE_UNSETENV */
1329   int len;
1330   gchar **e, **f;
1331
1332   g_return_if_fail (variable != NULL);
1333   g_return_if_fail (strchr (variable, '=') == NULL);
1334
1335   len = strlen (variable);
1336   
1337   /* Mess directly with the environ array.
1338    * This seems to be the only portable way to do this.
1339    *
1340    * Note that we remove *all* environment entries for
1341    * the variable name, not just the first.
1342    */
1343   e = f = environ;
1344   while (*e != NULL) 
1345     {
1346       if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=') 
1347         {
1348           *f = *e;
1349           f++;
1350         }
1351       e++;
1352     }
1353   *f = NULL;
1354 #endif /* !HAVE_UNSETENV */
1355
1356 #else  /* G_OS_WIN32 */
1357
1358   g_return_if_fail (variable != NULL);
1359   g_return_if_fail (strchr (variable, '=') == NULL);
1360   g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1361
1362   if (G_WIN32_HAVE_WIDECHAR_API ())
1363     {
1364       wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1365       gchar *tem = g_strconcat (variable, "=", NULL);
1366       wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1367       
1368       g_free (tem);
1369       _wputenv (wassignment);
1370       g_free (wassignment);
1371
1372       SetEnvironmentVariableW (wname, NULL);
1373
1374       g_free (wname);
1375     }
1376   else
1377     {
1378       /* In the non-Unicode case (Win9x), just putenv() is good
1379        * enough.
1380        */
1381       gchar *tem = g_strconcat (variable, "=", NULL);
1382       gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1383
1384       g_free (tem);
1385       
1386       putenv (cpassignment);
1387
1388       g_free (cpassignment);
1389     }
1390
1391 #endif /* G_OS_WIN32 */
1392 }
1393
1394 /**
1395  * g_listenv:
1396  *
1397  * Gets the names of all variables set in the environment.
1398  * 
1399  * Returns: a %NULL-terminated list of strings which must be freed
1400  * with g_strfreev().
1401  *
1402  * Since: 2.8
1403  */
1404 gchar **
1405 g_listenv (void)
1406 {
1407 #ifndef G_OS_WIN32
1408   gchar **result, *eq;
1409   gint len, i, j;
1410
1411   len = g_strv_length (environ);
1412   result = g_new0 (gchar *, len + 1);
1413   
1414   j = 0;
1415   for (i = 0; i < len; i++)
1416     {
1417       eq = strchr (environ[i], '=');
1418       if (eq)
1419         result[j++] = g_strndup (environ[i], eq - environ[i]);
1420     }
1421
1422   result[j] = NULL;
1423
1424   return result;
1425 #else
1426   gchar **result, *eq;
1427   gint len = 0, i, j;
1428
1429   if (G_WIN32_HAVE_WIDECHAR_API ())
1430     {
1431       wchar_t *p, *q;
1432
1433       p = (wchar_t *) GetEnvironmentStringsW ();
1434       if (p != NULL)
1435         {
1436           q = p;
1437           while (*q)
1438             {
1439               q += wcslen (q) + 1;
1440               len++;
1441             }
1442         }
1443       result = g_new0 (gchar *, len + 1);
1444
1445       j = 0;
1446       q = p;
1447       while (*q)
1448         {
1449           result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1450           if (result[j] != NULL)
1451             {
1452               eq = strchr (result[j], '=');
1453               if (eq && eq > result[j])
1454                 {
1455                   *eq = '\0';
1456                   j++;
1457                 }
1458               else
1459                 g_free (result[j]);
1460             }
1461           q += wcslen (q) + 1;
1462         }
1463       result[j] = NULL;
1464       FreeEnvironmentStringsW (p);
1465     }
1466   else
1467     {
1468       len = g_strv_length (environ);
1469       result = g_new0 (gchar *, len + 1);
1470       
1471       j = 0;
1472       for (i = 0; i < len; i++)
1473         {
1474           result[j] = g_locale_to_utf8 (environ[i], -1, NULL, NULL, NULL);
1475           if (result[j] != NULL)
1476             {
1477               eq = strchr (result[j], '=');
1478               if (eq && eq > result[j])
1479                 {
1480                   *eq = '\0';
1481                   j++;
1482                 }
1483               else
1484                 g_free (result[j]);
1485             }
1486         }
1487       result[j] = NULL;
1488     }
1489
1490   return result;
1491 #endif
1492 }
1493
1494 G_LOCK_DEFINE_STATIC (g_utils_global);
1495
1496 static  gchar   *g_tmp_dir = NULL;
1497 static  gchar   *g_user_name = NULL;
1498 static  gchar   *g_real_name = NULL;
1499 static  gchar   *g_home_dir = NULL;
1500 static  gchar   *g_host_name = NULL;
1501
1502 #ifdef G_OS_WIN32
1503 /* System codepage versions of the above, kept at file level so that they,
1504  * too, are produced only once.
1505  */
1506 static  gchar   *g_tmp_dir_cp = NULL;
1507 static  gchar   *g_user_name_cp = NULL;
1508 static  gchar   *g_real_name_cp = NULL;
1509 static  gchar   *g_home_dir_cp = NULL;
1510 #endif
1511
1512 static  gchar   *g_user_data_dir = NULL;
1513 static  gchar  **g_system_data_dirs = NULL;
1514 static  gchar   *g_user_cache_dir = NULL;
1515 static  gchar   *g_user_config_dir = NULL;
1516 static  gchar  **g_system_config_dirs = NULL;
1517
1518 #ifdef G_OS_WIN32
1519
1520 static gchar *
1521 get_special_folder (int csidl)
1522 {
1523   union {
1524     char c[MAX_PATH+1];
1525     wchar_t wc[MAX_PATH+1];
1526   } path;
1527   HRESULT hr;
1528   LPITEMIDLIST pidl = NULL;
1529   BOOL b;
1530   gchar *retval = NULL;
1531
1532   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1533   if (hr == S_OK)
1534     {
1535       if (G_WIN32_HAVE_WIDECHAR_API ())
1536         {
1537           b = SHGetPathFromIDListW (pidl, path.wc);
1538           if (b)
1539             retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
1540         }
1541       else
1542         {
1543           b = SHGetPathFromIDListA (pidl, path.c);
1544           if (b)
1545             retval = g_locale_to_utf8 (path.c, -1, NULL, NULL, NULL);
1546         }
1547       CoTaskMemFree (pidl);
1548     }
1549   return retval;
1550 }
1551
1552 static char *
1553 get_windows_directory_root (void)
1554 {
1555   char windowsdir[MAX_PATH];
1556
1557   if (GetWindowsDirectory (windowsdir, sizeof (windowsdir)))
1558     {
1559       /* Usually X:\Windows, but in terminal server environments
1560        * might be an UNC path, AFAIK.
1561        */
1562       char *p = (char *) g_path_skip_root (windowsdir);
1563       if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1564         p--;
1565       *p = '\0';
1566       return g_strdup (windowsdir);
1567     }
1568   else
1569     return g_strdup ("C:\\");
1570 }
1571
1572 #endif
1573
1574 /* HOLDS: g_utils_global_lock */
1575 static void
1576 g_get_any_init_do (void)
1577 {
1578   gchar hostname[100];
1579
1580   g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1581   if (!g_tmp_dir)
1582     g_tmp_dir = g_strdup (g_getenv ("TMP"));
1583   if (!g_tmp_dir)
1584     g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1585
1586 #ifdef G_OS_WIN32
1587   if (!g_tmp_dir)
1588     g_tmp_dir = get_windows_directory_root ();
1589 #else  
1590 #ifdef P_tmpdir
1591   if (!g_tmp_dir)
1592     {
1593       gsize k;    
1594       g_tmp_dir = g_strdup (P_tmpdir);
1595       k = strlen (g_tmp_dir);
1596       if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1597         g_tmp_dir[k - 1] = '\0';
1598     }
1599 #endif
1600   
1601   if (!g_tmp_dir)
1602     {
1603       g_tmp_dir = g_strdup ("/tmp");
1604     }
1605 #endif  /* !G_OS_WIN32 */
1606   
1607 #ifdef G_OS_WIN32
1608   /* We check $HOME first for Win32, though it is a last resort for Unix
1609    * where we prefer the results of getpwuid().
1610    */
1611   g_home_dir = g_strdup (g_getenv ("HOME"));
1612
1613   /* Only believe HOME if it is an absolute path and exists */
1614   if (g_home_dir)
1615     {
1616       if (!(g_path_is_absolute (g_home_dir) &&
1617             g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1618         {
1619           g_free (g_home_dir);
1620           g_home_dir = NULL;
1621         }
1622     }
1623   
1624   /* In case HOME is Unix-style (it happens), convert it to
1625    * Windows style.
1626    */
1627   if (g_home_dir)
1628     {
1629       gchar *p;
1630       while ((p = strchr (g_home_dir, '/')) != NULL)
1631         *p = '\\';
1632     }
1633
1634   if (!g_home_dir)
1635     {
1636       /* USERPROFILE is probably the closest equivalent to $HOME? */
1637       if (g_getenv ("USERPROFILE") != NULL)
1638         g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1639     }
1640
1641   if (!g_home_dir)
1642     g_home_dir = get_special_folder (CSIDL_PROFILE);
1643   
1644   if (!g_home_dir)
1645     g_home_dir = get_windows_directory_root ();
1646 #endif /* G_OS_WIN32 */
1647   
1648 #ifdef HAVE_PWD_H
1649   {
1650     struct passwd *pw = NULL;
1651     gpointer buffer = NULL;
1652     gint error;
1653     gchar *logname;
1654
1655 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1656     struct passwd pwd;
1657 #    ifdef _SC_GETPW_R_SIZE_MAX  
1658     /* This reurns the maximum length */
1659     glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1660     
1661     if (bufsize < 0)
1662       bufsize = 64;
1663 #    else /* _SC_GETPW_R_SIZE_MAX */
1664     glong bufsize = 64;
1665 #    endif /* _SC_GETPW_R_SIZE_MAX */
1666
1667     logname = (gchar *) g_getenv ("LOGNAME");
1668         
1669     do
1670       {
1671         g_free (buffer);
1672         /* we allocate 6 extra bytes to work around a bug in 
1673          * Mac OS < 10.3. See #156446
1674          */
1675         buffer = g_malloc (bufsize + 6);
1676         errno = 0;
1677         
1678 #    ifdef HAVE_POSIX_GETPWUID_R
1679         if (logname) {
1680           error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1681           if (!pw || (pw->pw_uid != getuid ())) {
1682             /* LOGNAME is lying, fall back to looking up the uid */
1683             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1684           }
1685         } else {
1686           error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1687         }
1688         error = error < 0 ? errno : error;
1689 #    else /* HAVE_NONPOSIX_GETPWUID_R */
1690    /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1691 #      if defined(_AIX) || defined(__hpux)
1692         error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1693         pw = error == 0 ? &pwd : NULL;
1694 #      else /* !_AIX */
1695         if (logname) {
1696           pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1697           if (!pw || (pw->pw_uid != getuid ())) {
1698             /* LOGNAME is lying, fall back to looking up the uid */
1699             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1700           }
1701         } else {
1702           pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1703         }
1704         error = pw ? 0 : errno;
1705 #      endif /* !_AIX */            
1706 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
1707         
1708         if (!pw)
1709           {
1710             /* we bail out prematurely if the user id can't be found
1711              * (should be pretty rare case actually), or if the buffer
1712              * should be sufficiently big and lookups are still not
1713              * successfull.
1714              */
1715             if (error == 0 || error == ENOENT)
1716               {
1717                 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1718                            (gulong) getuid ());
1719                 break;
1720               }
1721             if (bufsize > 32 * 1024)
1722               {
1723                 g_warning ("getpwuid_r(): failed due to: %s.",
1724                            g_strerror (error));
1725                 break;
1726               }
1727             
1728             bufsize *= 2;
1729           }
1730       }
1731     while (!pw);
1732 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1733     
1734     if (!pw)
1735       {
1736         setpwent ();
1737         pw = getpwuid (getuid ());
1738         endpwent ();
1739       }
1740     if (pw)
1741       {
1742         g_user_name = g_strdup (pw->pw_name);
1743
1744         if (pw->pw_gecos && *pw->pw_gecos != '\0') 
1745           {
1746             gchar **gecos_fields;
1747             gchar **name_parts;
1748
1749             /* split the gecos field and substitute '&' */
1750             gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1751             name_parts = g_strsplit (gecos_fields[0], "&", 0);
1752             pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1753             g_real_name = g_strjoinv (pw->pw_name, name_parts);
1754             g_strfreev (gecos_fields);
1755             g_strfreev (name_parts);
1756           }
1757
1758         if (!g_home_dir)
1759           g_home_dir = g_strdup (pw->pw_dir);
1760       }
1761     g_free (buffer);
1762   }
1763   
1764 #else /* !HAVE_PWD_H */
1765   
1766 #ifdef G_OS_WIN32
1767   if (G_WIN32_HAVE_WIDECHAR_API ())
1768     {
1769       guint len = UNLEN+1;
1770       wchar_t buffer[UNLEN+1];
1771       
1772       if (GetUserNameW (buffer, (LPDWORD) &len))
1773         {
1774           g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1775           g_real_name = g_strdup (g_user_name);
1776         }
1777     }
1778   else
1779     {
1780       guint len = UNLEN+1;
1781       char buffer[UNLEN+1];
1782       
1783       if (GetUserNameA (buffer, (LPDWORD) &len))
1784         {
1785           g_user_name = g_locale_to_utf8 (buffer, -1, NULL, NULL, NULL);
1786           g_real_name = g_strdup (g_user_name);
1787         }
1788     }
1789 #endif /* G_OS_WIN32 */
1790
1791 #endif /* !HAVE_PWD_H */
1792
1793 #ifndef G_OS_WIN32
1794   if (!g_home_dir)
1795     g_home_dir = g_strdup (g_getenv ("HOME"));
1796 #endif
1797
1798 #ifdef __EMX__
1799   /* change '\\' in %HOME% to '/' */
1800   g_strdelimit (g_home_dir, "\\",'/');
1801 #endif
1802   if (!g_user_name)
1803     g_user_name = g_strdup ("somebody");
1804   if (!g_real_name)
1805     g_real_name = g_strdup ("Unknown");
1806
1807   {
1808 #ifndef G_OS_WIN32
1809     gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1810 #else
1811     DWORD size = sizeof (hostname);
1812     gboolean hostname_fail = (!GetComputerName (hostname, &size));
1813 #endif
1814     g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1815   }
1816
1817 #ifdef G_OS_WIN32
1818   g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1819   g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1820   g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1821
1822   if (!g_tmp_dir_cp)
1823     g_tmp_dir_cp = g_strdup ("\\");
1824   if (!g_user_name_cp)
1825     g_user_name_cp = g_strdup ("somebody");
1826   if (!g_real_name_cp)
1827     g_real_name_cp = g_strdup ("Unknown");
1828
1829   /* home_dir might be NULL, unlike tmp_dir, user_name and
1830    * real_name.
1831    */
1832   if (g_home_dir)
1833     g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1834   else
1835     g_home_dir_cp = NULL;
1836 #endif /* G_OS_WIN32 */
1837 }
1838
1839 static inline void
1840 g_get_any_init (void)
1841 {
1842   if (!g_tmp_dir)
1843     g_get_any_init_do ();
1844 }
1845
1846 static inline void
1847 g_get_any_init_locked (void)
1848 {
1849   G_LOCK (g_utils_global);
1850   g_get_any_init ();
1851   G_UNLOCK (g_utils_global);
1852 }
1853
1854
1855 /**
1856  * g_get_user_name:
1857  *
1858  * Gets the user name of the current user. The encoding of the returned
1859  * string is system-defined. On UNIX, it might be the preferred file name
1860  * encoding, or something else, and there is no guarantee that it is even
1861  * consistent on a machine. On Windows, it is always UTF-8.
1862  *
1863  * Returns: the user name of the current user.
1864  */
1865 G_CONST_RETURN gchar*
1866 g_get_user_name (void)
1867 {
1868   g_get_any_init_locked ();
1869   return g_user_name;
1870 }
1871
1872 /**
1873  * g_get_real_name:
1874  *
1875  * Gets the real name of the user. This usually comes from the user's entry 
1876  * in the <filename>passwd</filename> file. The encoding of the returned 
1877  * string is system-defined. (On Windows, it is, however, always UTF-8.) 
1878  * If the real user name cannot be determined, the string "Unknown" is 
1879  * returned.
1880  *
1881  * Returns: the user's real name.
1882  */
1883 G_CONST_RETURN gchar*
1884 g_get_real_name (void)
1885 {
1886   g_get_any_init_locked ();
1887   return g_real_name;
1888 }
1889
1890 /**
1891  * g_get_home_dir:
1892  *
1893  * Gets the current user's home directory. 
1894  *
1895  * Note that in contrast to traditional UNIX tools, this function 
1896  * prefers <filename>passwd</filename> entries over the <envar>HOME</envar> 
1897  * environment variable.
1898  *
1899  * Returns: the current user's home directory.
1900  */
1901 G_CONST_RETURN gchar*
1902 g_get_home_dir (void)
1903 {
1904   g_get_any_init_locked ();
1905   return g_home_dir;
1906 }
1907
1908 /**
1909  * g_get_tmp_dir:
1910  *
1911  * Gets the directory to use for temporary files. This is found from 
1912  * inspecting the environment variables <envar>TMPDIR</envar>, 
1913  * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none 
1914  * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows. 
1915  * The encoding of the returned string is system-defined. On Windows, 
1916  * it is always UTF-8. The return value is never %NULL.
1917  *
1918  * Returns: the directory to use for temporary files.
1919  */
1920 G_CONST_RETURN gchar*
1921 g_get_tmp_dir (void)
1922 {
1923   g_get_any_init_locked ();
1924   return g_tmp_dir;
1925 }
1926
1927 /**
1928  * g_get_host_name:
1929  *
1930  * Return a name for the machine. 
1931  *
1932  * The returned name is not necessarily a fully-qualified domain name,
1933  * or even present in DNS or some other name service at all. It need
1934  * not even be unique on your local network or site, but usually it
1935  * is. Callers should not rely on the return value having any specific
1936  * properties like uniqueness for security purposes. Even if the name
1937  * of the machine is changed while an application is running, the
1938  * return value from this function does not change. The returned
1939  * string is owned by GLib and should not be modified or freed. If no
1940  * name can be determined, a default fixed string "localhost" is
1941  * returned.
1942  *
1943  * Returns: the host name of the machine.
1944  *
1945  * Since: 2.8
1946  */
1947 const gchar *
1948 g_get_host_name (void)
1949 {
1950   g_get_any_init_locked ();
1951   return g_host_name;
1952 }
1953
1954 G_LOCK_DEFINE_STATIC (g_prgname);
1955 static gchar *g_prgname = NULL;
1956
1957 /**
1958  * g_get_prgname:
1959  *
1960  * Gets the name of the program. This name should <emphasis>not</emphasis> 
1961  * be localized, contrast with g_get_application_name().
1962  * (If you are using GDK or GTK+ the program name is set in gdk_init(), 
1963  * which is called by gtk_init(). The program name is found by taking 
1964  * the last component of <literal>argv[0]</literal>.)
1965  *
1966  * Returns: the name of the program. The returned string belongs 
1967  * to GLib and must not be modified or freed.
1968  */
1969 gchar*
1970 g_get_prgname (void)
1971 {
1972   gchar* retval;
1973
1974   G_LOCK (g_prgname);
1975 #ifdef G_OS_WIN32
1976   if (g_prgname == NULL)
1977     {
1978       static gboolean beenhere = FALSE;
1979
1980       if (!beenhere)
1981         {
1982           gchar *utf8_buf = NULL;
1983
1984           beenhere = TRUE;
1985           if (G_WIN32_HAVE_WIDECHAR_API ())
1986             {
1987               wchar_t buf[MAX_PATH+1];
1988               if (GetModuleFileNameW (GetModuleHandle (NULL),
1989                                       buf, G_N_ELEMENTS (buf)) > 0)
1990                 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1991             }
1992           else
1993             {
1994               gchar buf[MAX_PATH+1];
1995               if (GetModuleFileNameA (GetModuleHandle (NULL),
1996                                       buf, G_N_ELEMENTS (buf)) > 0)
1997                 utf8_buf = g_locale_to_utf8 (buf, -1, NULL, NULL, NULL);
1998             }
1999           if (utf8_buf)
2000             {
2001               g_prgname = g_path_get_basename (utf8_buf);
2002               g_free (utf8_buf);
2003             }
2004         }
2005     }
2006 #endif
2007   retval = g_prgname;
2008   G_UNLOCK (g_prgname);
2009
2010   return retval;
2011 }
2012
2013 /**
2014  * g_set_prgname:
2015  * @prgname: the name of the program.
2016  *
2017  * Sets the name of the program. This name should <emphasis>not</emphasis> 
2018  * be localized, contrast with g_set_application_name(). Note that for 
2019  * thread-safety reasons this function can only be called once.
2020  */
2021 void
2022 g_set_prgname (const gchar *prgname)
2023 {
2024   G_LOCK (g_prgname);
2025   g_free (g_prgname);
2026   g_prgname = g_strdup (prgname);
2027   G_UNLOCK (g_prgname);
2028 }
2029
2030 G_LOCK_DEFINE_STATIC (g_application_name);
2031 static gchar *g_application_name = NULL;
2032
2033 /**
2034  * g_get_application_name:
2035  * 
2036  * Gets a human-readable name for the application, as set by
2037  * g_set_application_name(). This name should be localized if
2038  * possible, and is intended for display to the user.  Contrast with
2039  * g_get_prgname(), which gets a non-localized name. If
2040  * g_set_application_name() has not been called, returns the result of
2041  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2042  * been called).
2043  * 
2044  * Return value: human-readable application name. may return %NULL
2045  *
2046  * Since: 2.2
2047  **/
2048 G_CONST_RETURN gchar*
2049 g_get_application_name (void)
2050 {
2051   gchar* retval;
2052
2053   G_LOCK (g_application_name);
2054   retval = g_application_name;
2055   G_UNLOCK (g_application_name);
2056
2057   if (retval == NULL)
2058     return g_get_prgname ();
2059   
2060   return retval;
2061 }
2062
2063 /**
2064  * g_set_application_name:
2065  * @application_name: localized name of the application
2066  *
2067  * Sets a human-readable name for the application. This name should be
2068  * localized if possible, and is intended for display to the user.
2069  * Contrast with g_set_prgname(), which sets a non-localized name.
2070  * g_set_prgname() will be called automatically by gtk_init(),
2071  * but g_set_application_name() will not.
2072  *
2073  * Note that for thread safety reasons, this function can only
2074  * be called once.
2075  *
2076  * The application name will be used in contexts such as error messages,
2077  * or when displaying an application's name in the task list.
2078  * 
2079  **/
2080 void
2081 g_set_application_name (const gchar *application_name)
2082 {
2083   gboolean already_set = FALSE;
2084         
2085   G_LOCK (g_application_name);
2086   if (g_application_name)
2087     already_set = TRUE;
2088   else
2089     g_application_name = g_strdup (application_name);
2090   G_UNLOCK (g_application_name);
2091
2092   if (already_set)
2093     g_warning ("g_set_application() name called multiple times");
2094 }
2095
2096 /**
2097  * g_get_user_data_dir:
2098  * 
2099  * Returns a base directory in which to access application data such
2100  * as icons that is customized for a particular user.  
2101  *
2102  * On UNIX platforms this is determined using the mechanisms described in
2103  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2104  * XDG Base Directory Specification</ulink>
2105  * 
2106  * Return value: a string owned by GLib that must not be modified 
2107  *               or freed.
2108  * Since: 2.6
2109  **/
2110 G_CONST_RETURN gchar*
2111 g_get_user_data_dir (void)
2112 {
2113   gchar *data_dir;  
2114
2115   G_LOCK (g_utils_global);
2116
2117   if (!g_user_data_dir)
2118     {
2119 #ifdef G_OS_WIN32
2120       data_dir = get_special_folder (CSIDL_PERSONAL);
2121 #else
2122       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2123
2124       if (data_dir && data_dir[0])
2125         data_dir = g_strdup (data_dir);
2126 #endif
2127       if (!data_dir || !data_dir[0])
2128         {
2129           g_get_any_init ();
2130
2131           if (g_home_dir)
2132             data_dir = g_build_filename (g_home_dir, ".local", 
2133                                          "share", NULL);
2134           else
2135             data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local", 
2136                                          "share", NULL);
2137         }
2138
2139       g_user_data_dir = data_dir;
2140     }
2141   else
2142     data_dir = g_user_data_dir;
2143
2144   G_UNLOCK (g_utils_global);
2145
2146   return data_dir;
2147 }
2148
2149 /**
2150  * g_get_user_config_dir:
2151  * 
2152  * Returns a base directory in which to store user-specific application 
2153  * configuration information such as user preferences and settings. 
2154  *
2155  * On UNIX platforms this is determined using the mechanisms described in
2156  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2157  * XDG Base Directory Specification</ulink>
2158  * 
2159  * Return value: a string owned by GLib that must not be modified 
2160  *               or freed.
2161  * Since: 2.6
2162  **/
2163 G_CONST_RETURN gchar*
2164 g_get_user_config_dir (void)
2165 {
2166   gchar *config_dir;  
2167
2168   G_LOCK (g_utils_global);
2169
2170   if (!g_user_config_dir)
2171     {
2172 #ifdef G_OS_WIN32
2173       config_dir = get_special_folder (CSIDL_APPDATA);
2174 #else
2175       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2176
2177       if (config_dir && config_dir[0])
2178         config_dir = g_strdup (config_dir);
2179 #endif
2180       if (!config_dir || !config_dir[0])
2181         {
2182           g_get_any_init ();
2183
2184           if (g_home_dir)
2185             config_dir = g_build_filename (g_home_dir, ".config", NULL);
2186           else
2187             config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2188         }
2189       g_user_config_dir = config_dir;
2190     }
2191   else
2192     config_dir = g_user_config_dir;
2193
2194   G_UNLOCK (g_utils_global);
2195
2196   return config_dir;
2197 }
2198
2199 /**
2200  * g_get_user_cache_dir:
2201  * 
2202  * Returns a base directory in which to store non-essential, cached
2203  * data specific to particular user.
2204  *
2205  * On UNIX platforms this is determined using the mechanisms described in
2206  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2207  * XDG Base Directory Specification</ulink>
2208  * 
2209  * Return value: a string owned by GLib that must not be modified 
2210  *               or freed.
2211  * Since: 2.6
2212  **/
2213 G_CONST_RETURN gchar*
2214 g_get_user_cache_dir (void)
2215 {
2216   gchar *cache_dir;  
2217
2218   G_LOCK (g_utils_global);
2219
2220   if (!g_user_cache_dir)
2221     {
2222 #ifdef G_OS_WIN32
2223       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2224 #else
2225       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2226
2227       if (cache_dir && cache_dir[0])
2228           cache_dir = g_strdup (cache_dir);
2229 #endif
2230       if (!cache_dir || !cache_dir[0])
2231         {
2232           g_get_any_init ();
2233         
2234           if (g_home_dir)
2235             cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2236           else
2237             cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2238         }
2239       g_user_cache_dir = cache_dir;
2240     }
2241   else
2242     cache_dir = g_user_cache_dir;
2243
2244   G_UNLOCK (g_utils_global);
2245
2246   return cache_dir;
2247 }
2248
2249 #ifdef G_OS_WIN32
2250
2251 #undef g_get_system_data_dirs
2252
2253 static HMODULE
2254 get_module_for_address (gconstpointer address)
2255 {
2256   /* Holds the g_utils_global lock */
2257
2258   static gboolean beenhere = FALSE;
2259   typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2260   static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2261   HMODULE hmodule;
2262
2263   if (!address)
2264     return NULL;
2265
2266   if (!beenhere)
2267     {
2268       p_GetModuleHandleExA =
2269         (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2270                                                "GetModuleHandleExA");
2271       beenhere = TRUE;
2272     }
2273
2274   if (p_GetModuleHandleExA == NULL ||
2275       !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2276                                 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2277                                 address, &hmodule))
2278     {
2279       MEMORY_BASIC_INFORMATION mbi;
2280       VirtualQuery (address, &mbi, sizeof (mbi));
2281       hmodule = (HMODULE) mbi.AllocationBase;
2282     }
2283
2284   return hmodule;
2285 }
2286
2287 static gchar *
2288 get_module_share_dir (gconstpointer address)
2289 {
2290   HMODULE hmodule;
2291   gchar *filename = NULL;
2292   gchar *p, *retval;
2293
2294   hmodule = get_module_for_address (address);
2295   if (hmodule == NULL)
2296     return NULL;
2297
2298   if (G_WIN32_IS_NT_BASED ())
2299     {
2300       wchar_t wfilename[MAX_PATH];
2301       if (GetModuleFileNameW (hmodule, wfilename, G_N_ELEMENTS (wfilename)))
2302         filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
2303     }
2304   else
2305     {
2306       char cpfilename[MAX_PATH];
2307       if (GetModuleFileNameA (hmodule, cpfilename, G_N_ELEMENTS (cpfilename)))
2308         filename = g_locale_to_utf8 (cpfilename, -1, NULL, NULL, NULL);
2309     }
2310
2311   if (filename == NULL)
2312     return NULL;
2313
2314   if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
2315     *p = '\0';
2316
2317   p = strrchr (filename, G_DIR_SEPARATOR);
2318   if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
2319     *p = '\0';
2320
2321   retval = g_build_filename (filename, "share", NULL);
2322   g_free (filename);
2323
2324   return retval;
2325 }
2326
2327 G_CONST_RETURN gchar * G_CONST_RETURN *
2328 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2329 {
2330   GArray *data_dirs;
2331   HMODULE hmodule;
2332   static GHashTable *per_module_data_dirs = NULL;
2333   gchar **retval;
2334   gchar *p;
2335       
2336   if (address)
2337     {
2338       G_LOCK (g_utils_global);
2339       hmodule = get_module_for_address (address);
2340       if (hmodule != NULL)
2341         {
2342           if (per_module_data_dirs == NULL)
2343             per_module_data_dirs = g_hash_table_new (NULL, NULL);
2344           else
2345             {
2346               retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2347               
2348               if (retval != NULL)
2349                 {
2350                   G_UNLOCK (g_utils_global);
2351                   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2352                 }
2353             }
2354         }
2355     }
2356
2357   data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2358
2359   /* Documents and Settings\All Users\Application Data */
2360   p = get_special_folder (CSIDL_COMMON_APPDATA);
2361   if (p)
2362     g_array_append_val (data_dirs, p);
2363   
2364   /* Documents and Settings\All Users\Documents */
2365   p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2366   if (p)
2367     g_array_append_val (data_dirs, p);
2368         
2369   /* Using the above subfolders of Documents and Settings perhaps
2370    * makes sense from a Windows perspective.
2371    *
2372    * But looking at the actual use cases of this function in GTK+
2373    * and GNOME software, what we really want is the "share"
2374    * subdirectory of the installation directory for the package
2375    * our caller is a part of.
2376    *
2377    * The address parameter, if non-NULL, points to a function in the
2378    * calling module. Use that to determine that module's installation
2379    * folder, and use its "share" subfolder.
2380    *
2381    * Additionally, also use the "share" subfolder of the installation
2382    * locations of GLib and the .exe file being run.
2383    *
2384    * To guard against none of the above being what is really wanted,
2385    * callers of this function should have Win32-specific code to look
2386    * up their installation folder themselves, and handle a subfolder
2387    * "share" of it in the same way as the folders returned from this
2388    * function.
2389    */
2390
2391   p = get_module_share_dir (address);
2392   if (p)
2393     g_array_append_val (data_dirs, p);
2394     
2395   p = g_win32_get_package_installation_subdirectory (NULL, dll_name, "share");
2396   if (p)
2397     g_array_append_val (data_dirs, p);
2398   
2399   p = g_win32_get_package_installation_subdirectory (NULL, NULL, "share");
2400   if (p)
2401     g_array_append_val (data_dirs, p);
2402
2403   retval = (gchar **) g_array_free (data_dirs, FALSE);
2404
2405   if (address)
2406     {
2407       if (hmodule != NULL)
2408         g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2409       G_UNLOCK (g_utils_global);
2410     }
2411
2412   return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2413 }
2414
2415 #endif
2416
2417 /**
2418  * g_get_system_data_dirs:
2419  * 
2420  * Returns an ordered list of base directories in which to access 
2421  * system-wide application data.
2422  *
2423  * On UNIX platforms this is determined using the mechanisms described in
2424  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2425  * XDG Base Directory Specification</ulink>
2426  * 
2427  * On Windows the first elements in the list are the Application Data
2428  * and Documents folders for All Users. (These can be determined only
2429  * on Windows 2000 or later and are not present in the list on other
2430  * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2431  * CSIDL_COMMON_DOCUMENTS.
2432  *
2433  * Then follows the "share" subfolder in the installation folder for
2434  * the package containing the DLL that calls this function, if it can
2435  * be determined.
2436  * 
2437  * Finally the list contains the "share" subfolder in the installation
2438  * folder for GLib, and in the installation folder for the package the
2439  * application's .exe file belongs to.
2440  *
2441  * The installation folders above are determined by looking up the
2442  * folder where the module (DLL or EXE) in question is located. If the
2443  * folder's name is "bin", its parent is used, otherwise the folder
2444  * itself.
2445  *
2446  * Note that on Windows the returned list can vary depending on where
2447  * this function is called.
2448  *
2449  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2450  *               not be modified or freed.
2451  * Since: 2.6
2452  **/
2453 G_CONST_RETURN gchar * G_CONST_RETURN * 
2454 g_get_system_data_dirs (void)
2455 {
2456   gchar **data_dir_vector;
2457
2458   G_LOCK (g_utils_global);
2459
2460   if (!g_system_data_dirs)
2461     {
2462 #ifdef G_OS_WIN32
2463       data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2464 #else
2465       gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2466
2467       if (!data_dirs || !data_dirs[0])
2468           data_dirs = "/usr/local/share/:/usr/share/";
2469
2470       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2471 #endif
2472
2473       g_system_data_dirs = data_dir_vector;
2474     }
2475   else
2476     data_dir_vector = g_system_data_dirs;
2477
2478   G_UNLOCK (g_utils_global);
2479
2480   return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2481 }
2482
2483 /**
2484  * g_get_system_config_dirs:
2485  * 
2486  * Returns an ordered list of base directories in which to access 
2487  * system-wide configuration information.
2488  *
2489  * On UNIX platforms this is determined using the mechanisms described in
2490  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2491  * XDG Base Directory Specification</ulink>
2492  * 
2493  * Return value: a %NULL-terminated array of strings owned by GLib that must 
2494  *               not be modified or freed.
2495  * Since: 2.6
2496  **/
2497 G_CONST_RETURN gchar * G_CONST_RETURN *
2498 g_get_system_config_dirs (void)
2499 {
2500   gchar *conf_dirs, **conf_dir_vector;
2501
2502   G_LOCK (g_utils_global);
2503
2504   if (!g_system_config_dirs)
2505     {
2506 #ifdef G_OS_WIN32
2507       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2508       if (conf_dirs)
2509         {
2510           conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2511           g_free (conf_dirs);
2512         }
2513       else
2514         {
2515           /* Return empty list */
2516           conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2517         }
2518 #else
2519       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2520
2521       if (!conf_dirs || !conf_dirs[0])
2522           conf_dirs = "/etc/xdg";
2523
2524       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2525 #endif
2526
2527       g_system_config_dirs = conf_dir_vector;
2528     }
2529   else
2530     conf_dir_vector = g_system_config_dirs;
2531   G_UNLOCK (g_utils_global);
2532
2533   return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2534 }
2535
2536 #ifndef G_OS_WIN32
2537
2538 static GHashTable *alias_table = NULL;
2539
2540 /* read an alias file for the locales */
2541 static void
2542 read_aliases (gchar *file)
2543 {
2544   FILE *fp;
2545   char buf[256];
2546   
2547   if (!alias_table)
2548     alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2549   fp = fopen (file,"r");
2550   if (!fp)
2551     return;
2552   while (fgets (buf, 256, fp))
2553     {
2554       char *p, *q;
2555
2556       g_strstrip (buf);
2557
2558       /* Line is a comment */
2559       if ((buf[0] == '#') || (buf[0] == '\0'))
2560         continue;
2561
2562       /* Reads first column */
2563       for (p = buf, q = NULL; *p; p++) {
2564         if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2565           *p = '\0';
2566           q = p+1;
2567           while ((*q == '\t') || (*q == ' ')) {
2568             q++;
2569           }
2570           break;
2571         }
2572       }
2573       /* The line only had one column */
2574       if (!q || *q == '\0')
2575         continue;
2576       
2577       /* Read second column */
2578       for (p = q; *p; p++) {
2579         if ((*p == '\t') || (*p == ' ')) {
2580           *p = '\0';
2581           break;
2582         }
2583       }
2584
2585       /* Add to alias table if necessary */
2586       if (!g_hash_table_lookup (alias_table, buf)) {
2587         g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2588       }
2589     }
2590   fclose (fp);
2591 }
2592
2593 #endif
2594
2595 static char *
2596 unalias_lang (char *lang)
2597 {
2598 #ifndef G_OS_WIN32
2599   char *p;
2600   int i;
2601
2602   if (!alias_table)
2603     read_aliases ("/usr/share/locale/locale.alias");
2604
2605   i = 0;
2606   while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2607     {
2608       lang = p;
2609       if (i++ == 30)
2610         {
2611           static gboolean said_before = FALSE;
2612           if (!said_before)
2613             g_warning ("Too many alias levels for a locale, "
2614                        "may indicate a loop");
2615           said_before = TRUE;
2616           return lang;
2617         }
2618     }
2619 #endif
2620   return lang;
2621 }
2622
2623 /* Mask for components of locale spec. The ordering here is from
2624  * least significant to most significant
2625  */
2626 enum
2627 {
2628   COMPONENT_CODESET =   1 << 0,
2629   COMPONENT_TERRITORY = 1 << 1,
2630   COMPONENT_MODIFIER =  1 << 2
2631 };
2632
2633 /* Break an X/Open style locale specification into components
2634  */
2635 static guint
2636 explode_locale (const gchar *locale,
2637                 gchar      **language, 
2638                 gchar      **territory, 
2639                 gchar      **codeset, 
2640                 gchar      **modifier)
2641 {
2642   const gchar *uscore_pos;
2643   const gchar *at_pos;
2644   const gchar *dot_pos;
2645
2646   guint mask = 0;
2647
2648   uscore_pos = strchr (locale, '_');
2649   dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2650   at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2651
2652   if (at_pos)
2653     {
2654       mask |= COMPONENT_MODIFIER;
2655       *modifier = g_strdup (at_pos);
2656     }
2657   else
2658     at_pos = locale + strlen (locale);
2659
2660   if (dot_pos)
2661     {
2662       mask |= COMPONENT_CODESET;
2663       *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2664     }
2665   else
2666     dot_pos = at_pos;
2667
2668   if (uscore_pos)
2669     {
2670       mask |= COMPONENT_TERRITORY;
2671       *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2672     }
2673   else
2674     uscore_pos = dot_pos;
2675
2676   *language = g_strndup (locale, uscore_pos - locale);
2677
2678   return mask;
2679 }
2680
2681 /*
2682  * Compute all interesting variants for a given locale name -
2683  * by stripping off different components of the value.
2684  *
2685  * For simplicity, we assume that the locale is in
2686  * X/Open format: language[_territory][.codeset][@modifier]
2687  *
2688  * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2689  *       as well. We could just copy the code from glibc wholesale
2690  *       but it is big, ugly, and complicated, so I'm reluctant
2691  *       to do so when this should handle 99% of the time...
2692  */
2693 GSList *
2694 _g_compute_locale_variants (const gchar *locale)
2695 {
2696   GSList *retval = NULL;
2697
2698   gchar *language = NULL;
2699   gchar *territory = NULL;
2700   gchar *codeset = NULL;
2701   gchar *modifier = NULL;
2702
2703   guint mask;
2704   guint i;
2705
2706   g_return_val_if_fail (locale != NULL, NULL);
2707
2708   mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2709
2710   /* Iterate through all possible combinations, from least attractive
2711    * to most attractive.
2712    */
2713   for (i = 0; i <= mask; i++)
2714     if ((i & ~mask) == 0)
2715       {
2716         gchar *val = g_strconcat (language,
2717                                   (i & COMPONENT_TERRITORY) ? territory : "",
2718                                   (i & COMPONENT_CODESET) ? codeset : "",
2719                                   (i & COMPONENT_MODIFIER) ? modifier : "",
2720                                   NULL);
2721         retval = g_slist_prepend (retval, val);
2722       }
2723
2724   g_free (language);
2725   if (mask & COMPONENT_CODESET)
2726     g_free (codeset);
2727   if (mask & COMPONENT_TERRITORY)
2728     g_free (territory);
2729   if (mask & COMPONENT_MODIFIER)
2730     g_free (modifier);
2731
2732   return retval;
2733 }
2734
2735 /* The following is (partly) taken from the gettext package.
2736    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
2737
2738 static const gchar *
2739 guess_category_value (const gchar *category_name)
2740 {
2741   const gchar *retval;
2742
2743   /* The highest priority value is the `LANGUAGE' environment
2744      variable.  This is a GNU extension.  */
2745   retval = g_getenv ("LANGUAGE");
2746   if ((retval != NULL) && (retval[0] != '\0'))
2747     return retval;
2748
2749   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
2750      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
2751      systems this can be done by the `setlocale' function itself.  */
2752
2753   /* Setting of LC_ALL overwrites all other.  */
2754   retval = g_getenv ("LC_ALL");  
2755   if ((retval != NULL) && (retval[0] != '\0'))
2756     return retval;
2757
2758   /* Next comes the name of the desired category.  */
2759   retval = g_getenv (category_name);
2760   if ((retval != NULL) && (retval[0] != '\0'))
2761     return retval;
2762
2763   /* Last possibility is the LANG environment variable.  */
2764   retval = g_getenv ("LANG");
2765   if ((retval != NULL) && (retval[0] != '\0'))
2766     return retval;
2767
2768 #ifdef G_PLATFORM_WIN32
2769   /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2770    * LANG, which we already did above. Oh well. The main point of
2771    * calling g_win32_getlocale() is to get the thread's locale as used
2772    * by Windows and the Microsoft C runtime (in the "English_United
2773    * States" format) translated into the Unixish format.
2774    */
2775   retval = g_win32_getlocale ();
2776   if ((retval != NULL) && (retval[0] != '\0'))
2777     return retval;
2778 #endif  
2779
2780   return NULL;
2781 }
2782
2783 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2784
2785 struct _GLanguageNamesCache {
2786   gchar *languages;
2787   gchar **language_names;
2788 };
2789
2790 static void
2791 language_names_cache_free (gpointer data)
2792 {
2793   GLanguageNamesCache *cache = data;
2794   g_free (cache->languages);
2795   g_strfreev (cache->language_names);
2796   g_free (cache);
2797 }
2798
2799 /**
2800  * g_get_language_names:
2801  * 
2802  * Computes a list of applicable locale names, which can be used to 
2803  * e.g. construct locale-dependent filenames or search paths. The returned 
2804  * list is sorted from most desirable to least desirable and always contains 
2805  * the default locale "C".
2806  *
2807  * For example, if LANGUAGE=de:en_US, then the returned list is
2808  * "de", "en_US", "en", "C".
2809  *
2810  * This function consults the environment variables <envar>LANGUAGE</envar>, 
2811  * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar> 
2812  * to find the list of locales specified by the user.
2813  * 
2814  * Return value: a %NULL-terminated array of strings owned by GLib 
2815  *    that must not be modified or freed.
2816  *
2817  * Since: 2.6
2818  **/
2819 G_CONST_RETURN gchar * G_CONST_RETURN * 
2820 g_get_language_names (void)
2821 {
2822   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2823   GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2824   const gchar *value;
2825
2826   if (!cache)
2827     {
2828       cache = g_new0 (GLanguageNamesCache, 1);
2829       g_static_private_set (&cache_private, cache, language_names_cache_free);
2830     }
2831
2832   value = guess_category_value ("LC_MESSAGES");
2833   if (!value)
2834     value = "C";
2835
2836   if (!(cache->languages && strcmp (cache->languages, value) == 0))
2837     {
2838       gchar **languages;
2839       gchar **alist, **a;
2840       GSList *list, *l;
2841       gint i;
2842
2843       g_free (cache->languages);
2844       g_strfreev (cache->language_names);
2845       cache->languages = g_strdup (value);
2846
2847       alist = g_strsplit (value, ":", 0);
2848       list = NULL;
2849       for (a = alist; *a; a++)
2850         {
2851           gchar *b = unalias_lang (*a);
2852           list = g_slist_concat (list, _g_compute_locale_variants (b));
2853         }
2854       g_strfreev (alist);
2855       list = g_slist_append (list, g_strdup ("C"));
2856
2857       cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
2858       for (l = list, i = 0; l; l = l->next, i++)
2859         languages[i] = l->data;
2860       languages[i] = NULL;
2861
2862       g_slist_free (list);
2863     }
2864
2865   return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
2866 }
2867
2868 /**
2869  * g_direct_hash:
2870  * @v: a #gpointer key
2871  *
2872  * Converts a gpointer to a hash value.
2873  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
2874  * when using pointers as keys in a #GHashTable.
2875  *
2876  * Returns: a hash value corresponding to the key.
2877  */
2878 guint
2879 g_direct_hash (gconstpointer v)
2880 {
2881   return GPOINTER_TO_UINT (v);
2882 }
2883
2884 /**
2885  * g_direct_equal:
2886  * @v1: a key.
2887  * @v2: a key to compare with @v1.
2888  *
2889  * Compares two #gpointer arguments and returns %TRUE if they are equal.
2890  * It can be passed to g_hash_table_new() as the @key_equal_func
2891  * parameter, when using pointers as keys in a #GHashTable.
2892  * 
2893  * Returns: %TRUE if the two keys match.
2894  */
2895 gboolean
2896 g_direct_equal (gconstpointer v1,
2897                 gconstpointer v2)
2898 {
2899   return v1 == v2;
2900 }
2901
2902 /**
2903  * g_int_equal:
2904  * @v1: a pointer to a #gint key.
2905  * @v2: a pointer to a #gint key to compare with @v1.
2906  *
2907  * Compares the two #gint values being pointed to and returns 
2908  * %TRUE if they are equal.
2909  * It can be passed to g_hash_table_new() as the @key_equal_func
2910  * parameter, when using pointers to integers as keys in a #GHashTable.
2911  * 
2912  * Returns: %TRUE if the two keys match.
2913  */
2914 gboolean
2915 g_int_equal (gconstpointer v1,
2916              gconstpointer v2)
2917 {
2918   return *((const gint*) v1) == *((const gint*) v2);
2919 }
2920
2921 /**
2922  * g_int_hash:
2923  * @v: a pointer to a #gint key
2924  *
2925  * Converts a pointer to a #gint to a hash value.
2926  * It can be passed to g_hash_table_new() as the @hash_func parameter, 
2927  * when using pointers to integers values as keys in a #GHashTable.
2928  *
2929  * Returns: a hash value corresponding to the key.
2930  */
2931 guint
2932 g_int_hash (gconstpointer v)
2933 {
2934   return *(const gint*) v;
2935 }
2936
2937 /**
2938  * g_nullify_pointer:
2939  * @nullify_location: the memory address of the pointer.
2940  * 
2941  * Set the pointer at the specified location to %NULL.
2942  **/
2943 void
2944 g_nullify_pointer (gpointer *nullify_location)
2945 {
2946   g_return_if_fail (nullify_location != NULL);
2947
2948   *nullify_location = NULL;
2949 }
2950
2951 /**
2952  * g_get_codeset:
2953  * 
2954  * Get the codeset for the current locale.
2955  * 
2956  * Return value: a newly allocated string containing the name
2957  * of the codeset. This string must be freed with g_free().
2958  **/
2959 gchar *
2960 g_get_codeset (void)
2961 {
2962   const gchar *charset;
2963
2964   g_get_charset (&charset);
2965
2966   return g_strdup (charset);
2967 }
2968
2969 /* This is called from g_thread_init(). It's used to
2970  * initialize some static data in a threadsafe way.
2971  */
2972 void
2973 _g_utils_thread_init (void)
2974 {
2975   g_get_language_names ();
2976 }
2977
2978 #ifdef ENABLE_NLS
2979
2980 #include <libintl.h>
2981
2982 #ifdef G_OS_WIN32
2983
2984 /**
2985  * _glib_get_locale_dir:
2986  *
2987  * Return the path to the lib\locale subfolder of the GLib
2988  * installation folder. The path is in the system codepage. We have to
2989  * use system codepage as bindtextdomain() doesn't have a UTF-8
2990  * interface.
2991  */
2992 static const gchar *
2993 _glib_get_locale_dir (void)
2994 {
2995   gchar *dir, *cp_dir;
2996   gchar *retval = NULL;
2997
2998   dir = g_win32_get_package_installation_directory (GETTEXT_PACKAGE, dll_name);
2999   cp_dir = g_win32_locale_filename_from_utf8 (dir);
3000   g_free (dir);
3001
3002   if (cp_dir)
3003     {
3004       /* Don't use g_build_filename() on pathnames in the system
3005        * codepage. In CJK locales cp_dir might end with a double-byte
3006        * character whose trailing byte is a backslash.
3007        */
3008       retval = g_strconcat (cp_dir, "\\lib\\locale", NULL);
3009       g_free (cp_dir);
3010     }
3011
3012   if (retval)
3013     return retval;
3014   else
3015     return g_strdup ("");
3016 }
3017
3018 #undef GLIB_LOCALE_DIR
3019 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
3020
3021 #endif /* G_OS_WIN32 */
3022
3023 G_CONST_RETURN gchar *
3024 _glib_gettext (const gchar *str)
3025 {
3026   static gboolean _glib_gettext_initialized = FALSE;
3027
3028   if (!_glib_gettext_initialized)
3029     {
3030       bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3031 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3032       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3033 #    endif
3034       _glib_gettext_initialized = TRUE;
3035     }
3036   
3037   return dgettext (GETTEXT_PACKAGE, str);
3038 }
3039
3040 #endif /* ENABLE_NLS */
3041
3042 #ifdef G_OS_WIN32
3043
3044 /* Binary compatibility versions. Not for newly compiled code. */
3045
3046 #undef g_find_program_in_path
3047
3048 gchar*
3049 g_find_program_in_path (const gchar *program)
3050 {
3051   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3052   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3053   gchar *retval;
3054
3055   g_free (utf8_program);
3056   if (utf8_retval == NULL)
3057     return NULL;
3058   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3059   g_free (utf8_retval);
3060
3061   return retval;
3062 }
3063
3064 #undef g_get_current_dir
3065
3066 gchar*
3067 g_get_current_dir (void)
3068 {
3069   gchar *utf8_dir = g_get_current_dir_utf8 ();
3070   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3071   g_free (utf8_dir);
3072   return dir;
3073 }
3074
3075 #undef g_getenv
3076
3077 G_CONST_RETURN gchar*
3078 g_getenv (const gchar *variable)
3079 {
3080   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3081   const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3082   gchar *value;
3083   GQuark quark;
3084
3085   g_free (utf8_variable);
3086   if (!utf8_value)
3087     return NULL;
3088   value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3089   quark = g_quark_from_string (value);
3090   g_free (value);
3091
3092   return g_quark_to_string (quark);
3093 }
3094
3095 #undef g_setenv
3096
3097 gboolean
3098 g_setenv (const gchar *variable, 
3099           const gchar *value, 
3100           gboolean     overwrite)
3101 {
3102   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3103   gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3104   gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3105
3106   g_free (utf8_variable);
3107   g_free (utf8_value);
3108
3109   return retval;
3110 }
3111
3112 #undef g_unsetenv
3113
3114 void
3115 g_unsetenv (const gchar *variable)
3116 {
3117   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3118
3119   g_unsetenv_utf8 (utf8_variable);
3120
3121   g_free (utf8_variable);
3122 }
3123
3124 #undef g_get_user_name
3125
3126 G_CONST_RETURN gchar*
3127 g_get_user_name (void)
3128 {
3129   g_get_any_init_locked ();
3130   return g_user_name_cp;
3131 }
3132
3133 #undef g_get_real_name
3134
3135 G_CONST_RETURN gchar*
3136 g_get_real_name (void)
3137 {
3138   g_get_any_init_locked ();
3139   return g_real_name_cp;
3140 }
3141
3142 #undef g_get_home_dir
3143
3144 G_CONST_RETURN gchar*
3145 g_get_home_dir (void)
3146 {
3147   g_get_any_init_locked ();
3148   return g_home_dir_cp;
3149 }
3150
3151 #undef g_get_tmp_dir
3152
3153 G_CONST_RETURN gchar*
3154 g_get_tmp_dir (void)
3155 {
3156   g_get_any_init_locked ();
3157   return g_tmp_dir_cp;
3158 }
3159
3160 #endif
3161
3162 #define __G_UTILS_C__
3163 #include "galiasdef.c"