glib/glib.symbols glib/gutils.h Make also g_getenv(), g_setenv(),
[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
50 /* implement gutils's inline functions
51  */
52 #define G_IMPLEMENT_INLINES 1
53 #define __G_UTILS_C__
54 #include "galias.h"
55 #include "glib.h"
56 #include "gprintfint.h"
57 #include "gthreadinit.h"
58
59 #ifdef  MAXPATHLEN
60 #define G_PATH_LENGTH   MAXPATHLEN
61 #elif   defined (PATH_MAX)
62 #define G_PATH_LENGTH   PATH_MAX
63 #elif   defined (_PC_PATH_MAX)
64 #define G_PATH_LENGTH   sysconf(_PC_PATH_MAX)
65 #else   
66 #define G_PATH_LENGTH   2048
67 #endif
68
69 #ifdef G_PLATFORM_WIN32
70 #  define STRICT                /* Strict typing, please */
71 #  include <windows.h>
72 #  undef STRICT
73 #  include <lmcons.h>           /* For UNLEN */
74 #endif /* G_PLATFORM_WIN32 */
75
76 #ifdef G_OS_WIN32
77 #  include <direct.h>
78 #  include <shlobj.h>
79    /* older SDK (e.g. msvc 5.0) does not have these*/
80 #  ifndef CSIDL_INTERNET_CACHE
81 #    define CSIDL_INTERNET_CACHE 32
82 #  endif
83 #  ifndef CSIDL_COMMON_APPDATA
84 #    define CSIDL_COMMON_APPDATA 35
85 #  endif
86 #  ifndef CSIDL_COMMON_DOCUMENTS
87 #    define CSIDL_COMMON_DOCUMENTS 46
88 #  endif
89 #  ifndef CSIDL_PROFILE
90 #    define CSIDL_PROFILE 40
91 #  endif
92 #endif
93
94 #ifdef HAVE_CODESET
95 #include <langinfo.h>
96 #endif
97
98 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
99 #include <libintl.h>
100 #endif
101
102 const guint glib_major_version = GLIB_MAJOR_VERSION;
103 const guint glib_minor_version = GLIB_MINOR_VERSION;
104 const guint glib_micro_version = GLIB_MICRO_VERSION;
105 const guint glib_interface_age = GLIB_INTERFACE_AGE;
106 const guint glib_binary_age = GLIB_BINARY_AGE;
107
108 /**
109  * glib_check_version:
110  * @required_major: the required major version.
111  * @required_minor: the required major version.
112  * @required_micro: the required major version.
113  *
114  * Checks that the GLib library in use is compatible with the
115  * given version. Generally you would pass in the constants
116  * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
117  * as the three arguments to this function; that produces
118  * a check that the library in use is compatible with
119  * the version of GLib the application or module was compiled
120  * against.
121  *
122  * Compatibility is defined by two things: first the version
123  * of the running library is newer than the version
124  * @required_major.required_minor.@required_micro. Second
125  * the running library must be binary compatible with the
126  * version @required_major.required_minor.@required_micro
127  * (same major version.)
128  *
129  * Return value: %NULL if the GLib library is compatible with the
130  *   given version, or a string describing the version mismatch.
131  *   The returned string is owned by GLib and must not be modified
132  *   or freed.
133  *
134  * Since: 2.6
135  **/
136 const gchar *
137 glib_check_version (guint required_major,
138                     guint required_minor,
139                     guint required_micro)
140 {
141   gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
142   gint required_effective_micro = 100 * required_minor + required_micro;
143
144   if (required_major > GLIB_MAJOR_VERSION)
145     return "GLib version too old (major mismatch)";
146   if (required_major < GLIB_MAJOR_VERSION)
147     return "GLib version too new (major mismatch)";
148   if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
149     return "GLib version too new (micro mismatch)";
150   if (required_effective_micro > glib_effective_micro)
151     return "GLib version too old (micro mismatch)";
152   return NULL;
153 }
154
155 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
156 void 
157 g_memmove (gpointer dest, gconstpointer src, gulong len)
158 {
159   gchar* destptr = dest;
160   const gchar* srcptr = src;
161   if (src + len < dest || dest + len < src)
162     {
163       bcopy (src, dest, len);
164       return;
165     }
166   else if (dest <= src)
167     {
168       while (len--)
169         *(destptr++) = *(srcptr++);
170     }
171   else
172     {
173       destptr += len;
174       srcptr += len;
175       while (len--)
176         *(--destptr) = *(--srcptr);
177     }
178 }
179 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
180
181 void
182 g_atexit (GVoidFunc func)
183 {
184   gint result;
185   const gchar *error = NULL;
186
187   /* keep this in sync with glib.h */
188
189 #ifdef  G_NATIVE_ATEXIT
190   result = ATEXIT (func);
191   if (result)
192     error = g_strerror (errno);
193 #elif defined (HAVE_ATEXIT)
194 #  ifdef NeXT /* @#%@! NeXTStep */
195   result = !atexit ((void (*)(void)) func);
196   if (result)
197     error = g_strerror (errno);
198 #  else
199   result = atexit ((void (*)(void)) func);
200   if (result)
201     error = g_strerror (errno);
202 #  endif /* NeXT */
203 #elif defined (HAVE_ON_EXIT)
204   result = on_exit ((void (*)(int, void *)) func, NULL);
205   if (result)
206     error = g_strerror (errno);
207 #else
208   result = 0;
209   error = "no implementation";
210 #endif /* G_NATIVE_ATEXIT */
211
212   if (error)
213     g_error ("Could not register atexit() function: %s", error);
214 }
215
216 /* Based on execvp() from GNU Libc.
217  * Some of this code is cut-and-pasted into gspawn.c
218  */
219
220 static gchar*
221 my_strchrnul (const gchar *str, gchar c)
222 {
223   gchar *p = (gchar*)str;
224   while (*p && (*p != c))
225     ++p;
226
227   return p;
228 }
229
230 #ifdef G_OS_WIN32
231
232 static gchar *inner_find_program_in_path (const gchar *program);
233
234 gchar*
235 g_find_program_in_path (const gchar *program)
236 {
237   const gchar *last_dot = strrchr (program, '.');
238
239   if (last_dot == NULL ||
240       strchr (last_dot, '\\') != NULL ||
241       strchr (last_dot, '/') != NULL)
242     {
243       const gint program_length = strlen (program);
244       gchar *pathext = g_build_path (";",
245                                      ".exe;.cmd;.bat;.com",
246                                      g_getenv ("PATHEXT"),
247                                      NULL);
248       gchar *p;
249       gchar *decorated_program;
250       gchar *retval;
251
252       p = pathext;
253       do
254         {
255           gchar *q = my_strchrnul (p, ';');
256
257           decorated_program = g_malloc (program_length + (q-p) + 1);
258           memcpy (decorated_program, program, program_length);
259           memcpy (decorated_program+program_length, p, q-p);
260           decorated_program [program_length + (q-p)] = '\0';
261           
262           retval = inner_find_program_in_path (decorated_program);
263           g_free (decorated_program);
264
265           if (retval != NULL)
266             {
267               g_free (pathext);
268               return retval;
269             }
270           p = q;
271         } while (*p++ != '\0');
272       g_free (pathext);
273       return NULL;
274     }
275   else
276     return inner_find_program_in_path (program);
277 }
278
279 #endif
280
281 /**
282  * g_find_program_in_path:
283  * @program: a program name in the GLib file name encoding
284  * 
285  * Locates the first executable named @program in the user's path, in the
286  * same way that execvp() would locate it. Returns an allocated string
287  * with the absolute path name, or NULL if the program is not found in
288  * the path. If @program is already an absolute path, returns a copy of
289  * @program if @program exists and is executable, and NULL otherwise.
290  * 
291  * On Windows, if @program does not have a file type suffix, tries
292  * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
293  * the PATHEXT environment variable.
294  *
295  * It looks for the file in the same way as CreateProcess()
296  * would. This means first in the directory where the executing
297  * program was loaded from, then in the current directory, then in the
298  * Windows 32-bit system directory, then in the Windows directory, and
299  * finally in the directories in the PATH environment variable. If the
300  * program is found, the return value contains the full name including
301  * the type suffix.
302  *
303  * Return value: absolute path, or NULL
304  **/
305 #ifdef G_OS_WIN32
306 static gchar *
307 inner_find_program_in_path (const gchar *program)
308 #else
309 gchar*
310 g_find_program_in_path (const gchar *program)
311 #endif
312 {
313   const gchar *path, *p;
314   gchar *name, *freeme;
315 #ifdef G_OS_WIN32
316   const gchar *path_copy;
317   gchar *filename = NULL, *appdir = NULL;
318   gchar *sysdir = NULL, *windir = NULL;
319 #endif
320   size_t len;
321   size_t pathlen;
322
323   g_return_val_if_fail (program != NULL, NULL);
324
325   /* If it is an absolute path, or a relative path including subdirectories,
326    * don't look in PATH.
327    */
328   if (g_path_is_absolute (program)
329       || strchr (program, G_DIR_SEPARATOR) != NULL
330 #ifdef G_OS_WIN32
331       || strchr (program, '/') != NULL
332 #endif
333       )
334     {
335       if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
336         return g_strdup (program);
337       else
338         return NULL;
339     }
340   
341   path = g_getenv ("PATH");
342 #ifdef G_OS_UNIX
343   if (path == NULL)
344     {
345       /* There is no `PATH' in the environment.  The default
346        * search path in GNU libc is the current directory followed by
347        * the path `confstr' returns for `_CS_PATH'.
348        */
349       
350       /* In GLib we put . last, for security, and don't use the
351        * unportable confstr(); UNIX98 does not actually specify
352        * what to search if PATH is unset. POSIX may, dunno.
353        */
354       
355       path = "/bin:/usr/bin:.";
356     }
357 #else
358   if (G_WIN32_HAVE_WIDECHAR_API ())
359     {
360       int n;
361       wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
362         wwindir[MAXPATHLEN];
363       
364       n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
365       if (n > 0 && n < MAXPATHLEN)
366         filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
367       
368       n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
369       if (n > 0 && n < MAXPATHLEN)
370         sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
371       
372       n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
373       if (n > 0 && n < MAXPATHLEN)
374         windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
375     }
376   else
377     {
378       int n;
379       gchar cpfilename[MAXPATHLEN], cpsysdir[MAXPATHLEN],
380         cpwindir[MAXPATHLEN];
381       
382       n = GetModuleFileNameA (NULL, cpfilename, MAXPATHLEN);
383       if (n > 0 && n < MAXPATHLEN)
384         filename = g_locale_to_utf8 (cpfilename, -1, NULL, NULL, NULL);
385       
386       n = GetSystemDirectoryA (cpsysdir, MAXPATHLEN);
387       if (n > 0 && n < MAXPATHLEN)
388         sysdir = g_locale_to_utf8 (cpsysdir, -1, NULL, NULL, NULL);
389       
390       n = GetWindowsDirectoryA (cpwindir, MAXPATHLEN);
391       if (n > 0 && n < MAXPATHLEN)
392         windir = g_locale_to_utf8 (cpwindir, -1, NULL, NULL, NULL);
393     }
394   
395   if (filename)
396     {
397       appdir = g_path_get_dirname (filename);
398       g_free (filename);
399     }
400   
401   path = g_strdup (path);
402
403   if (windir)
404     {
405       const gchar *tem = path;
406       path = g_strconcat (windir, ";", path, NULL);
407       g_free ((gchar *) tem);
408       g_free (windir);
409     }
410   
411   if (sysdir)
412     {
413       const gchar *tem = path;
414       path = g_strconcat (sysdir, ";", path, NULL);
415       g_free ((gchar *) tem);
416       g_free (sysdir);
417     }
418   
419   {
420     const gchar *tem = path;
421     path = g_strconcat (".;", path, NULL);
422     g_free ((gchar *) tem);
423   }
424   
425   if (appdir)
426     {
427       const gchar *tem = path;
428       path = g_strconcat (appdir, ";", path, NULL);
429       g_free ((gchar *) tem);
430       g_free (appdir);
431     }
432
433   path_copy = path;
434 #endif
435   
436   len = strlen (program) + 1;
437   pathlen = strlen (path);
438   freeme = name = g_malloc (pathlen + len + 1);
439   
440   /* Copy the file name at the top, including '\0'  */
441   memcpy (name + pathlen + 1, program, len);
442   name = name + pathlen;
443   /* And add the slash before the filename  */
444   *name = G_DIR_SEPARATOR;
445   
446   p = path;
447   do
448     {
449       char *startp;
450
451       path = p;
452       p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
453
454       if (p == path)
455         /* Two adjacent colons, or a colon at the beginning or the end
456          * of `PATH' means to search the current directory.
457          */
458         startp = name + 1;
459       else
460         startp = memcpy (name - (p - path), path, p - path);
461
462       if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
463         {
464           gchar *ret;
465           ret = g_strdup (startp);
466           g_free (freeme);
467 #ifdef G_OS_WIN32
468           g_free ((gchar *) path_copy);
469 #endif
470           return ret;
471         }
472     }
473   while (*p++ != '\0');
474   
475   g_free (freeme);
476 #ifdef G_OS_WIN32
477   g_free ((gchar *) path_copy);
478 #endif
479
480   return NULL;
481 }
482
483 guint        
484 g_parse_debug_string  (const gchar     *string, 
485                        const GDebugKey *keys, 
486                        guint            nkeys)
487 {
488   guint i;
489   guint result = 0;
490   
491   g_return_val_if_fail (string != NULL, 0);
492   
493   if (!g_ascii_strcasecmp (string, "all"))
494     {
495       for (i=0; i<nkeys; i++)
496         result |= keys[i].value;
497     }
498   else
499     {
500       const gchar *p = string;
501       const gchar *q;
502       gboolean done = FALSE;
503       
504       while (*p && !done)
505         {
506           q = strchr (p, ':');
507           if (!q)
508             {
509               q = p + strlen(p);
510               done = TRUE;
511             }
512           
513           for (i=0; i<nkeys; i++)
514             if (g_ascii_strncasecmp (keys[i].key, p, q - p) == 0 &&
515                 keys[i].key[q - p] == '\0')
516               result |= keys[i].value;
517           
518           p = q + 1;
519         }
520     }
521   
522   return result;
523 }
524
525 /**
526  * g_basename:
527  * @file_name: the name of the file.
528  * 
529  * Gets the name of the file without any leading directory components.  
530  * It returns a pointer into the given file name string.
531  * 
532  * Return value: the name of the file without any leading directory components.
533  *
534  * Deprecated: Use g_path_get_basename() instead, but notice that
535  * g_path_get_basename() allocates new memory for the returned string, unlike
536  * this function which returns a pointer into the argument.
537  **/
538 G_CONST_RETURN gchar*
539 g_basename (const gchar    *file_name)
540 {
541   register gchar *base;
542   
543   g_return_val_if_fail (file_name != NULL, NULL);
544   
545   base = strrchr (file_name, G_DIR_SEPARATOR);
546
547 #ifdef G_OS_WIN32
548   {
549     gchar *q = strrchr (file_name, '/');
550     if (base == NULL || (q != NULL && q > base))
551         base = q;
552   }
553 #endif
554
555   if (base)
556     return base + 1;
557
558 #ifdef G_OS_WIN32
559   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
560     return (gchar*) file_name + 2;
561 #endif /* G_OS_WIN32 */
562   
563   return (gchar*) file_name;
564 }
565
566 /**
567  * g_path_get_basename:
568  * @file_name: the name of the file.
569  *
570  * Gets the last component of the filename. If @file_name ends with a 
571  * directory separator it gets the component before the last slash. If 
572  * @file_name consists only of directory separators (and on Windows, 
573  * possibly a drive letter), a single separator is returned. If
574  * @file_name is empty, it gets ".".
575  *
576  * Return value: a newly allocated string containing the last component of 
577  *   the filename.
578  */
579 gchar*
580 g_path_get_basename (const gchar   *file_name)
581 {
582   register gssize base;             
583   register gssize last_nonslash;    
584   gsize len;    
585   gchar *retval;
586  
587   g_return_val_if_fail (file_name != NULL, NULL);
588
589   if (file_name[0] == '\0')
590     /* empty string */
591     return g_strdup (".");
592   
593   last_nonslash = strlen (file_name) - 1;
594
595   while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
596     last_nonslash--;
597
598   if (last_nonslash == -1)
599     /* string only containing slashes */
600     return g_strdup (G_DIR_SEPARATOR_S);
601
602 #ifdef G_OS_WIN32
603   if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
604     /* string only containing slashes and a drive */
605     return g_strdup (G_DIR_SEPARATOR_S);
606 #endif /* G_OS_WIN32 */
607
608   base = last_nonslash;
609
610   while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
611     base--;
612
613 #ifdef G_OS_WIN32
614   if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
615     base = 1;
616 #endif /* G_OS_WIN32 */
617
618   len = last_nonslash - base;
619   retval = g_malloc (len + 1);
620   memcpy (retval, file_name + base + 1, len);
621   retval [len] = '\0';
622   return retval;
623 }
624
625 gboolean
626 g_path_is_absolute (const gchar *file_name)
627 {
628   g_return_val_if_fail (file_name != NULL, FALSE);
629   
630   if (G_IS_DIR_SEPARATOR (file_name[0]))
631     return TRUE;
632
633 #ifdef G_OS_WIN32
634   /* Recognize drive letter on native Windows */
635   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
636     return TRUE;
637 #endif /* G_OS_WIN32 */
638
639   return FALSE;
640 }
641
642 G_CONST_RETURN gchar*
643 g_path_skip_root (const gchar *file_name)
644 {
645   g_return_val_if_fail (file_name != NULL, NULL);
646   
647 #ifdef G_PLATFORM_WIN32
648   /* Skip \\server\share or //server/share */
649   if (G_IS_DIR_SEPARATOR (file_name[0]) &&
650       G_IS_DIR_SEPARATOR (file_name[1]) &&
651       file_name[2] &&
652       !G_IS_DIR_SEPARATOR (file_name[2]))
653     {
654       gchar *p;
655
656       p = strchr (file_name + 2, G_DIR_SEPARATOR);
657 #ifdef G_OS_WIN32
658       {
659         gchar *q = strchr (file_name + 2, '/');
660         if (p == NULL || (q != NULL && q < p))
661           p = q;
662       }
663 #endif
664       if (p &&
665           p > file_name + 2 &&
666           p[1])
667         {
668           file_name = p + 1;
669
670           while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
671             file_name++;
672
673           /* Possibly skip a backslash after the share name */
674           if (G_IS_DIR_SEPARATOR (file_name[0]))
675             file_name++;
676
677           return (gchar *)file_name;
678         }
679     }
680 #endif
681   
682   /* Skip initial slashes */
683   if (G_IS_DIR_SEPARATOR (file_name[0]))
684     {
685       while (G_IS_DIR_SEPARATOR (file_name[0]))
686         file_name++;
687       return (gchar *)file_name;
688     }
689
690 #ifdef G_OS_WIN32
691   /* Skip X:\ */
692   if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
693     return (gchar *)file_name + 3;
694 #endif
695
696   return NULL;
697 }
698
699 gchar*
700 g_path_get_dirname (const gchar    *file_name)
701 {
702   register gchar *base;
703   register gsize len;    
704   
705   g_return_val_if_fail (file_name != NULL, NULL);
706   
707   base = strrchr (file_name, G_DIR_SEPARATOR);
708 #ifdef G_OS_WIN32
709   {
710     gchar *q = strrchr (file_name, '/');
711     if (base == NULL || (q != NULL && q > base))
712         base = q;
713   }
714 #endif
715   if (!base)
716     {
717 #ifdef G_OS_WIN32
718       if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
719         {
720           gchar drive_colon_dot[4];
721
722           drive_colon_dot[0] = file_name[0];
723           drive_colon_dot[1] = ':';
724           drive_colon_dot[2] = '.';
725           drive_colon_dot[3] = '\0';
726
727           return g_strdup (drive_colon_dot);
728         }
729 #endif
730     return g_strdup (".");
731     }
732
733   while (base > file_name && G_IS_DIR_SEPARATOR (*base))
734     base--;
735
736 #ifdef G_OS_WIN32
737   /* base points to the char before the last slash.
738    *
739    * In case file_name is the root of a drive (X:\) or a child of the
740    * root of a drive (X:\foo), include the slash.
741    *
742    * In case file_name is the root share of an UNC path
743    * (\\server\share), add a slash, returning \\server\share\ .
744    *
745    * In case file_name is a direct child of a share in an UNC path
746    * (\\server\share\foo), include the slash after the share name,
747    * returning \\server\share\ .
748    */
749   if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
750     base++;
751   else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
752            G_IS_DIR_SEPARATOR (file_name[1]) &&
753            file_name[2] &&
754            !G_IS_DIR_SEPARATOR (file_name[2]) &&
755            base >= file_name + 2)
756     {
757       const gchar *p = file_name + 2;
758       while (*p && !G_IS_DIR_SEPARATOR (*p))
759         p++;
760       if (p == base + 1)
761         {
762           len = (guint) strlen (file_name) + 1;
763           base = g_new (gchar, len + 1);
764           strcpy (base, file_name);
765           base[len-1] = G_DIR_SEPARATOR;
766           base[len] = 0;
767           return base;
768         }
769       if (G_IS_DIR_SEPARATOR (*p))
770         {
771           p++;
772           while (*p && !G_IS_DIR_SEPARATOR (*p))
773             p++;
774           if (p == base + 1)
775             base++;
776         }
777     }
778 #endif
779
780   len = (guint) 1 + base - file_name;
781   
782   base = g_new (gchar, len + 1);
783   g_memmove (base, file_name, len);
784   base[len] = 0;
785   
786   return base;
787 }
788
789 gchar*
790 g_get_current_dir (void)
791 {
792 #ifdef G_OS_WIN32
793
794   gchar *dir = NULL;
795
796   if (G_WIN32_HAVE_WIDECHAR_API ())
797     {
798       wchar_t dummy[2], *wdir;
799       int len;
800
801       len = GetCurrentDirectoryW (2, dummy);
802       wdir = g_new (wchar_t, len);
803
804       if (GetCurrentDirectoryW (len, wdir) == len - 1)
805         dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
806
807       g_free (wdir);
808     }
809   else
810     {
811       gchar dummy[2], *cpdir;
812       int len;
813
814       len = GetCurrentDirectoryA (2, dummy);
815       cpdir = g_new (gchar, len);
816
817       if (GetCurrentDirectoryA (len, cpdir) == len - 1)
818         dir = g_locale_to_utf8 (cpdir, -1, NULL, NULL, NULL);
819
820       g_free (cpdir);
821     }
822
823   if (dir == NULL)
824     dir = g_strdup ("\\");
825
826   return dir;
827
828 #else
829
830   gchar *buffer = NULL;
831   gchar *dir = NULL;
832   static gulong max_len = 0;
833
834   if (max_len == 0) 
835     max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
836   
837   /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
838    * and, if that wasn't bad enough, hangs in doing so.
839    */
840 #if     (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
841   buffer = g_new (gchar, max_len + 1);
842   *buffer = 0;
843   dir = getwd (buffer);
844 #else   /* !sun || !HAVE_GETCWD */
845   while (max_len < G_MAXULONG / 2)
846     {
847       buffer = g_new (gchar, max_len + 1);
848       *buffer = 0;
849       dir = getcwd (buffer, max_len);
850
851       if (dir || errno != ERANGE)
852         break;
853
854       g_free (buffer);
855       max_len *= 2;
856     }
857 #endif  /* !sun || !HAVE_GETCWD */
858   
859   if (!dir || !*buffer)
860     {
861       /* hm, should we g_error() out here?
862        * this can happen if e.g. "./" has mode \0000
863        */
864       buffer[0] = G_DIR_SEPARATOR;
865       buffer[1] = 0;
866     }
867
868   dir = g_strdup (buffer);
869   g_free (buffer);
870   
871   return dir;
872 #endif /* !Win32 */
873 }
874
875 /**
876  * g_getenv:
877  * @variable: the environment variable to get, in the GLib file name encoding.
878  * 
879  * Returns the value of an environment variable. The name and value
880  * are in the GLib file name encoding. On Unix, this means the actual
881  * bytes which might or might not be in some consistent character set
882  * and encoding. On Windows, it is in UTF-8. On Windows, in case the
883  * environment variable's value contains references to other
884  * environment variables, they are expanded.
885  * 
886  * Return value: the value of the environment variable, or %NULL if
887  * the environment variable is not found. The returned string may be
888  * overwritten by the next call to g_getenv(), g_setenv() or
889  * g_unsetenv().
890  **/
891 G_CONST_RETURN gchar*
892 g_getenv (const gchar *variable)
893 {
894 #ifndef G_OS_WIN32
895
896   g_return_val_if_fail (variable != NULL, NULL);
897
898   return getenv (variable);
899
900 #else /* G_OS_WIN32 */
901
902   GQuark quark;
903   gchar *value;
904
905   g_return_val_if_fail (variable != NULL, NULL);
906   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
907
908   /* On Windows NT, it is relatively typical that environment
909    * variables contain references to other environment variables. If
910    * so, use ExpandEnvironmentStrings(). (In an ideal world, such
911    * environment variables would be stored in the Registry as
912    * REG_EXPAND_SZ type values, and would then get automatically
913    * expanded before a program sees them. But there is broken software
914    * that stores environment variables as REG_SZ values even if they
915    * contain references to other environment variables.)
916    */
917
918   if (G_WIN32_HAVE_WIDECHAR_API ())
919     {
920       wchar_t dummy[2], *wname, *wvalue;
921       int len;
922       
923       wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
924
925       len = GetEnvironmentVariableW (wname, dummy, 2);
926
927       if (len == 0)
928         {
929           g_free (wname);
930           return NULL;
931         }
932
933       wvalue = g_new (wchar_t, len);
934
935       if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
936         {
937           g_free (wname);
938           g_free (wvalue);
939           return NULL;
940         }
941
942       if (wcschr (wvalue, L'%') != NULL)
943         {
944           wchar_t *tem = wvalue;
945
946           len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
947
948           if (len > 0)
949             {
950               wvalue = g_new (wchar_t, len);
951
952               if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
953                 {
954                   g_free (wvalue);
955                   wvalue = tem;
956                 }
957               else
958                 g_free (tem);
959             }
960         }
961
962       value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
963
964       g_free (wname);
965       g_free (wvalue);
966     }
967   else
968     {
969       gchar dummy[3], *cpname, *cpvalue;
970       int len;
971       
972       cpname = g_locale_from_utf8 (variable, -1, NULL, NULL, NULL);
973
974       g_return_val_if_fail (cpname != NULL, NULL);
975
976       len = GetEnvironmentVariableA (cpname, dummy, 2);
977
978       if (len == 0)
979         {
980           g_free (cpname);
981           return NULL;
982         }
983
984       cpvalue = g_new (gchar, len);
985
986       if (GetEnvironmentVariableA (cpname, cpvalue, len) != len - 1)
987         {
988           g_free (cpname);
989           g_free (cpvalue);
990           return NULL;
991         }
992
993       if (strchr (cpvalue, '%') != NULL)
994         {
995           gchar *tem = cpvalue;
996
997           len = ExpandEnvironmentStringsA (cpvalue, dummy, 3);
998
999           if (len > 0)
1000             {
1001               cpvalue = g_new (gchar, len);
1002
1003               if (ExpandEnvironmentStringsA (tem, cpvalue, len) != len)
1004                 {
1005                   g_free (cpvalue);
1006                   cpvalue = tem;
1007                 }
1008               else
1009                 g_free (tem);
1010             }
1011         }
1012
1013       value = g_locale_to_utf8 (cpvalue, -1, NULL, NULL, NULL);
1014
1015       g_free (cpname);
1016       g_free (cpvalue);
1017     }
1018
1019   quark = g_quark_from_string (value);
1020   g_free (value);
1021   
1022   return g_quark_to_string (quark);
1023
1024 #endif /* G_OS_WIN32 */
1025 }
1026
1027 /**
1028  * g_setenv:
1029  * @variable: the environment variable to set, must not contain '='.
1030  * @value: the value for to set the variable to.
1031  * @overwrite: whether to change the variable if it already exists.
1032  *
1033  * Sets an environment variable. Both the variable's name and value
1034  * should be in the GLib file name encoding. On Unix, this means that
1035  * they can be any sequence of bytes. On Windows, they should be in
1036  * UTF-8.
1037  *
1038  * Note that on some systems, the memory used for the variable and its value 
1039  * can't be reclaimed later.
1040  *
1041  * Returns: %FALSE if the environment variable couldn't be set.
1042  *
1043  * Since: 2.4
1044  */
1045 gboolean
1046 g_setenv (const gchar *variable, 
1047           const gchar *value, 
1048           gboolean     overwrite)
1049 {
1050 #ifndef G_OS_WIN32
1051
1052   gint result;
1053 #ifndef HAVE_SETENV
1054   gchar *string;
1055 #endif
1056
1057   g_return_val_if_fail (variable != NULL, FALSE);
1058   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1059
1060 #ifdef HAVE_SETENV
1061   result = setenv (variable, value, overwrite);
1062 #else
1063   if (!overwrite && getenv (variable) != NULL)
1064     return TRUE;
1065   
1066   /* This results in a leak when you overwrite existing
1067    * settings. It would be fairly easy to fix this by keeping
1068    * our own parallel array or hash table.
1069    */
1070   string = g_strconcat (variable, "=", value, NULL);
1071   result = putenv (string);
1072 #endif
1073   return result == 0;
1074
1075 #else /* G_OS_WIN32 */
1076
1077   gboolean retval;
1078
1079   g_return_val_if_fail (variable != NULL, FALSE);
1080   g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1081   g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1082   g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1083
1084   if (!overwrite && g_getenv (variable) != NULL)
1085     return TRUE;
1086
1087   /* We want to (if possible) set both the environment variable copy
1088    * kept by the C runtime and the one kept by the system.
1089    *
1090    * We can't use only the C runtime's putenv or _wputenv() as that
1091    * won't work for arbitrary Unicode strings in a "non-Unicode" app
1092    * (with main() and not wmain()). In a "main()" app the C runtime
1093    * initializes the C runtime's environment table by converting the
1094    * real (wide char) environment variables to system codepage, thus
1095    * breaking those that aren't representable in the system codepage.
1096    *
1097    * As the C runtime's putenv() will also set the system copy, we do
1098    * the putenv() first, then call SetEnvironmentValueW ourselves.
1099    */
1100
1101   if (G_WIN32_HAVE_WIDECHAR_API ())
1102     {
1103       wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1104       wchar_t *wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1105       gchar *tem = g_strconcat (variable, "=", value, NULL);
1106       wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1107       
1108       g_free (tem);
1109       _wputenv (wassignment);
1110       g_free (wassignment);
1111
1112       retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1113
1114       g_free (wname);
1115       g_free (wvalue);
1116     }
1117   else
1118     {
1119       /* In the non-Unicode case (Win9x), just putenv() is good
1120        * enough.
1121        */
1122       gchar *tem = g_strconcat (variable, "=", value, NULL);
1123       gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1124
1125       g_free (tem);
1126       
1127       retval = (putenv (cpassignment) == 0);
1128
1129       g_free (cpassignment);
1130     }
1131
1132   return retval;
1133
1134 #endif /* G_OS_WIN32 */
1135 }
1136
1137 #ifndef G_OS_WIN32
1138 #ifndef HAVE_UNSETENV     
1139 /* According to the Single Unix Specification, environ is not in 
1140  * any system header, although unistd.h often declares it.
1141  */
1142 extern char **environ;
1143 #endif
1144 #endif
1145            
1146 /**
1147  * g_unsetenv:
1148  * @variable: the environment variable to remove, must not contain '='.
1149  * 
1150  * Removes an environment variable from the environment.
1151  *
1152  * Note that on some systems, the memory used for the variable and its value 
1153  * can't be reclaimed. Furthermore, this function can't be guaranteed to operate in a 
1154  * threadsafe way.
1155  *
1156  * Since: 2.4 
1157  **/
1158 void
1159 g_unsetenv (const gchar *variable)
1160 {
1161 #ifndef G_OS_WIN32
1162
1163 #ifdef HAVE_UNSETENV
1164   g_return_if_fail (variable != NULL);
1165   g_return_if_fail (strchr (variable, '=') == NULL);
1166
1167   unsetenv (variable);
1168 #else /* !HAVE_UNSETENV */
1169   int len;
1170   gchar **e, **f;
1171
1172   g_return_if_fail (variable != NULL);
1173   g_return_if_fail (strchr (variable, '=') == NULL);
1174
1175   len = strlen (variable);
1176   
1177   /* Mess directly with the environ array.
1178    * This seems to be the only portable way to do this.
1179    *
1180    * Note that we remove *all* environment entries for
1181    * the variable name, not just the first.
1182    */
1183   e = f = environ;
1184   while (*e != NULL) 
1185     {
1186       if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=') 
1187         {
1188           *f = *e;
1189           f++;
1190         }
1191       e++;
1192     }
1193   *f = NULL;
1194 #endif /* !HAVE_UNSETENV */
1195
1196 #else  /* G_OS_WIN32 */
1197
1198   g_return_if_fail (variable != NULL);
1199   g_return_if_fail (strchr (variable, '=') == NULL);
1200   g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1201
1202   if (G_WIN32_HAVE_WIDECHAR_API ())
1203     {
1204       wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1205       gchar *tem = g_strconcat (variable, "=", NULL);
1206       wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1207       
1208       g_free (tem);
1209       _wputenv (wassignment);
1210       g_free (wassignment);
1211
1212       SetEnvironmentVariableW (wname, NULL);
1213
1214       g_free (wname);
1215     }
1216   else
1217     {
1218       /* In the non-Unicode case (Win9x), just putenv() is good
1219        * enough.
1220        */
1221       gchar *tem = g_strconcat (variable, "=", NULL);
1222       gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1223
1224       g_free (tem);
1225       
1226       putenv (cpassignment);
1227
1228       g_free (cpassignment);
1229     }
1230
1231 #endif /* G_OS_WIN32 */
1232 }
1233
1234 G_LOCK_DEFINE_STATIC (g_utils_global);
1235
1236 static  gchar   *g_tmp_dir = NULL;
1237 static  gchar   *g_user_name = NULL;
1238 static  gchar   *g_real_name = NULL;
1239 static  gchar   *g_home_dir = NULL;
1240
1241 #ifdef G_OS_WIN32
1242 /* System codepage versions of the above, kept at file level so that they,
1243  * too, are produced only once.
1244  */
1245 static  gchar   *g_tmp_dir_cp = NULL;
1246 static  gchar   *g_user_name_cp = NULL;
1247 static  gchar   *g_real_name_cp = NULL;
1248 static  gchar   *g_home_dir_cp = NULL;
1249 #endif
1250
1251 static  gchar   *g_user_data_dir = NULL;
1252 static  gchar  **g_system_data_dirs = NULL;
1253 static  gchar   *g_user_cache_dir = NULL;
1254 static  gchar   *g_user_config_dir = NULL;
1255 static  gchar  **g_system_config_dirs = NULL;
1256
1257 #ifdef G_OS_WIN32
1258
1259 static gchar *
1260 get_special_folder (int csidl)
1261 {
1262   union {
1263     char c[MAX_PATH+1];
1264     wchar_t wc[MAX_PATH+1];
1265   } path;
1266   HRESULT hr;
1267   LPITEMIDLIST pidl = NULL;
1268   BOOL b;
1269   gchar *retval = NULL;
1270
1271   hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1272   if (hr == S_OK)
1273     {
1274       if (G_WIN32_HAVE_WIDECHAR_API ())
1275         {
1276           b = SHGetPathFromIDListW (pidl, path.wc);
1277           if (b)
1278             retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
1279         }
1280       else
1281         {
1282           b = SHGetPathFromIDListA (pidl, path.c);
1283           if (b)
1284             retval = g_locale_to_utf8 (path.c, -1, NULL, NULL, NULL);
1285         }
1286       CoTaskMemFree (pidl);
1287     }
1288   return retval;
1289 }
1290
1291 #endif
1292
1293 /* HOLDS: g_utils_global_lock */
1294 static void
1295 g_get_any_init (void)
1296 {
1297   if (!g_tmp_dir)
1298     {
1299       g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1300       if (!g_tmp_dir)
1301         g_tmp_dir = g_strdup (g_getenv ("TMP"));
1302       if (!g_tmp_dir)
1303         g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1304       
1305 #ifdef P_tmpdir
1306       if (!g_tmp_dir)
1307         {
1308           gsize k;    
1309           g_tmp_dir = g_strdup (P_tmpdir);
1310           k = strlen (g_tmp_dir);
1311           if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1312             g_tmp_dir[k - 1] = '\0';
1313         }
1314 #endif
1315       
1316       if (!g_tmp_dir)
1317         {
1318 #ifndef G_OS_WIN32
1319           g_tmp_dir = g_strdup ("/tmp");
1320 #else /* G_OS_WIN32 */
1321           g_tmp_dir = g_strdup ("\\");
1322 #endif /* G_OS_WIN32 */
1323         }
1324       
1325 #ifdef G_OS_WIN32
1326       /* We check $HOME first for Win32, though it is a last resort for Unix
1327        * where we prefer the results of getpwuid().
1328        */
1329       g_home_dir = g_strdup (g_getenv ("HOME"));
1330
1331       /* Only believe HOME if it is an absolute path and exists */
1332       if (g_home_dir)
1333         {
1334           if (!(g_path_is_absolute (g_home_dir) &&
1335                 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1336             {
1337               g_free (g_home_dir);
1338               g_home_dir = NULL;
1339             }
1340         }
1341       
1342       /* In case HOME is Unix-style (it happens), convert it to
1343        * Windows style.
1344        */
1345       if (g_home_dir)
1346         {
1347           gchar *p;
1348           while ((p = strchr (g_home_dir, '/')) != NULL)
1349             *p = '\\';
1350         }
1351
1352       if (!g_home_dir)
1353         {
1354           /* USERPROFILE is probably the closest equivalent to $HOME? */
1355           if (g_getenv ("USERPROFILE") != NULL)
1356             g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1357         }
1358
1359       if (!g_home_dir)
1360         g_home_dir = get_special_folder (CSIDL_PROFILE);
1361       
1362       if (!g_home_dir)
1363         {
1364           /* At least at some time, HOMEDRIVE and HOMEPATH were used
1365            * to point to the home directory, I think. But on Windows
1366            * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
1367            * HOMEPATH is its root "\"?
1368            */
1369           if (g_getenv ("HOMEDRIVE") != NULL && g_getenv ("HOMEPATH") != NULL)
1370             g_home_dir = g_strconcat (g_getenv ("HOMEDRIVE"),
1371                                       g_getenv ("HOMEPATH"),
1372                                       NULL);
1373         }
1374 #endif /* G_OS_WIN32 */
1375       
1376 #ifdef HAVE_PWD_H
1377       {
1378         struct passwd *pw = NULL;
1379         gpointer buffer = NULL;
1380         gint error;
1381         
1382 #  if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1383         struct passwd pwd;
1384 #    ifdef _SC_GETPW_R_SIZE_MAX  
1385         /* This reurns the maximum length */
1386         glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1387         
1388         if (bufsize < 0)
1389           bufsize = 64;
1390 #    else /* _SC_GETPW_R_SIZE_MAX */
1391         glong bufsize = 64;
1392 #    endif /* _SC_GETPW_R_SIZE_MAX */
1393         
1394         do
1395           {
1396             g_free (buffer);
1397             /* we allocate 6 extra bytes to work around a bug in 
1398              * Mac OS < 10.3. See #156446
1399              */
1400             buffer = g_malloc (bufsize + 6);
1401             errno = 0;
1402             
1403 #    ifdef HAVE_POSIX_GETPWUID_R
1404             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1405             error = error < 0 ? errno : error;
1406 #    else /* HAVE_NONPOSIX_GETPWUID_R */
1407        /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1408 #      if defined(_AIX) || defined(__hpux)
1409             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1410             pw = error == 0 ? &pwd : NULL;
1411 #      else /* !_AIX */
1412             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1413             error = pw ? 0 : errno;
1414 #      endif /* !_AIX */            
1415 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
1416             
1417             if (!pw)
1418               {
1419                 /* we bail out prematurely if the user id can't be found
1420                  * (should be pretty rare case actually), or if the buffer
1421                  * should be sufficiently big and lookups are still not
1422                  * successfull.
1423                  */
1424                 if (error == 0 || error == ENOENT)
1425                   {
1426                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1427                                (gulong) getuid ());
1428                     break;
1429                   }
1430                 if (bufsize > 32 * 1024)
1431                   {
1432                     g_warning ("getpwuid_r(): failed due to: %s.",
1433                                g_strerror (error));
1434                     break;
1435                   }
1436                 
1437                 bufsize *= 2;
1438               }
1439           }
1440         while (!pw);
1441 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1442         
1443         if (!pw)
1444           {
1445             setpwent ();
1446             pw = getpwuid (getuid ());
1447             endpwent ();
1448           }
1449         if (pw)
1450           {
1451             g_user_name = g_strdup (pw->pw_name);
1452
1453             if (pw->pw_gecos && *pw->pw_gecos != '\0') 
1454               {
1455                 gchar **gecos_fields;
1456                 gchar **name_parts;
1457
1458                 /* split the gecos field and substitute '&' */
1459                 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1460                 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1461                 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1462                 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1463                 g_strfreev (gecos_fields);
1464                 g_strfreev (name_parts);
1465               }
1466
1467             if (!g_home_dir)
1468               g_home_dir = g_strdup (pw->pw_dir);
1469           }
1470         g_free (buffer);
1471       }
1472       
1473 #else /* !HAVE_PWD_H */
1474       
1475 #ifdef G_OS_WIN32
1476       if (G_WIN32_HAVE_WIDECHAR_API ())
1477         {
1478           guint len = UNLEN+1;
1479           wchar_t buffer[UNLEN+1];
1480           
1481           if (GetUserNameW (buffer, (LPDWORD) &len))
1482             {
1483               g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1484               g_real_name = g_strdup (g_user_name);
1485             }
1486         }
1487       else
1488         {
1489           guint len = UNLEN+1;
1490           char buffer[UNLEN+1];
1491           
1492           if (GetUserNameA (buffer, (LPDWORD) &len))
1493             {
1494               g_user_name = g_locale_to_utf8 (buffer, -1, NULL, NULL, NULL);
1495               g_real_name = g_strdup (g_user_name);
1496             }
1497         }
1498 #endif /* G_OS_WIN32 */
1499
1500 #endif /* !HAVE_PWD_H */
1501
1502 #ifndef G_OS_WIN32
1503       if (!g_home_dir)
1504         g_home_dir = g_strdup (g_getenv ("HOME"));
1505 #endif
1506
1507 #ifdef __EMX__
1508       /* change '\\' in %HOME% to '/' */
1509       g_strdelimit (g_home_dir, "\\",'/');
1510 #endif
1511       if (!g_user_name)
1512         g_user_name = g_strdup ("somebody");
1513       if (!g_real_name)
1514         g_real_name = g_strdup ("Unknown");
1515
1516 #ifdef G_OS_WIN32
1517       g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1518       g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1519       g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1520
1521       if (!g_tmp_dir_cp)
1522         g_tmp_dir_cp = g_strdup ("\\");
1523       if (!g_user_name_cp)
1524         g_user_name_cp = g_strdup ("somebody");
1525       if (!g_real_name_cp)
1526         g_real_name_cp = g_strdup ("Unknown");
1527
1528       /* home_dir might be NULL, unlike tmp_dir, user_name and
1529        * real_name.
1530        */
1531       if (g_home_dir)
1532         g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1533       else
1534         g_home_dir_cp = NULL;
1535 #endif /* G_OS_WIN32 */
1536     }
1537 }
1538
1539 G_CONST_RETURN gchar*
1540 g_get_user_name (void)
1541 {
1542   G_LOCK (g_utils_global);
1543   if (!g_tmp_dir)
1544     g_get_any_init ();
1545   G_UNLOCK (g_utils_global);
1546   
1547   return g_user_name;
1548 }
1549
1550 G_CONST_RETURN gchar*
1551 g_get_real_name (void)
1552 {
1553   G_LOCK (g_utils_global);
1554   if (!g_tmp_dir)
1555     g_get_any_init ();
1556   G_UNLOCK (g_utils_global);
1557  
1558   return g_real_name;
1559 }
1560
1561 G_CONST_RETURN gchar*
1562 g_get_home_dir (void)
1563 {
1564   G_LOCK (g_utils_global);
1565   if (!g_tmp_dir)
1566     g_get_any_init ();
1567   G_UNLOCK (g_utils_global);
1568   
1569   return g_home_dir;
1570 }
1571
1572 /* Return a directory to be used to store temporary files. This is the
1573  * value of the TMPDIR, TMP or TEMP environment variables (they are
1574  * checked in that order). If none of those exist, use P_tmpdir from
1575  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
1576  * and C:\ on Windows.
1577  */
1578
1579 G_CONST_RETURN gchar*
1580 g_get_tmp_dir (void)
1581 {
1582   G_LOCK (g_utils_global);
1583   if (!g_tmp_dir)
1584     g_get_any_init ();
1585   G_UNLOCK (g_utils_global);
1586   
1587   return g_tmp_dir;
1588 }
1589
1590 G_LOCK_DEFINE_STATIC (g_prgname);
1591 static gchar *g_prgname = NULL;
1592
1593 gchar*
1594 g_get_prgname (void)
1595 {
1596   gchar* retval;
1597
1598   G_LOCK (g_prgname);
1599   retval = g_prgname;
1600   G_UNLOCK (g_prgname);
1601
1602   return retval;
1603 }
1604
1605 void
1606 g_set_prgname (const gchar *prgname)
1607 {
1608   G_LOCK (g_prgname);
1609   g_free (g_prgname);
1610   g_prgname = g_strdup (prgname);
1611   G_UNLOCK (g_prgname);
1612 }
1613
1614 G_LOCK_DEFINE_STATIC (g_application_name);
1615 static gchar *g_application_name = NULL;
1616
1617 /**
1618  * g_get_application_name:
1619  * 
1620  * Gets a human-readable name for the application, as set by
1621  * g_set_application_name(). This name should be localized if
1622  * possible, and is intended for display to the user.  Contrast with
1623  * g_get_prgname(), which gets a non-localized name. If
1624  * g_set_application_name() has not been called, returns the result of
1625  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1626  * been called).
1627  * 
1628  * Return value: human-readable application name. may return %NULL
1629  *
1630  * Since: 2.2
1631  **/
1632 G_CONST_RETURN gchar*
1633 g_get_application_name (void)
1634 {
1635   gchar* retval;
1636
1637   G_LOCK (g_application_name);
1638   retval = g_application_name;
1639   G_UNLOCK (g_application_name);
1640
1641   if (retval == NULL)
1642     return g_get_prgname ();
1643   
1644   return retval;
1645 }
1646
1647 /**
1648  * g_set_application_name:
1649  * @application_name: localized name of the application
1650  *
1651  * Sets a human-readable name for the application. This name should be
1652  * localized if possible, and is intended for display to the user.
1653  * Contrast with g_set_prgname(), which sets a non-localized name.
1654  * g_set_prgname() will be called automatically by gtk_init(),
1655  * but g_set_application_name() will not.
1656  *
1657  * Note that for thread safety reasons, this function can only
1658  * be called once.
1659  *
1660  * The application name will be used in contexts such as error messages,
1661  * or when displaying an application's name in the task list.
1662  * 
1663  **/
1664 void
1665 g_set_application_name (const gchar *application_name)
1666 {
1667   gboolean already_set = FALSE;
1668         
1669   G_LOCK (g_application_name);
1670   if (g_application_name)
1671     already_set = TRUE;
1672   else
1673     g_application_name = g_strdup (application_name);
1674   G_UNLOCK (g_application_name);
1675
1676   if (already_set)
1677     g_warning ("g_set_application() name called multiple times");
1678 }
1679
1680 /**
1681  * g_get_user_data_dir:
1682  * 
1683  * Returns a base directory in which to access application data such
1684  * as icons that is customized for a particular user.  
1685  *
1686  * On Unix platforms this is determined using the mechanisms described in
1687  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1688  * XDG Base Directory Specification</ulink>
1689  * 
1690  * Return value: a string owned by GLib that must not be modified 
1691  *               or freed.
1692  * Since: 2.6
1693  **/
1694 G_CONST_RETURN gchar*
1695 g_get_user_data_dir (void)
1696 {
1697   gchar *data_dir;  
1698
1699   G_LOCK (g_utils_global);
1700
1701   if (!g_user_data_dir)
1702     {
1703 #ifdef G_OS_WIN32
1704       data_dir = get_special_folder (CSIDL_PERSONAL);
1705 #else
1706       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1707 #endif
1708
1709       if (data_dir && data_dir[0])
1710         data_dir = g_strdup (data_dir);
1711       else
1712         {
1713           if (!g_tmp_dir)
1714             g_get_any_init ();
1715
1716           data_dir = g_build_filename (g_home_dir, ".local", 
1717                                        "share", NULL);
1718         }
1719
1720       g_user_data_dir = data_dir;
1721     }
1722   else
1723     data_dir = g_user_data_dir;
1724
1725   G_UNLOCK (g_utils_global);
1726
1727   return data_dir;
1728 }
1729
1730 /**
1731  * g_get_user_config_dir:
1732  * 
1733  * Returns a base directory in which to store user-specific application 
1734  * configuration information such as user preferences and settings. 
1735  *
1736  * On Unix platforms this is determined using the mechanisms described in
1737  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1738  * XDG Base Directory Specification</ulink>
1739  * 
1740  * Return value: a string owned by GLib that must not be modified 
1741  *               or freed.
1742  * Since: 2.6
1743  **/
1744 G_CONST_RETURN gchar*
1745 g_get_user_config_dir (void)
1746 {
1747   gchar *config_dir;  
1748
1749   G_LOCK (g_utils_global);
1750
1751   if (!g_user_config_dir)
1752     {
1753 #ifdef G_OS_WIN32
1754       config_dir = get_special_folder (CSIDL_APPDATA);
1755 #else
1756       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1757 #endif
1758
1759       if (config_dir && config_dir[0])
1760         config_dir = g_strdup (config_dir);
1761       else
1762         {
1763           if (!g_tmp_dir)
1764             g_get_any_init ();
1765           
1766           config_dir = g_build_filename (g_home_dir, ".config", NULL);
1767         }
1768       g_user_config_dir = config_dir;
1769     }
1770   else
1771     config_dir = g_user_config_dir;
1772
1773   G_UNLOCK (g_utils_global);
1774
1775   return config_dir;
1776 }
1777
1778 /**
1779  * g_get_user_cache_dir:
1780  * 
1781  * Returns a base directory in which to store non-essential, cached
1782  * data specific to particular user.
1783  *
1784  * On Unix platforms this is determined using the mechanisms described in
1785  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1786  * XDG Base Directory Specification</ulink>
1787  * 
1788  * Return value: a string owned by GLib that must not be modified 
1789  *               or freed.
1790  * Since: 2.6
1791  **/
1792 G_CONST_RETURN gchar*
1793 g_get_user_cache_dir (void)
1794 {
1795   gchar *cache_dir;  
1796
1797   G_LOCK (g_utils_global);
1798
1799   if (!g_user_cache_dir)
1800     {
1801 #ifdef G_OS_WIN32
1802       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1803 #else
1804       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1805 #endif
1806       if (cache_dir && cache_dir[0])
1807           cache_dir = g_strdup (cache_dir);
1808       else
1809         {
1810           if (!g_tmp_dir)
1811             g_get_any_init ();
1812
1813           cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1814         }
1815       g_user_cache_dir = cache_dir;
1816     }
1817   else
1818     cache_dir = g_user_cache_dir;
1819
1820   G_UNLOCK (g_utils_global);
1821
1822   return cache_dir;
1823 }
1824
1825 /**
1826  * g_get_system_data_dirs:
1827  * 
1828  * Returns an ordered list of base directories in which to access 
1829  * system-wide application data.
1830  *
1831  * On Unix platforms this is determined using the mechanisms described in
1832  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1833  * XDG Base Directory Specification</ulink>
1834  * 
1835  * Return value: a %NULL-terminated array of strings owned by GLib that must 
1836  *               not be modified or freed.
1837  * Since: 2.6
1838  **/
1839 G_CONST_RETURN gchar * G_CONST_RETURN * 
1840 g_get_system_data_dirs (void)
1841 {
1842   gchar *data_dirs, **data_dir_vector;
1843
1844   G_LOCK (g_utils_global);
1845
1846   if (!g_system_data_dirs)
1847     {
1848 #ifdef G_OS_WIN32
1849       data_dirs = g_strconcat (get_special_folder (CSIDL_COMMON_APPDATA),
1850                                G_SEARCHPATH_SEPARATOR_S,
1851                                get_special_folder (CSIDL_COMMON_DOCUMENTS),
1852                                NULL);
1853 #else
1854       data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1855
1856       if (!data_dirs || !data_dirs[0])
1857           data_dirs = "/usr/local/share/:/usr/share/";
1858 #endif
1859       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1860
1861       g_system_data_dirs = data_dir_vector;
1862     }
1863   else
1864     data_dir_vector = g_system_data_dirs;
1865
1866   G_UNLOCK (g_utils_global);
1867
1868   return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
1869 }
1870
1871 /**
1872  * g_get_system_config_dirs:
1873  * 
1874  * Returns an ordered list of base directories in which to access 
1875  * system-wide configuration information.
1876  *
1877  * On Unix platforms this is determined using the mechanisms described in
1878  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1879  * XDG Base Directory Specification</ulink>
1880  * 
1881  * Return value: a %NULL-terminated array of strings owned by GLib that must 
1882  *               not be modified or freed.
1883  * Since: 2.6
1884  **/
1885 G_CONST_RETURN gchar * G_CONST_RETURN *
1886 g_get_system_config_dirs (void)
1887 {
1888   gchar *conf_dirs, **conf_dir_vector;
1889
1890   G_LOCK (g_utils_global);
1891
1892   if (!g_system_config_dirs)
1893     {
1894 #ifdef G_OS_WIN32
1895       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1896 #else
1897       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
1898
1899       if (!conf_dirs || !conf_dirs[0])
1900           conf_dirs = "/etc/xdg";
1901 #endif
1902       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1903
1904       g_system_config_dirs = conf_dir_vector;
1905     }
1906   else
1907     conf_dir_vector = g_system_config_dirs;
1908   G_UNLOCK (g_utils_global);
1909
1910   return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
1911 }
1912
1913 static GHashTable *alias_table = NULL;
1914
1915 /* read an alias file for the locales */
1916 static void
1917 read_aliases (gchar *file)
1918 {
1919   FILE *fp;
1920   char buf[256];
1921   
1922   if (!alias_table)
1923     alias_table = g_hash_table_new (g_str_hash, g_str_equal);
1924   fp = fopen (file,"r");
1925   if (!fp)
1926     return;
1927   while (fgets (buf, 256, fp))
1928     {
1929       char *p, *q;
1930
1931       g_strstrip (buf);
1932
1933       /* Line is a comment */
1934       if ((buf[0] == '#') || (buf[0] == '\0'))
1935         continue;
1936
1937       /* Reads first column */
1938       for (p = buf, q = NULL; *p; p++) {
1939         if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
1940           *p = '\0';
1941           q = p+1;
1942           while ((*q == '\t') || (*q == ' ')) {
1943             q++;
1944           }
1945           break;
1946         }
1947       }
1948       /* The line only had one column */
1949       if (!q || *q == '\0')
1950         continue;
1951       
1952       /* Read second column */
1953       for (p = q; *p; p++) {
1954         if ((*p == '\t') || (*p == ' ')) {
1955           *p = '\0';
1956           break;
1957         }
1958       }
1959
1960       /* Add to alias table if necessary */
1961       if (!g_hash_table_lookup (alias_table, buf)) {
1962         g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
1963       }
1964     }
1965   fclose (fp);
1966 }
1967
1968 static char *
1969 unalias_lang (char *lang)
1970 {
1971   char *p;
1972   int i;
1973
1974   if (!alias_table)
1975     read_aliases ("/usr/share/locale/locale.alias");
1976
1977   i = 0;
1978   while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
1979     {
1980       lang = p;
1981       if (i++ == 30)
1982         {
1983           static gboolean said_before = FALSE;
1984           if (!said_before)
1985             g_warning ("Too many alias levels for a locale, "
1986                        "may indicate a loop");
1987           said_before = TRUE;
1988           return lang;
1989         }
1990     }
1991   return lang;
1992 }
1993
1994 /* Mask for components of locale spec. The ordering here is from
1995  * least significant to most significant
1996  */
1997 enum
1998 {
1999   COMPONENT_CODESET =   1 << 0,
2000   COMPONENT_TERRITORY = 1 << 1,
2001   COMPONENT_MODIFIER =  1 << 2
2002 };
2003
2004 /* Break an X/Open style locale specification into components
2005  */
2006 static guint
2007 explode_locale (const gchar *locale,
2008                 gchar      **language, 
2009                 gchar      **territory, 
2010                 gchar      **codeset, 
2011                 gchar      **modifier)
2012 {
2013   const gchar *uscore_pos;
2014   const gchar *at_pos;
2015   const gchar *dot_pos;
2016
2017   guint mask = 0;
2018
2019   uscore_pos = strchr (locale, '_');
2020   dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2021   at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2022
2023   if (at_pos)
2024     {
2025       mask |= COMPONENT_MODIFIER;
2026       *modifier = g_strdup (at_pos);
2027     }
2028   else
2029     at_pos = locale + strlen (locale);
2030
2031   if (dot_pos)
2032     {
2033       mask |= COMPONENT_CODESET;
2034       *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2035     }
2036   else
2037     dot_pos = at_pos;
2038
2039   if (uscore_pos)
2040     {
2041       mask |= COMPONENT_TERRITORY;
2042       *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2043     }
2044   else
2045     uscore_pos = dot_pos;
2046
2047   *language = g_strndup (locale, uscore_pos - locale);
2048
2049   return mask;
2050 }
2051
2052 /*
2053  * Compute all interesting variants for a given locale name -
2054  * by stripping off different components of the value.
2055  *
2056  * For simplicity, we assume that the locale is in
2057  * X/Open format: language[_territory][.codeset][@modifier]
2058  *
2059  * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2060  *       as well. We could just copy the code from glibc wholesale
2061  *       but it is big, ugly, and complicated, so I'm reluctant
2062  *       to do so when this should handle 99% of the time...
2063  */
2064 GSList *
2065 _g_compute_locale_variants (const gchar *locale)
2066 {
2067   GSList *retval = NULL;
2068
2069   gchar *language;
2070   gchar *territory;
2071   gchar *codeset;
2072   gchar *modifier;
2073
2074   guint mask;
2075   guint i;
2076
2077   g_return_val_if_fail (locale != NULL, NULL);
2078
2079   mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2080
2081   /* Iterate through all possible combinations, from least attractive
2082    * to most attractive.
2083    */
2084   for (i = 0; i <= mask; i++)
2085     if ((i & ~mask) == 0)
2086       {
2087         gchar *val = g_strconcat (language,
2088                                   (i & COMPONENT_TERRITORY) ? territory : "",
2089                                   (i & COMPONENT_CODESET) ? codeset : "",
2090                                   (i & COMPONENT_MODIFIER) ? modifier : "",
2091                                   NULL);
2092         retval = g_slist_prepend (retval, val);
2093       }
2094
2095   g_free (language);
2096   if (mask & COMPONENT_CODESET)
2097     g_free (codeset);
2098   if (mask & COMPONENT_TERRITORY)
2099     g_free (territory);
2100   if (mask & COMPONENT_MODIFIER)
2101     g_free (modifier);
2102
2103   return retval;
2104 }
2105
2106 /* The following is (partly) taken from the gettext package.
2107    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
2108
2109 static const gchar *
2110 guess_category_value (const gchar *category_name)
2111 {
2112   const gchar *retval;
2113
2114   /* The highest priority value is the `LANGUAGE' environment
2115      variable.  This is a GNU extension.  */
2116   retval = g_getenv ("LANGUAGE");
2117   if ((retval != NULL) && (retval[0] != '\0'))
2118     return retval;
2119
2120   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
2121      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
2122      systems this can be done by the `setlocale' function itself.  */
2123
2124   /* Setting of LC_ALL overwrites all other.  */
2125   retval = g_getenv ("LC_ALL");  
2126   if ((retval != NULL) && (retval[0] != '\0'))
2127     return retval;
2128
2129   /* Next comes the name of the desired category.  */
2130   retval = g_getenv (category_name);
2131   if ((retval != NULL) && (retval[0] != '\0'))
2132     return retval;
2133
2134   /* Last possibility is the LANG environment variable.  */
2135   retval = g_getenv ("LANG");
2136   if ((retval != NULL) && (retval[0] != '\0'))
2137     return retval;
2138
2139 #ifdef G_PLATFORM_WIN32
2140   /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2141    * LANG, which we already did above. Oh well. The main point of
2142    * calling g_win32_getlocale() is to get the thread's locale as used
2143    * by Windows and the Microsoft C runtime (in the "English_United
2144    * States" format) translated into the Unixish format.
2145    */
2146   retval = g_win32_getlocale ();
2147   if ((retval != NULL) && (retval[0] != '\0'))
2148     return retval;
2149 #endif  
2150
2151   return NULL;
2152 }
2153
2154 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2155
2156 struct _GLanguageNamesCache {
2157   gchar *languages;
2158   gchar **language_names;
2159 };
2160
2161 static void
2162 language_names_cache_free (gpointer data)
2163 {
2164   GLanguageNamesCache *cache = data;
2165   g_free (cache->languages);
2166   g_strfreev (cache->language_names);
2167   g_free (cache);
2168 }
2169
2170 /**
2171  * g_get_language_names:
2172  * 
2173  * Computes a list of applicable locale names, which can be used to 
2174  * e.g. construct locale-dependent filenames or search paths. The returned 
2175  * list is sorted from most desirable to least desirable and always contains 
2176  * the default locale "C".
2177  *
2178  * For example, if LANGUAGE=de:en_US, then the returned list is
2179  * "de", "en_US", "en", "C".
2180  *
2181  * This function consults the environment variables <envar>LANGUAGE</envar>, 
2182  * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar> 
2183  * to find the list of locales specified by the user.
2184  * 
2185  * Return value: a %NULL-terminated array of strings owned by GLib 
2186  *    that must not be modified or freed.
2187  *
2188  * Since: 2.6
2189  **/
2190 G_CONST_RETURN gchar * G_CONST_RETURN * 
2191 g_get_language_names (void)
2192 {
2193   static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2194   GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2195   const gchar *value;
2196
2197   if (!cache)
2198     {
2199       cache = g_new0 (GLanguageNamesCache, 1);
2200       g_static_private_set (&cache_private, cache, language_names_cache_free);
2201     }
2202
2203   value = guess_category_value ("LC_MESSAGES");
2204   if (!value)
2205     value = "C";
2206
2207   if (!(cache->languages && strcmp (cache->languages, value) == 0))
2208     {
2209       gchar **languages;
2210       gchar **alist, **a;
2211       GSList *list, *l;
2212       gint i;
2213
2214       g_free (cache->languages);
2215       g_strfreev (cache->language_names);
2216       cache->languages = g_strdup (value);
2217
2218       alist = g_strsplit (value, ":", 0);
2219       list = NULL;
2220       for (a = alist; *a; a++)
2221         {
2222           gchar *b = unalias_lang (*a);
2223           list = g_slist_concat (list, _g_compute_locale_variants (b));
2224         }
2225       g_strfreev (alist);
2226       list = g_slist_append (list, g_strdup ("C"));
2227
2228       cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
2229       for (l = list, i = 0; l; l = l->next, i++)
2230         languages[i] = l->data;
2231       languages[i] = NULL;
2232
2233       g_slist_free (list);
2234     }
2235
2236   return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
2237 }
2238
2239 guint
2240 g_direct_hash (gconstpointer v)
2241 {
2242   return GPOINTER_TO_UINT (v);
2243 }
2244
2245 gboolean
2246 g_direct_equal (gconstpointer v1,
2247                 gconstpointer v2)
2248 {
2249   return v1 == v2;
2250 }
2251
2252 gboolean
2253 g_int_equal (gconstpointer v1,
2254              gconstpointer v2)
2255 {
2256   return *((const gint*) v1) == *((const gint*) v2);
2257 }
2258
2259 guint
2260 g_int_hash (gconstpointer v)
2261 {
2262   return *(const gint*) v;
2263 }
2264
2265 /**
2266  * g_nullify_pointer:
2267  * @nullify_location: the memory address of the pointer.
2268  * 
2269  * Set the pointer at the specified location to %NULL.
2270  **/
2271 void
2272 g_nullify_pointer (gpointer *nullify_location)
2273 {
2274   g_return_if_fail (nullify_location != NULL);
2275
2276   *nullify_location = NULL;
2277 }
2278
2279 /**
2280  * g_get_codeset:
2281  * 
2282  * Get the codeset for the current locale.
2283  * 
2284  * Return value: a newly allocated string containing the name
2285  * of the codeset. This string must be freed with g_free().
2286  **/
2287 gchar *
2288 g_get_codeset (void)
2289 {
2290   const gchar *charset;
2291
2292   g_get_charset (&charset);
2293
2294   return g_strdup (charset);
2295 }
2296
2297 /* This is called from g_thread_init(). It's used to
2298  * initialize some static data in a threadsafe way.
2299  */
2300 void
2301 _g_utils_thread_init (void)
2302 {
2303   g_get_language_names ();
2304 }
2305
2306 #ifdef ENABLE_NLS
2307
2308 #include <libintl.h>
2309
2310 #ifdef G_PLATFORM_WIN32
2311
2312 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
2313
2314 static const gchar *
2315 _glib_get_locale_dir (void)
2316 {
2317   static const gchar *cache = NULL;
2318   if (cache == NULL)
2319     cache = g_win32_get_package_installation_subdirectory
2320       (GETTEXT_PACKAGE, dll_name, "lib\\locale");
2321
2322   return cache;
2323 }
2324
2325 #undef GLIB_LOCALE_DIR
2326 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
2327
2328 #endif /* G_PLATFORM_WIN32 */
2329
2330 G_CONST_RETURN gchar *
2331 _glib_gettext (const gchar *str)
2332 {
2333   static gboolean _glib_gettext_initialized = FALSE;
2334
2335   if (!_glib_gettext_initialized)
2336     {
2337       bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
2338 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2339       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2340 #    endif
2341       _glib_gettext_initialized = TRUE;
2342     }
2343   
2344   return dgettext (GETTEXT_PACKAGE, str);
2345 }
2346
2347 #endif /* ENABLE_NLS */
2348
2349 #ifdef G_OS_WIN32
2350
2351 /* Binary compatibility versions. Not for newly compiled code. */
2352
2353 #undef g_find_program_in_path
2354
2355 gchar*
2356 g_find_program_in_path (const gchar *program)
2357 {
2358   gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2359   gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2360   gchar *retval;
2361
2362   g_free (utf8_program);
2363   if (utf8_retval == NULL)
2364     return NULL;
2365   retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2366   g_free (utf8_retval);
2367
2368   return retval;
2369 }
2370
2371 #undef g_get_current_dir
2372
2373 gchar*
2374 g_get_current_dir (void)
2375 {
2376   gchar *utf8_dir = g_get_current_dir_utf8 ();
2377   gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2378   g_free (utf8_dir);
2379   return dir;
2380 }
2381
2382 #undef g_getenv
2383
2384 G_CONST_RETURN gchar*
2385 g_getenv (const gchar *variable)
2386 {
2387   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2388   const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
2389   gchar *value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
2390   GQuark quark = g_quark_from_string (value);
2391
2392   g_free (utf8_variable);
2393   g_free (value);
2394
2395   return g_quark_to_string (quark);
2396 }
2397
2398 #undef g_setenv
2399
2400 gboolean
2401 g_setenv (const gchar *variable, 
2402           const gchar *value, 
2403           gboolean     overwrite)
2404 {
2405   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2406   gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
2407   gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
2408
2409   g_free (utf8_variable);
2410   g_free (utf8_value);
2411
2412   return retval;
2413 }
2414
2415 #undef g_unsetenv
2416
2417 void
2418 g_unsetenv (const gchar *variable)
2419 {
2420   gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2421
2422   g_unsetenv_utf8 (utf8_variable);
2423
2424   g_free (utf8_variable);
2425 }
2426
2427 #undef g_get_user_name
2428
2429 G_CONST_RETURN gchar*
2430 g_get_user_name (void)
2431 {
2432   G_LOCK (g_utils_global);
2433   if (!g_tmp_dir)
2434     g_get_any_init ();
2435   G_UNLOCK (g_utils_global);
2436   
2437   return g_user_name_cp;
2438 }
2439
2440 #undef g_get_real_name
2441
2442 G_CONST_RETURN gchar*
2443 g_get_real_name (void)
2444 {
2445   G_LOCK (g_utils_global);
2446   if (!g_tmp_dir)
2447     g_get_any_init ();
2448   G_UNLOCK (g_utils_global);
2449  
2450   return g_real_name_cp;
2451 }
2452
2453 #undef g_get_home_dir
2454
2455 G_CONST_RETURN gchar*
2456 g_get_home_dir (void)
2457 {
2458   G_LOCK (g_utils_global);
2459   if (!g_tmp_dir)
2460     g_get_any_init ();
2461   G_UNLOCK (g_utils_global);
2462
2463   return g_home_dir_cp;
2464 }
2465
2466 #undef g_get_tmp_dir
2467
2468 G_CONST_RETURN gchar*
2469 g_get_tmp_dir (void)
2470 {
2471   G_LOCK (g_utils_global);
2472   if (!g_tmp_dir)
2473     g_get_any_init ();
2474   G_UNLOCK (g_utils_global);
2475
2476   return g_tmp_dir_cp;
2477 }
2478
2479 #endif