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