updated [and finally fixed my script to produce ready to go de-in(ed)
[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             buffer = g_malloc (bufsize);
1065             errno = 0;
1066             
1067 #    ifdef HAVE_POSIX_GETPWUID_R
1068             error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1069             error = error < 0 ? errno : error;
1070 #    else /* HAVE_NONPOSIX_GETPWUID_R */
1071        /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1072 #      if defined(_AIX) || defined(__hpux)
1073             error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1074             pw = error == 0 ? &pwd : NULL;
1075 #      else /* !_AIX */
1076             pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1077             error = pw ? 0 : errno;
1078 #      endif /* !_AIX */            
1079 #    endif /* HAVE_NONPOSIX_GETPWUID_R */
1080             
1081             if (!pw)
1082               {
1083                 /* we bail out prematurely if the user id can't be found
1084                  * (should be pretty rare case actually), or if the buffer
1085                  * should be sufficiently big and lookups are still not
1086                  * successfull.
1087                  */
1088                 if (error == 0 || error == ENOENT)
1089                   {
1090                     g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1091                                (gulong) getuid ());
1092                     break;
1093                   }
1094                 if (bufsize > 32 * 1024)
1095                   {
1096                     g_warning ("getpwuid_r(): failed due to: %s.",
1097                                g_strerror (error));
1098                     break;
1099                   }
1100                 
1101                 bufsize *= 2;
1102               }
1103           }
1104         while (!pw);
1105 #  endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1106         
1107         if (!pw)
1108           {
1109             setpwent ();
1110             pw = getpwuid (getuid ());
1111             endpwent ();
1112           }
1113         if (pw)
1114           {
1115             g_user_name = g_strdup (pw->pw_name);
1116
1117             if (pw->pw_gecos && *pw->pw_gecos != '\0') 
1118               {
1119                 gchar **gecos_fields;
1120                 gchar **name_parts;
1121
1122                 /* split the gecos field and substitute '&' */
1123                 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1124                 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1125                 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1126                 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1127                 g_strfreev (gecos_fields);
1128                 g_strfreev (name_parts);
1129               }
1130
1131             if (!g_home_dir)
1132               g_home_dir = g_strdup (pw->pw_dir);
1133           }
1134         g_free (buffer);
1135       }
1136       
1137 #else /* !HAVE_PWD_H */
1138       
1139 #  ifdef G_OS_WIN32
1140       {
1141         guint len = UNLEN+1;
1142         gchar buffer[UNLEN+1];
1143         
1144         if (GetUserName ((LPTSTR) buffer, (LPDWORD) &len))
1145           {
1146             g_user_name = g_strdup (buffer);
1147             g_real_name = g_strdup (buffer);
1148           }
1149       }
1150 #  endif /* G_OS_WIN32 */
1151
1152 #endif /* !HAVE_PWD_H */
1153
1154       if (!g_home_dir)
1155         g_home_dir = g_strdup (g_getenv ("HOME"));
1156       
1157 #ifdef __EMX__
1158       /* change '\\' in %HOME% to '/' */
1159       g_strdelimit (g_home_dir, "\\",'/');
1160 #endif
1161       if (!g_user_name)
1162         g_user_name = g_strdup ("somebody");
1163       if (!g_real_name)
1164         g_real_name = g_strdup ("Unknown");
1165     }
1166 }
1167
1168 G_CONST_RETURN gchar*
1169 g_get_user_name (void)
1170 {
1171   G_LOCK (g_utils_global);
1172   if (!g_tmp_dir)
1173     g_get_any_init ();
1174   G_UNLOCK (g_utils_global);
1175   
1176   return g_user_name;
1177 }
1178
1179 G_CONST_RETURN gchar*
1180 g_get_real_name (void)
1181 {
1182   G_LOCK (g_utils_global);
1183   if (!g_tmp_dir)
1184     g_get_any_init ();
1185   G_UNLOCK (g_utils_global);
1186  
1187   return g_real_name;
1188 }
1189
1190 G_CONST_RETURN gchar*
1191 g_get_home_dir (void)
1192 {
1193   G_LOCK (g_utils_global);
1194   if (!g_tmp_dir)
1195     g_get_any_init ();
1196   G_UNLOCK (g_utils_global);
1197   
1198   return g_home_dir;
1199 }
1200
1201 #ifdef G_OS_WIN32
1202
1203 #undef g_get_home_dir
1204
1205 G_CONST_RETURN gchar*
1206 g_get_home_dir (void)
1207 {
1208   static gchar *home_dir = NULL;
1209
1210   G_LOCK (g_utils_global);
1211   if (!g_tmp_dir)
1212     g_get_any_init ();
1213   if (!home_dir && g_home_dir)
1214     home_dir = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1215   G_UNLOCK (g_utils_global);
1216
1217   return home_dir;
1218 }
1219
1220 #endif
1221
1222 /* Return a directory to be used to store temporary files. This is the
1223  * value of the TMPDIR, TMP or TEMP environment variables (they are
1224  * checked in that order). If none of those exist, use P_tmpdir from
1225  * stdio.h.  If that isn't defined, return "/tmp" on POSIXly systems,
1226  * and C:\ on Windows.
1227  */
1228
1229 G_CONST_RETURN gchar*
1230 g_get_tmp_dir (void)
1231 {
1232   G_LOCK (g_utils_global);
1233   if (!g_tmp_dir)
1234     g_get_any_init ();
1235   G_UNLOCK (g_utils_global);
1236   
1237   return g_tmp_dir;
1238 }
1239
1240 #ifdef G_OS_WIN32
1241
1242 #undef g_get_tmp_dir
1243
1244 G_CONST_RETURN gchar*
1245 g_get_tmp_dir (void)
1246 {
1247   static gchar *tmp_dir = NULL;
1248
1249   G_LOCK (g_utils_global);
1250   if (!g_tmp_dir)
1251     g_get_any_init ();
1252   if (!tmp_dir)
1253     tmp_dir = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1254
1255   if (tmp_dir == NULL)
1256     tmp_dir = "C:\\";
1257   G_UNLOCK (g_utils_global);
1258
1259   return tmp_dir;
1260 }
1261
1262 #endif
1263
1264 G_LOCK_DEFINE_STATIC (g_prgname);
1265 static gchar *g_prgname = NULL;
1266
1267 gchar*
1268 g_get_prgname (void)
1269 {
1270   gchar* retval;
1271
1272   G_LOCK (g_prgname);
1273   retval = g_prgname;
1274   G_UNLOCK (g_prgname);
1275
1276   return retval;
1277 }
1278
1279 void
1280 g_set_prgname (const gchar *prgname)
1281 {
1282   G_LOCK (g_prgname);
1283   g_free (g_prgname);
1284   g_prgname = g_strdup (prgname);
1285   G_UNLOCK (g_prgname);
1286 }
1287
1288 G_LOCK_DEFINE_STATIC (g_application_name);
1289 static gchar *g_application_name = NULL;
1290
1291 /**
1292  * g_get_application_name:
1293  * 
1294  * Gets a human-readable name for the application, as set by
1295  * g_set_application_name(). This name should be localized if
1296  * possible, and is intended for display to the user.  Contrast with
1297  * g_get_prgname(), which gets a non-localized name. If
1298  * g_set_application_name() has not been called, returns the result of
1299  * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1300  * been called).
1301  * 
1302  * Return value: human-readable application name. may return %NULL
1303  *
1304  * Since: 2.2
1305  **/
1306 G_CONST_RETURN gchar*
1307 g_get_application_name (void)
1308 {
1309   gchar* retval;
1310
1311   G_LOCK (g_application_name);
1312   retval = g_application_name;
1313   G_UNLOCK (g_application_name);
1314
1315   if (retval == NULL)
1316     return g_get_prgname ();
1317   
1318   return retval;
1319 }
1320
1321 /**
1322  * g_set_application_name:
1323  * @application_name: localized name of the application
1324  *
1325  * Sets a human-readable name for the application. This name should be
1326  * localized if possible, and is intended for display to the user.
1327  * Contrast with g_set_prgname(), which sets a non-localized name.
1328  * g_set_prgname() will be called automatically by gtk_init(),
1329  * but g_set_application_name() will not.
1330  *
1331  * Note that for thread safety reasons, this function can only
1332  * be called once.
1333  *
1334  * The application name will be used in contexts such as error messages,
1335  * or when displaying an application's name in the task list.
1336  * 
1337  **/
1338 void
1339 g_set_application_name (const gchar *application_name)
1340 {
1341   gboolean already_set = FALSE;
1342         
1343   G_LOCK (g_application_name);
1344   if (g_application_name)
1345     already_set = TRUE;
1346   else
1347     g_application_name = g_strdup (application_name);
1348   G_UNLOCK (g_application_name);
1349
1350   if (already_set)
1351     g_warning ("g_set_application() name called multiple times");
1352 }
1353
1354 /**
1355  * g_get_user_data_dir:
1356  * 
1357  * Returns a base directory in which to access application data such
1358  * as icons that is customized for a particular user.  
1359  *
1360  * On Unix platforms this is determined using the mechanisms described in
1361  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1362  * XDG Base Directory Specification</ulink>
1363  * 
1364  * Return value: a string owned by GLib that must not be modified 
1365  *               or freed.
1366  * Since: 2.6
1367  **/
1368 G_CONST_RETURN gchar*
1369 g_get_user_data_dir (void)
1370 {
1371   gchar *data_dir;  
1372
1373   G_LOCK (g_utils_global);
1374
1375   if (!g_user_data_dir)
1376     {
1377 #ifdef G_OS_WIN32
1378       data_dir = get_special_folder (CSIDL_PERSONAL);
1379 #else
1380       data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1381 #endif
1382
1383       if (data_dir && data_dir[0])
1384         data_dir = g_strdup (data_dir);
1385       else
1386         {
1387           if (!g_tmp_dir)
1388             g_get_any_init ();
1389
1390           data_dir = g_build_filename (g_home_dir, ".local", 
1391                                        "share", NULL);
1392         }
1393
1394       g_user_data_dir = data_dir;
1395     }
1396   else
1397     data_dir = g_user_data_dir;
1398
1399   G_UNLOCK (g_utils_global);
1400
1401   return data_dir;
1402 }
1403
1404 /**
1405  * g_get_user_config_dir:
1406  * 
1407  * Returns a base directory in which to store user-specific application 
1408  * configuration information such as user preferences and settings. 
1409  *
1410  * On Unix platforms this is determined using the mechanisms described in
1411  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1412  * XDG Base Directory Specification</ulink>
1413  * 
1414  * Return value: a string owned by GLib that must not be modified 
1415  *               or freed.
1416  * Since: 2.6
1417  **/
1418 G_CONST_RETURN gchar*
1419 g_get_user_config_dir (void)
1420 {
1421   gchar *config_dir;  
1422
1423   G_LOCK (g_utils_global);
1424
1425   if (!g_user_config_dir)
1426     {
1427 #ifdef G_OS_WIN32
1428       config_dir = get_special_folder (CSIDL_APPDATA);
1429 #else
1430       config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1431 #endif
1432
1433       if (config_dir && config_dir[0])
1434         config_dir = g_strdup (config_dir);
1435       else
1436         {
1437           if (!g_tmp_dir)
1438             g_get_any_init ();
1439           
1440           config_dir = g_build_filename (g_home_dir, ".config", NULL);
1441         }
1442       g_user_config_dir = config_dir;
1443     }
1444   else
1445     config_dir = g_user_config_dir;
1446
1447   G_UNLOCK (g_utils_global);
1448
1449   return config_dir;
1450 }
1451
1452 /**
1453  * g_get_user_cache_dir:
1454  * 
1455  * Returns a base directory in which to store non-essential, cached
1456  * data specific to particular user.
1457  *
1458  * On Unix platforms this is determined using the mechanisms described in
1459  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1460  * XDG Base Directory Specification</ulink>
1461  * 
1462  * Return value: a string owned by GLib that must not be modified 
1463  *               or freed.
1464  * Since: 2.6
1465  **/
1466 G_CONST_RETURN gchar*
1467 g_get_user_cache_dir (void)
1468 {
1469   gchar *cache_dir;  
1470
1471   G_LOCK (g_utils_global);
1472
1473   if (!g_user_cache_dir)
1474     {
1475 #ifdef G_OS_WIN32
1476       cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1477 #else
1478       cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1479 #endif
1480       if (cache_dir && cache_dir[0])
1481           cache_dir = g_strdup (cache_dir);
1482       else
1483         {
1484           if (!g_tmp_dir)
1485             g_get_any_init ();
1486
1487           cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1488         }
1489       g_user_cache_dir = cache_dir;
1490     }
1491   else
1492     cache_dir = g_user_cache_dir;
1493
1494   G_UNLOCK (g_utils_global);
1495
1496   return cache_dir;
1497 }
1498
1499 /**
1500  * g_get_system_data_dirs:
1501  * 
1502  * Returns an ordered list of base directories in which to access 
1503  * system-wide application data.
1504  *
1505  * On Unix platforms this is determined using the mechanisms described in
1506  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1507  * XDG Base Directory Specification</ulink>
1508  * 
1509  * Return value: a %NULL-terminated array of strings owned by GLib that must 
1510  *               not be modified or freed.
1511  * Since: 2.6
1512  **/
1513 G_CONST_RETURN gchar * G_CONST_RETURN * 
1514 g_get_system_data_dirs (void)
1515 {
1516   gchar *data_dirs, **data_dir_vector;
1517
1518   G_LOCK (g_utils_global);
1519
1520   if (!g_system_data_dirs)
1521     {
1522 #ifdef G_OS_WIN32
1523       data_dirs = g_strconcat (get_special_folder (CSIDL_COMMON_APPDATA),
1524                                G_SEARCHPATH_SEPARATOR_S,
1525                                get_special_folder (CSIDL_COMMON_DOCUMENTS),
1526                                NULL);
1527 #else
1528       data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1529
1530       if (!data_dirs || !data_dirs[0])
1531           data_dirs = "/usr/local/share/:/usr/share/";
1532 #endif
1533       data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1534
1535       g_system_data_dirs = data_dir_vector;
1536     }
1537   else
1538     data_dir_vector = g_system_data_dirs;
1539
1540   G_UNLOCK (g_utils_global);
1541
1542   return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
1543 }
1544
1545 /**
1546  * g_get_system_config_dirs:
1547  * 
1548  * Returns an ordered list of base directories in which to access 
1549  * system-wide configuration information.
1550  *
1551  * On Unix platforms this is determined using the mechanisms described in
1552  * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1553  * XDG Base Directory Specification</ulink>
1554  * 
1555  * Return value: a %NULL-terminated array of strings owned by GLib that must 
1556  *               not be modified or freed.
1557  * Since: 2.6
1558  **/
1559 G_CONST_RETURN gchar * G_CONST_RETURN *
1560 g_get_system_config_dirs (void)
1561 {
1562   gchar *conf_dirs, **conf_dir_vector;
1563
1564   G_LOCK (g_utils_global);
1565
1566   if (!g_system_config_dirs)
1567     {
1568 #ifdef G_OS_WIN32
1569       conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1570 #else
1571       conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
1572
1573       if (!conf_dirs || !conf_dirs[0])
1574           conf_dirs = "/etc/xdg";
1575 #endif
1576       conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1577     }
1578   else
1579     conf_dir_vector = g_system_config_dirs;
1580   G_UNLOCK (g_utils_global);
1581
1582   return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
1583 }
1584
1585 static GHashTable *alias_table = NULL;
1586
1587 /* read an alias file for the locales */
1588 static void
1589 read_aliases (gchar *file)
1590 {
1591   FILE *fp;
1592   char buf[256];
1593   
1594   if (!alias_table)
1595     alias_table = g_hash_table_new (g_str_hash, g_str_equal);
1596   fp = fopen (file,"r");
1597   if (!fp)
1598     return;
1599   while (fgets (buf, 256, fp))
1600     {
1601       char *p, *q;
1602
1603       g_strstrip (buf);
1604
1605       /* Line is a comment */
1606       if ((buf[0] == '#') || (buf[0] == '\0'))
1607         continue;
1608
1609       /* Reads first column */
1610       for (p = buf, q = NULL; *p; p++) {
1611         if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
1612           *p = '\0';
1613           q = p+1;
1614           while ((*q == '\t') || (*q == ' ')) {
1615             q++;
1616           }
1617           break;
1618         }
1619       }
1620       /* The line only had one column */
1621       if (!q || *q == '\0')
1622         continue;
1623       
1624       /* Read second column */
1625       for (p = q; *p; p++) {
1626         if ((*p == '\t') || (*p == ' ')) {
1627           *p = '\0';
1628           break;
1629         }
1630       }
1631
1632       /* Add to alias table if necessary */
1633       if (!g_hash_table_lookup (alias_table, buf)) {
1634         g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
1635       }
1636     }
1637   fclose (fp);
1638 }
1639
1640 static char *
1641 unalias_lang (char *lang)
1642 {
1643   char *p;
1644   int i;
1645
1646   if (!alias_table)
1647     read_aliases ("/usr/share/locale/locale.alias");
1648
1649   i = 0;
1650   while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
1651     {
1652       lang = p;
1653       if (i++ == 30)
1654         {
1655           static gboolean said_before = FALSE;
1656           if (!said_before)
1657             g_warning ("Too many alias levels for a locale, "
1658                        "may indicate a loop");
1659           said_before = TRUE;
1660           return lang;
1661         }
1662     }
1663   return lang;
1664 }
1665
1666 /* Mask for components of locale spec. The ordering here is from
1667  * least significant to most significant
1668  */
1669 enum
1670 {
1671   COMPONENT_CODESET =   1 << 0,
1672   COMPONENT_TERRITORY = 1 << 1,
1673   COMPONENT_MODIFIER =  1 << 2
1674 };
1675
1676 /* Break an X/Open style locale specification into components
1677  */
1678 static guint
1679 explode_locale (const gchar *locale,
1680                 gchar      **language, 
1681                 gchar      **territory, 
1682                 gchar      **codeset, 
1683                 gchar      **modifier)
1684 {
1685   const gchar *uscore_pos;
1686   const gchar *at_pos;
1687   const gchar *dot_pos;
1688
1689   guint mask = 0;
1690
1691   uscore_pos = strchr (locale, '_');
1692   dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
1693   at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
1694
1695   if (at_pos)
1696     {
1697       mask |= COMPONENT_MODIFIER;
1698       *modifier = g_strdup (at_pos);
1699     }
1700   else
1701     at_pos = locale + strlen (locale);
1702
1703   if (dot_pos)
1704     {
1705       mask |= COMPONENT_CODESET;
1706       *codeset = g_strndup (dot_pos, at_pos - dot_pos);
1707     }
1708   else
1709     dot_pos = at_pos;
1710
1711   if (uscore_pos)
1712     {
1713       mask |= COMPONENT_TERRITORY;
1714       *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
1715     }
1716   else
1717     uscore_pos = dot_pos;
1718
1719   *language = g_strndup (locale, uscore_pos - locale);
1720
1721   return mask;
1722 }
1723
1724 /*
1725  * Compute all interesting variants for a given locale name -
1726  * by stripping off different components of the value.
1727  *
1728  * For simplicity, we assume that the locale is in
1729  * X/Open format: language[_territory][.codeset][@modifier]
1730  *
1731  * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
1732  *       as well. We could just copy the code from glibc wholesale
1733  *       but it is big, ugly, and complicated, so I'm reluctant
1734  *       to do so when this should handle 99% of the time...
1735  */
1736 GSList *
1737 _g_compute_locale_variants (const gchar *locale)
1738 {
1739   GSList *retval = NULL;
1740
1741   gchar *language;
1742   gchar *territory;
1743   gchar *codeset;
1744   gchar *modifier;
1745
1746   guint mask;
1747   guint i;
1748
1749   g_return_val_if_fail (locale != NULL, NULL);
1750
1751   mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
1752
1753   /* Iterate through all possible combinations, from least attractive
1754    * to most attractive.
1755    */
1756   for (i = 0; i <= mask; i++)
1757     if ((i & ~mask) == 0)
1758       {
1759         gchar *val = g_strconcat (language,
1760                                   (i & COMPONENT_TERRITORY) ? territory : "",
1761                                   (i & COMPONENT_CODESET) ? codeset : "",
1762                                   (i & COMPONENT_MODIFIER) ? modifier : "",
1763                                   NULL);
1764         retval = g_slist_prepend (retval, val);
1765       }
1766
1767   g_free (language);
1768   if (mask & COMPONENT_CODESET)
1769     g_free (codeset);
1770   if (mask & COMPONENT_TERRITORY)
1771     g_free (territory);
1772   if (mask & COMPONENT_MODIFIER)
1773     g_free (modifier);
1774
1775   return retval;
1776 }
1777
1778 /* The following is (partly) taken from the gettext package.
1779    Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc.  */
1780
1781 static const gchar *
1782 guess_category_value (const gchar *category_name)
1783 {
1784   const gchar *retval;
1785
1786   /* The highest priority value is the `LANGUAGE' environment
1787      variable.  This is a GNU extension.  */
1788   retval = g_getenv ("LANGUAGE");
1789   if ((retval != NULL) && (retval[0] != '\0'))
1790     return retval;
1791
1792   /* `LANGUAGE' is not set.  So we have to proceed with the POSIX
1793      methods of looking to `LC_ALL', `LC_xxx', and `LANG'.  On some
1794      systems this can be done by the `setlocale' function itself.  */
1795
1796   /* Setting of LC_ALL overwrites all other.  */
1797   retval = g_getenv ("LC_ALL");  
1798   if ((retval != NULL) && (retval[0] != '\0'))
1799     return retval;
1800
1801   /* Next comes the name of the desired category.  */
1802   retval = g_getenv (category_name);
1803   if ((retval != NULL) && (retval[0] != '\0'))
1804     return retval;
1805
1806   /* Last possibility is the LANG environment variable.  */
1807   retval = g_getenv ("LANG");
1808   if ((retval != NULL) && (retval[0] != '\0'))
1809     return retval;
1810
1811 #ifdef G_PLATFORM_WIN32
1812   /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
1813    * LANG, which we already did above. Oh well. The main point of
1814    * calling g_win32_getlocale() is to get the thread's locale as used
1815    * by Windows and the Microsoft C runtime (in the "English_United
1816    * States" format) translated into the Unixish format.
1817    */
1818   retval = g_win32_getlocale ();
1819   if ((retval != NULL) && (retval[0] != '\0'))
1820     return retval;
1821 #endif  
1822
1823   return NULL;
1824 }
1825
1826 static gchar **languages = NULL;
1827
1828 /**
1829  * g_get_language_names:
1830  * 
1831  * Computes a list of applicable locale names, which can be used to 
1832  * e.g. construct locale-dependent filenames or search paths. The returned 
1833  * list is sorted from most desirable to least desirable and always contains 
1834  * the default locale "C".
1835  *
1836  * For example, if LANGUAGE=de:en_US, then the returned list is
1837  * "de", "en_US", "en", "C".
1838  *
1839  * This function consults the environment variables <envar>LANGUAGE</envar>, 
1840  * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar> 
1841  * to find the list of locales specified by the user.
1842  * 
1843  * Return value: a %NULL-terminated array of strings owned by GLib 
1844  *    that must not be modified or freed.
1845  *
1846  * Since: 2.6
1847  **/
1848 G_CONST_RETURN gchar * G_CONST_RETURN * 
1849 g_get_language_names ()
1850 {
1851   G_LOCK (g_utils_global);
1852
1853   if (!languages)
1854     {
1855       const gchar *value;
1856       gchar **alist, **a;
1857       GSList *list, *l;
1858       gint i;
1859
1860       value = guess_category_value ("LC_MESSAGES");
1861       if (!value)
1862         value = "C";
1863
1864       alist = g_strsplit (value, ":", 0);
1865       list = NULL;
1866       for (a = alist; *a; a++)
1867         {
1868           gchar *b = unalias_lang (*a);
1869           list = g_slist_concat (list, _g_compute_locale_variants (b));
1870         }
1871       g_strfreev (alist);
1872       list = g_slist_append (list, "C");
1873
1874       languages = g_new (gchar *, g_slist_length (list) + 1);
1875       for (l = list, i = 0; l; l = l->next, i++)
1876         languages[i] = l->data;
1877       languages[i] = NULL;
1878
1879       g_slist_free (list);
1880     }
1881
1882   G_UNLOCK (g_utils_global);
1883
1884   return (G_CONST_RETURN gchar * G_CONST_RETURN *) languages;
1885 }
1886
1887 guint
1888 g_direct_hash (gconstpointer v)
1889 {
1890   return GPOINTER_TO_UINT (v);
1891 }
1892
1893 gboolean
1894 g_direct_equal (gconstpointer v1,
1895                 gconstpointer v2)
1896 {
1897   return v1 == v2;
1898 }
1899
1900 gboolean
1901 g_int_equal (gconstpointer v1,
1902              gconstpointer v2)
1903 {
1904   return *((const gint*) v1) == *((const gint*) v2);
1905 }
1906
1907 guint
1908 g_int_hash (gconstpointer v)
1909 {
1910   return *(const gint*) v;
1911 }
1912
1913 /**
1914  * g_nullify_pointer:
1915  * @nullify_location: the memory address of the pointer.
1916  * 
1917  * Set the pointer at the specified location to %NULL.
1918  **/
1919 void
1920 g_nullify_pointer (gpointer *nullify_location)
1921 {
1922   g_return_if_fail (nullify_location != NULL);
1923
1924   *nullify_location = NULL;
1925 }
1926
1927 /**
1928  * g_get_codeset:
1929  * 
1930  * Get the codeset for the current locale.
1931  * 
1932  * Return value: a newly allocated string containing the name
1933  * of the codeset. This string must be freed with g_free().
1934  **/
1935 gchar *
1936 g_get_codeset (void)
1937 {
1938   const gchar *charset;
1939
1940   g_get_charset (&charset);
1941
1942   return g_strdup (charset);
1943 }
1944
1945 #ifdef ENABLE_NLS
1946
1947 #include <libintl.h>
1948
1949 #ifdef G_PLATFORM_WIN32
1950
1951 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
1952
1953 static const gchar *
1954 _glib_get_locale_dir (void)
1955 {
1956   static const gchar *cache = NULL;
1957   if (cache == NULL)
1958     cache = g_win32_get_package_installation_subdirectory
1959       (GETTEXT_PACKAGE, dll_name, "lib\\locale");
1960
1961   return cache;
1962 }
1963
1964 #undef GLIB_LOCALE_DIR
1965 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
1966
1967 #endif /* G_PLATFORM_WIN32 */
1968
1969 G_CONST_RETURN gchar *
1970 _glib_gettext (const gchar *str)
1971 {
1972   static gboolean _glib_gettext_initialized = FALSE;
1973
1974   if (!_glib_gettext_initialized)
1975     {
1976       bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1977 #    ifdef HAVE_BIND_TEXTDOMAIN_CODESET
1978       bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1979 #    endif
1980       _glib_gettext_initialized = TRUE;
1981     }
1982   
1983   return dgettext (GETTEXT_PACKAGE, str);
1984 }
1985
1986 #endif /* ENABLE_NLS */