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