1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
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/.
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
45 #include <sys/types.h>
46 #ifdef HAVE_SYS_PARAM_H
47 #include <sys/param.h>
50 /* implement gutils's inline functions
52 #define G_IMPLEMENT_INLINES 1
56 #include "gprintfint.h"
57 #include "gthreadinit.h"
60 #define G_PATH_LENGTH MAXPATHLEN
61 #elif defined (PATH_MAX)
62 #define G_PATH_LENGTH PATH_MAX
63 #elif defined (_PC_PATH_MAX)
64 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
66 #define G_PATH_LENGTH 2048
69 #ifdef G_PLATFORM_WIN32
70 # define STRICT /* Strict typing, please */
73 # include <lmcons.h> /* For UNLEN */
74 #endif /* G_PLATFORM_WIN32 */
79 /* older SDK (e.g. msvc 5.0) does not have these*/
80 # ifndef CSIDL_INTERNET_CACHE
81 # define CSIDL_INTERNET_CACHE 32
83 # ifndef CSIDL_COMMON_APPDATA
84 # define CSIDL_COMMON_APPDATA 35
86 # ifndef CSIDL_COMMON_DOCUMENTS
87 # define CSIDL_COMMON_DOCUMENTS 46
89 # ifndef CSIDL_PROFILE
90 # define CSIDL_PROFILE 40
98 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
102 const guint glib_major_version = GLIB_MAJOR_VERSION;
103 const guint glib_minor_version = GLIB_MINOR_VERSION;
104 const guint glib_micro_version = GLIB_MICRO_VERSION;
105 const guint glib_interface_age = GLIB_INTERFACE_AGE;
106 const guint glib_binary_age = GLIB_BINARY_AGE;
109 * glib_check_version:
110 * @required_major: the required major version.
111 * @required_minor: the required major version.
112 * @required_micro: the required major version.
114 * Checks that the GLib library in use is compatible with the
115 * given version. Generally you would pass in the constants
116 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
117 * as the three arguments to this function; that produces
118 * a check that the library in use is compatible with
119 * the version of GLib the application or module was compiled
122 * Compatibility is defined by two things: first the version
123 * of the running library is newer than the version
124 * @required_major.required_minor.@required_micro. Second
125 * the running library must be binary compatible with the
126 * version @required_major.required_minor.@required_micro
127 * (same major version.)
129 * Return value: %NULL if the GLib library is compatible with the
130 * given version, or a string describing the version mismatch.
131 * The returned string is owned by GLib and must not be modified
137 glib_check_version (guint required_major,
138 guint required_minor,
139 guint required_micro)
141 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
142 gint required_effective_micro = 100 * required_minor + required_micro;
144 if (required_major > GLIB_MAJOR_VERSION)
145 return "GLib version too old (major mismatch)";
146 if (required_major < GLIB_MAJOR_VERSION)
147 return "GLib version too new (major mismatch)";
148 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
149 return "GLib version too new (micro mismatch)";
150 if (required_effective_micro > glib_effective_micro)
151 return "GLib version too old (micro mismatch)";
155 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
157 g_memmove (gpointer dest, gconstpointer src, gulong len)
159 gchar* destptr = dest;
160 const gchar* srcptr = src;
161 if (src + len < dest || dest + len < src)
163 bcopy (src, dest, len);
166 else if (dest <= src)
169 *(destptr++) = *(srcptr++);
176 *(--destptr) = *(--srcptr);
179 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
182 g_atexit (GVoidFunc func)
185 const gchar *error = NULL;
187 /* keep this in sync with glib.h */
189 #ifdef G_NATIVE_ATEXIT
190 result = ATEXIT (func);
192 error = g_strerror (errno);
193 #elif defined (HAVE_ATEXIT)
194 # ifdef NeXT /* @#%@! NeXTStep */
195 result = !atexit ((void (*)(void)) func);
197 error = g_strerror (errno);
199 result = atexit ((void (*)(void)) func);
201 error = g_strerror (errno);
203 #elif defined (HAVE_ON_EXIT)
204 result = on_exit ((void (*)(int, void *)) func, NULL);
206 error = g_strerror (errno);
209 error = "no implementation";
210 #endif /* G_NATIVE_ATEXIT */
213 g_error ("Could not register atexit() function: %s", error);
216 /* Based on execvp() from GNU Libc.
217 * Some of this code is cut-and-pasted into gspawn.c
221 my_strchrnul (const gchar *str, gchar c)
223 gchar *p = (gchar*)str;
224 while (*p && (*p != c))
232 static gchar *inner_find_program_in_path (const gchar *program);
235 g_find_program_in_path (const gchar *program)
237 const gchar *last_dot = strrchr (program, '.');
239 if (last_dot == NULL ||
240 strchr (last_dot, '\\') != NULL ||
241 strchr (last_dot, '/') != NULL)
243 const gint program_length = strlen (program);
244 gchar *pathext = g_build_path (";",
245 ".exe;.cmd;.bat;.com",
246 g_getenv ("PATHEXT"),
249 gchar *decorated_program;
255 gchar *q = my_strchrnul (p, ';');
257 decorated_program = g_malloc (program_length + (q-p) + 1);
258 memcpy (decorated_program, program, program_length);
259 memcpy (decorated_program+program_length, p, q-p);
260 decorated_program [program_length + (q-p)] = '\0';
262 retval = inner_find_program_in_path (decorated_program);
263 g_free (decorated_program);
271 } while (*p++ != '\0');
276 return inner_find_program_in_path (program);
282 * g_find_program_in_path:
283 * @program: a program name in the GLib file name encoding
285 * Locates the first executable named @program in the user's path, in the
286 * same way that execvp() would locate it. Returns an allocated string
287 * with the absolute path name, or NULL if the program is not found in
288 * the path. If @program is already an absolute path, returns a copy of
289 * @program if @program exists and is executable, and NULL otherwise.
291 * On Windows, if @program does not have a file type suffix, tries
292 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
293 * the PATHEXT environment variable.
295 * It looks for the file in the same way as CreateProcess()
296 * would. This means first in the directory where the executing
297 * program was loaded from, then in the current directory, then in the
298 * Windows 32-bit system directory, then in the Windows directory, and
299 * finally in the directories in the PATH environment variable. If the
300 * program is found, the return value contains the full name including
303 * Return value: absolute path, or NULL
307 inner_find_program_in_path (const gchar *program)
310 g_find_program_in_path (const gchar *program)
313 const gchar *path, *p;
314 gchar *name, *freeme;
316 const gchar *path_copy;
317 gchar *filename = NULL, *appdir = NULL;
318 gchar *sysdir = NULL, *windir = NULL;
323 g_return_val_if_fail (program != NULL, NULL);
325 /* If it is an absolute path, or a relative path including subdirectories,
326 * don't look in PATH.
328 if (g_path_is_absolute (program)
329 || strchr (program, G_DIR_SEPARATOR) != NULL
331 || strchr (program, '/') != NULL
335 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE))
336 return g_strdup (program);
341 path = g_getenv ("PATH");
345 /* There is no `PATH' in the environment. The default
346 * search path in GNU libc is the current directory followed by
347 * the path `confstr' returns for `_CS_PATH'.
350 /* In GLib we put . last, for security, and don't use the
351 * unportable confstr(); UNIX98 does not actually specify
352 * what to search if PATH is unset. POSIX may, dunno.
355 path = "/bin:/usr/bin:.";
358 if (G_WIN32_HAVE_WIDECHAR_API ())
361 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
364 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
365 if (n > 0 && n < MAXPATHLEN)
366 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
368 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
369 if (n > 0 && n < MAXPATHLEN)
370 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
372 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
373 if (n > 0 && n < MAXPATHLEN)
374 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
379 gchar cpfilename[MAXPATHLEN], cpsysdir[MAXPATHLEN],
380 cpwindir[MAXPATHLEN];
382 n = GetModuleFileNameA (NULL, cpfilename, MAXPATHLEN);
383 if (n > 0 && n < MAXPATHLEN)
384 filename = g_locale_to_utf8 (cpfilename, -1, NULL, NULL, NULL);
386 n = GetSystemDirectoryA (cpsysdir, MAXPATHLEN);
387 if (n > 0 && n < MAXPATHLEN)
388 sysdir = g_locale_to_utf8 (cpsysdir, -1, NULL, NULL, NULL);
390 n = GetWindowsDirectoryA (cpwindir, MAXPATHLEN);
391 if (n > 0 && n < MAXPATHLEN)
392 windir = g_locale_to_utf8 (cpwindir, -1, NULL, NULL, NULL);
397 appdir = g_path_get_dirname (filename);
401 path = g_strdup (path);
405 const gchar *tem = path;
406 path = g_strconcat (windir, ";", path, NULL);
407 g_free ((gchar *) tem);
413 const gchar *tem = path;
414 path = g_strconcat (sysdir, ";", path, NULL);
415 g_free ((gchar *) tem);
420 const gchar *tem = path;
421 path = g_strconcat (".;", path, NULL);
422 g_free ((gchar *) tem);
427 const gchar *tem = path;
428 path = g_strconcat (appdir, ";", path, NULL);
429 g_free ((gchar *) tem);
436 len = strlen (program) + 1;
437 pathlen = strlen (path);
438 freeme = name = g_malloc (pathlen + len + 1);
440 /* Copy the file name at the top, including '\0' */
441 memcpy (name + pathlen + 1, program, len);
442 name = name + pathlen;
443 /* And add the slash before the filename */
444 *name = G_DIR_SEPARATOR;
452 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
455 /* Two adjacent colons, or a colon at the beginning or the end
456 * of `PATH' means to search the current directory.
460 startp = memcpy (name - (p - path), path, p - path);
462 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE))
465 ret = g_strdup (startp);
468 g_free ((gchar *) path_copy);
473 while (*p++ != '\0');
477 g_free ((gchar *) path_copy);
484 g_parse_debug_string (const gchar *string,
485 const GDebugKey *keys,
491 g_return_val_if_fail (string != NULL, 0);
493 if (!g_ascii_strcasecmp (string, "all"))
495 for (i=0; i<nkeys; i++)
496 result |= keys[i].value;
500 const gchar *p = string;
502 gboolean done = FALSE;
513 for (i=0; i<nkeys; i++)
514 if (g_ascii_strncasecmp (keys[i].key, p, q - p) == 0 &&
515 keys[i].key[q - p] == '\0')
516 result |= keys[i].value;
527 * @file_name: the name of the file.
529 * Gets the name of the file without any leading directory components.
530 * It returns a pointer into the given file name string.
532 * Return value: the name of the file without any leading directory components.
534 * Deprecated: Use g_path_get_basename() instead, but notice that
535 * g_path_get_basename() allocates new memory for the returned string, unlike
536 * this function which returns a pointer into the argument.
538 G_CONST_RETURN gchar*
539 g_basename (const gchar *file_name)
541 register gchar *base;
543 g_return_val_if_fail (file_name != NULL, NULL);
545 base = strrchr (file_name, G_DIR_SEPARATOR);
549 gchar *q = strrchr (file_name, '/');
550 if (base == NULL || (q != NULL && q > base))
559 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
560 return (gchar*) file_name + 2;
561 #endif /* G_OS_WIN32 */
563 return (gchar*) file_name;
567 * g_path_get_basename:
568 * @file_name: the name of the file.
570 * Gets the last component of the filename. If @file_name ends with a
571 * directory separator it gets the component before the last slash. If
572 * @file_name consists only of directory separators (and on Windows,
573 * possibly a drive letter), a single separator is returned. If
574 * @file_name is empty, it gets ".".
576 * Return value: a newly allocated string containing the last component of
580 g_path_get_basename (const gchar *file_name)
582 register gssize base;
583 register gssize last_nonslash;
587 g_return_val_if_fail (file_name != NULL, NULL);
589 if (file_name[0] == '\0')
591 return g_strdup (".");
593 last_nonslash = strlen (file_name) - 1;
595 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
598 if (last_nonslash == -1)
599 /* string only containing slashes */
600 return g_strdup (G_DIR_SEPARATOR_S);
603 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
604 /* string only containing slashes and a drive */
605 return g_strdup (G_DIR_SEPARATOR_S);
606 #endif /* G_OS_WIN32 */
608 base = last_nonslash;
610 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
614 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
616 #endif /* G_OS_WIN32 */
618 len = last_nonslash - base;
619 retval = g_malloc (len + 1);
620 memcpy (retval, file_name + base + 1, len);
626 g_path_is_absolute (const gchar *file_name)
628 g_return_val_if_fail (file_name != NULL, FALSE);
630 if (G_IS_DIR_SEPARATOR (file_name[0]))
634 /* Recognize drive letter on native Windows */
635 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
637 #endif /* G_OS_WIN32 */
642 G_CONST_RETURN gchar*
643 g_path_skip_root (const gchar *file_name)
645 g_return_val_if_fail (file_name != NULL, NULL);
647 #ifdef G_PLATFORM_WIN32
648 /* Skip \\server\share or //server/share */
649 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
650 G_IS_DIR_SEPARATOR (file_name[1]) &&
652 !G_IS_DIR_SEPARATOR (file_name[2]))
656 p = strchr (file_name + 2, G_DIR_SEPARATOR);
659 gchar *q = strchr (file_name + 2, '/');
660 if (p == NULL || (q != NULL && q < p))
670 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
673 /* Possibly skip a backslash after the share name */
674 if (G_IS_DIR_SEPARATOR (file_name[0]))
677 return (gchar *)file_name;
682 /* Skip initial slashes */
683 if (G_IS_DIR_SEPARATOR (file_name[0]))
685 while (G_IS_DIR_SEPARATOR (file_name[0]))
687 return (gchar *)file_name;
692 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
693 return (gchar *)file_name + 3;
700 g_path_get_dirname (const gchar *file_name)
702 register gchar *base;
705 g_return_val_if_fail (file_name != NULL, NULL);
707 base = strrchr (file_name, G_DIR_SEPARATOR);
710 gchar *q = strrchr (file_name, '/');
711 if (base == NULL || (q != NULL && q > base))
718 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
720 gchar drive_colon_dot[4];
722 drive_colon_dot[0] = file_name[0];
723 drive_colon_dot[1] = ':';
724 drive_colon_dot[2] = '.';
725 drive_colon_dot[3] = '\0';
727 return g_strdup (drive_colon_dot);
730 return g_strdup (".");
733 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
737 /* base points to the char before the last slash.
739 * In case file_name is the root of a drive (X:\) or a child of the
740 * root of a drive (X:\foo), include the slash.
742 * In case file_name is the root share of an UNC path
743 * (\\server\share), add a slash, returning \\server\share\ .
745 * In case file_name is a direct child of a share in an UNC path
746 * (\\server\share\foo), include the slash after the share name,
747 * returning \\server\share\ .
749 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
751 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
752 G_IS_DIR_SEPARATOR (file_name[1]) &&
754 !G_IS_DIR_SEPARATOR (file_name[2]) &&
755 base >= file_name + 2)
757 const gchar *p = file_name + 2;
758 while (*p && !G_IS_DIR_SEPARATOR (*p))
762 len = (guint) strlen (file_name) + 1;
763 base = g_new (gchar, len + 1);
764 strcpy (base, file_name);
765 base[len-1] = G_DIR_SEPARATOR;
769 if (G_IS_DIR_SEPARATOR (*p))
772 while (*p && !G_IS_DIR_SEPARATOR (*p))
780 len = (guint) 1 + base - file_name;
782 base = g_new (gchar, len + 1);
783 g_memmove (base, file_name, len);
790 g_get_current_dir (void)
796 if (G_WIN32_HAVE_WIDECHAR_API ())
798 wchar_t dummy[2], *wdir;
801 len = GetCurrentDirectoryW (2, dummy);
802 wdir = g_new (wchar_t, len);
804 if (GetCurrentDirectoryW (len, wdir) == len - 1)
805 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
811 gchar dummy[2], *cpdir;
814 len = GetCurrentDirectoryA (2, dummy);
815 cpdir = g_new (gchar, len);
817 if (GetCurrentDirectoryA (len, cpdir) == len - 1)
818 dir = g_locale_to_utf8 (cpdir, -1, NULL, NULL, NULL);
824 dir = g_strdup ("\\");
830 gchar *buffer = NULL;
832 static gulong max_len = 0;
835 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
837 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
838 * and, if that wasn't bad enough, hangs in doing so.
840 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
841 buffer = g_new (gchar, max_len + 1);
843 dir = getwd (buffer);
844 #else /* !sun || !HAVE_GETCWD */
845 while (max_len < G_MAXULONG / 2)
847 buffer = g_new (gchar, max_len + 1);
849 dir = getcwd (buffer, max_len);
851 if (dir || errno != ERANGE)
857 #endif /* !sun || !HAVE_GETCWD */
859 if (!dir || !*buffer)
861 /* hm, should we g_error() out here?
862 * this can happen if e.g. "./" has mode \0000
864 buffer[0] = G_DIR_SEPARATOR;
868 dir = g_strdup (buffer);
877 * @variable: the environment variable to get, in the GLib file name encoding.
879 * Returns the value of an environment variable. The name and value
880 * are in the GLib file name encoding. On Unix, this means the actual
881 * bytes which might or might not be in some consistent character set
882 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
883 * environment variable's value contains references to other
884 * environment variables, they are expanded.
886 * Return value: the value of the environment variable, or %NULL if
887 * the environment variable is not found. The returned string may be
888 * overwritten by the next call to g_getenv(), g_setenv() or
891 G_CONST_RETURN gchar*
892 g_getenv (const gchar *variable)
896 g_return_val_if_fail (variable != NULL, NULL);
898 return getenv (variable);
900 #else /* G_OS_WIN32 */
905 g_return_val_if_fail (variable != NULL, NULL);
906 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
908 /* On Windows NT, it is relatively typical that environment
909 * variables contain references to other environment variables. If
910 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
911 * environment variables would be stored in the Registry as
912 * REG_EXPAND_SZ type values, and would then get automatically
913 * expanded before a program sees them. But there is broken software
914 * that stores environment variables as REG_SZ values even if they
915 * contain references to other environment variables.)
918 if (G_WIN32_HAVE_WIDECHAR_API ())
920 wchar_t dummy[2], *wname, *wvalue;
923 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
925 len = GetEnvironmentVariableW (wname, dummy, 2);
933 wvalue = g_new (wchar_t, len);
935 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
942 if (wcschr (wvalue, L'%') != NULL)
944 wchar_t *tem = wvalue;
946 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
950 wvalue = g_new (wchar_t, len);
952 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
962 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
969 gchar dummy[3], *cpname, *cpvalue;
972 cpname = g_locale_from_utf8 (variable, -1, NULL, NULL, NULL);
974 g_return_val_if_fail (cpname != NULL, NULL);
976 len = GetEnvironmentVariableA (cpname, dummy, 2);
984 cpvalue = g_new (gchar, len);
986 if (GetEnvironmentVariableA (cpname, cpvalue, len) != len - 1)
993 if (strchr (cpvalue, '%') != NULL)
995 gchar *tem = cpvalue;
997 len = ExpandEnvironmentStringsA (cpvalue, dummy, 3);
1001 cpvalue = g_new (gchar, len);
1003 if (ExpandEnvironmentStringsA (tem, cpvalue, len) != len)
1013 value = g_locale_to_utf8 (cpvalue, -1, NULL, NULL, NULL);
1019 quark = g_quark_from_string (value);
1022 return g_quark_to_string (quark);
1024 #endif /* G_OS_WIN32 */
1029 * @variable: the environment variable to set, must not contain '='.
1030 * @value: the value for to set the variable to.
1031 * @overwrite: whether to change the variable if it already exists.
1033 * Sets an environment variable. Both the variable's name and value
1034 * should be in the GLib file name encoding. On Unix, this means that
1035 * they can be any sequence of bytes. On Windows, they should be in
1038 * Note that on some systems, the memory used for the variable and its value
1039 * can't be reclaimed later.
1041 * Returns: %FALSE if the environment variable couldn't be set.
1046 g_setenv (const gchar *variable,
1057 g_return_val_if_fail (variable != NULL, FALSE);
1058 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1061 result = setenv (variable, value, overwrite);
1063 if (!overwrite && getenv (variable) != NULL)
1066 /* This results in a leak when you overwrite existing
1067 * settings. It would be fairly easy to fix this by keeping
1068 * our own parallel array or hash table.
1070 string = g_strconcat (variable, "=", value, NULL);
1071 result = putenv (string);
1075 #else /* G_OS_WIN32 */
1079 g_return_val_if_fail (variable != NULL, FALSE);
1080 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1081 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1082 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1084 if (!overwrite && g_getenv (variable) != NULL)
1087 /* We want to (if possible) set both the environment variable copy
1088 * kept by the C runtime and the one kept by the system.
1090 * We can't use only the C runtime's putenv or _wputenv() as that
1091 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1092 * (with main() and not wmain()). In a "main()" app the C runtime
1093 * initializes the C runtime's environment table by converting the
1094 * real (wide char) environment variables to system codepage, thus
1095 * breaking those that aren't representable in the system codepage.
1097 * As the C runtime's putenv() will also set the system copy, we do
1098 * the putenv() first, then call SetEnvironmentValueW ourselves.
1101 if (G_WIN32_HAVE_WIDECHAR_API ())
1103 wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1104 wchar_t *wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1105 gchar *tem = g_strconcat (variable, "=", value, NULL);
1106 wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1109 _wputenv (wassignment);
1110 g_free (wassignment);
1112 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1119 /* In the non-Unicode case (Win9x), just putenv() is good
1122 gchar *tem = g_strconcat (variable, "=", value, NULL);
1123 gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1127 retval = (putenv (cpassignment) == 0);
1129 g_free (cpassignment);
1134 #endif /* G_OS_WIN32 */
1138 #ifndef HAVE_UNSETENV
1139 /* According to the Single Unix Specification, environ is not in
1140 * any system header, although unistd.h often declares it.
1142 extern char **environ;
1148 * @variable: the environment variable to remove, must not contain '='.
1150 * Removes an environment variable from the environment.
1152 * Note that on some systems, the memory used for the variable and its value
1153 * can't be reclaimed. Furthermore, this function can't be guaranteed to operate in a
1159 g_unsetenv (const gchar *variable)
1163 #ifdef HAVE_UNSETENV
1164 g_return_if_fail (variable != NULL);
1165 g_return_if_fail (strchr (variable, '=') == NULL);
1167 unsetenv (variable);
1168 #else /* !HAVE_UNSETENV */
1172 g_return_if_fail (variable != NULL);
1173 g_return_if_fail (strchr (variable, '=') == NULL);
1175 len = strlen (variable);
1177 /* Mess directly with the environ array.
1178 * This seems to be the only portable way to do this.
1180 * Note that we remove *all* environment entries for
1181 * the variable name, not just the first.
1186 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1194 #endif /* !HAVE_UNSETENV */
1196 #else /* G_OS_WIN32 */
1198 g_return_if_fail (variable != NULL);
1199 g_return_if_fail (strchr (variable, '=') == NULL);
1200 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1202 if (G_WIN32_HAVE_WIDECHAR_API ())
1204 wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1205 gchar *tem = g_strconcat (variable, "=", NULL);
1206 wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1209 _wputenv (wassignment);
1210 g_free (wassignment);
1212 SetEnvironmentVariableW (wname, NULL);
1218 /* In the non-Unicode case (Win9x), just putenv() is good
1221 gchar *tem = g_strconcat (variable, "=", NULL);
1222 gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1226 putenv (cpassignment);
1228 g_free (cpassignment);
1231 #endif /* G_OS_WIN32 */
1234 G_LOCK_DEFINE_STATIC (g_utils_global);
1236 static gchar *g_tmp_dir = NULL;
1237 static gchar *g_user_name = NULL;
1238 static gchar *g_real_name = NULL;
1239 static gchar *g_home_dir = NULL;
1242 /* System codepage versions of the above, kept at file level so that they,
1243 * too, are produced only once.
1245 static gchar *g_tmp_dir_cp = NULL;
1246 static gchar *g_user_name_cp = NULL;
1247 static gchar *g_real_name_cp = NULL;
1248 static gchar *g_home_dir_cp = NULL;
1251 static gchar *g_user_data_dir = NULL;
1252 static gchar **g_system_data_dirs = NULL;
1253 static gchar *g_user_cache_dir = NULL;
1254 static gchar *g_user_config_dir = NULL;
1255 static gchar **g_system_config_dirs = NULL;
1260 get_special_folder (int csidl)
1264 wchar_t wc[MAX_PATH+1];
1267 LPITEMIDLIST pidl = NULL;
1269 gchar *retval = NULL;
1271 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1274 if (G_WIN32_HAVE_WIDECHAR_API ())
1276 b = SHGetPathFromIDListW (pidl, path.wc);
1278 retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
1282 b = SHGetPathFromIDListA (pidl, path.c);
1284 retval = g_locale_to_utf8 (path.c, -1, NULL, NULL, NULL);
1286 CoTaskMemFree (pidl);
1293 /* HOLDS: g_utils_global_lock */
1295 g_get_any_init (void)
1299 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1301 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1303 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1309 g_tmp_dir = g_strdup (P_tmpdir);
1310 k = strlen (g_tmp_dir);
1311 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1312 g_tmp_dir[k - 1] = '\0';
1319 g_tmp_dir = g_strdup ("/tmp");
1320 #else /* G_OS_WIN32 */
1321 g_tmp_dir = g_strdup ("\\");
1322 #endif /* G_OS_WIN32 */
1326 /* We check $HOME first for Win32, though it is a last resort for Unix
1327 * where we prefer the results of getpwuid().
1329 g_home_dir = g_strdup (g_getenv ("HOME"));
1331 /* Only believe HOME if it is an absolute path and exists */
1334 if (!(g_path_is_absolute (g_home_dir) &&
1335 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1337 g_free (g_home_dir);
1342 /* In case HOME is Unix-style (it happens), convert it to
1348 while ((p = strchr (g_home_dir, '/')) != NULL)
1354 /* USERPROFILE is probably the closest equivalent to $HOME? */
1355 if (g_getenv ("USERPROFILE") != NULL)
1356 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1360 g_home_dir = get_special_folder (CSIDL_PROFILE);
1364 /* At least at some time, HOMEDRIVE and HOMEPATH were used
1365 * to point to the home directory, I think. But on Windows
1366 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
1367 * HOMEPATH is its root "\"?
1369 if (g_getenv ("HOMEDRIVE") != NULL && g_getenv ("HOMEPATH") != NULL)
1370 g_home_dir = g_strconcat (g_getenv ("HOMEDRIVE"),
1371 g_getenv ("HOMEPATH"),
1374 #endif /* G_OS_WIN32 */
1378 struct passwd *pw = NULL;
1379 gpointer buffer = NULL;
1382 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1384 # ifdef _SC_GETPW_R_SIZE_MAX
1385 /* This reurns the maximum length */
1386 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1390 # else /* _SC_GETPW_R_SIZE_MAX */
1392 # endif /* _SC_GETPW_R_SIZE_MAX */
1397 /* we allocate 6 extra bytes to work around a bug in
1398 * Mac OS < 10.3. See #156446
1400 buffer = g_malloc (bufsize + 6);
1403 # ifdef HAVE_POSIX_GETPWUID_R
1404 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1405 error = error < 0 ? errno : error;
1406 # else /* HAVE_NONPOSIX_GETPWUID_R */
1407 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1408 # if defined(_AIX) || defined(__hpux)
1409 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1410 pw = error == 0 ? &pwd : NULL;
1412 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1413 error = pw ? 0 : errno;
1415 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1419 /* we bail out prematurely if the user id can't be found
1420 * (should be pretty rare case actually), or if the buffer
1421 * should be sufficiently big and lookups are still not
1424 if (error == 0 || error == ENOENT)
1426 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1427 (gulong) getuid ());
1430 if (bufsize > 32 * 1024)
1432 g_warning ("getpwuid_r(): failed due to: %s.",
1433 g_strerror (error));
1441 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1446 pw = getpwuid (getuid ());
1451 g_user_name = g_strdup (pw->pw_name);
1453 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1455 gchar **gecos_fields;
1458 /* split the gecos field and substitute '&' */
1459 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1460 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1461 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1462 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1463 g_strfreev (gecos_fields);
1464 g_strfreev (name_parts);
1468 g_home_dir = g_strdup (pw->pw_dir);
1473 #else /* !HAVE_PWD_H */
1476 if (G_WIN32_HAVE_WIDECHAR_API ())
1478 guint len = UNLEN+1;
1479 wchar_t buffer[UNLEN+1];
1481 if (GetUserNameW (buffer, (LPDWORD) &len))
1483 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1484 g_real_name = g_strdup (g_user_name);
1489 guint len = UNLEN+1;
1490 char buffer[UNLEN+1];
1492 if (GetUserNameA (buffer, (LPDWORD) &len))
1494 g_user_name = g_locale_to_utf8 (buffer, -1, NULL, NULL, NULL);
1495 g_real_name = g_strdup (g_user_name);
1498 #endif /* G_OS_WIN32 */
1500 #endif /* !HAVE_PWD_H */
1504 g_home_dir = g_strdup (g_getenv ("HOME"));
1508 /* change '\\' in %HOME% to '/' */
1509 g_strdelimit (g_home_dir, "\\",'/');
1512 g_user_name = g_strdup ("somebody");
1514 g_real_name = g_strdup ("Unknown");
1517 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1518 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1519 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1522 g_tmp_dir_cp = g_strdup ("\\");
1523 if (!g_user_name_cp)
1524 g_user_name_cp = g_strdup ("somebody");
1525 if (!g_real_name_cp)
1526 g_real_name_cp = g_strdup ("Unknown");
1528 /* home_dir might be NULL, unlike tmp_dir, user_name and
1532 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1534 g_home_dir_cp = NULL;
1535 #endif /* G_OS_WIN32 */
1539 G_CONST_RETURN gchar*
1540 g_get_user_name (void)
1542 G_LOCK (g_utils_global);
1545 G_UNLOCK (g_utils_global);
1550 G_CONST_RETURN gchar*
1551 g_get_real_name (void)
1553 G_LOCK (g_utils_global);
1556 G_UNLOCK (g_utils_global);
1561 G_CONST_RETURN gchar*
1562 g_get_home_dir (void)
1564 G_LOCK (g_utils_global);
1567 G_UNLOCK (g_utils_global);
1572 /* Return a directory to be used to store temporary files. This is the
1573 * value of the TMPDIR, TMP or TEMP environment variables (they are
1574 * checked in that order). If none of those exist, use P_tmpdir from
1575 * stdio.h. If that isn't defined, return "/tmp" on POSIXly systems,
1576 * and C:\ on Windows.
1579 G_CONST_RETURN gchar*
1580 g_get_tmp_dir (void)
1582 G_LOCK (g_utils_global);
1585 G_UNLOCK (g_utils_global);
1590 G_LOCK_DEFINE_STATIC (g_prgname);
1591 static gchar *g_prgname = NULL;
1594 g_get_prgname (void)
1600 G_UNLOCK (g_prgname);
1606 g_set_prgname (const gchar *prgname)
1610 g_prgname = g_strdup (prgname);
1611 G_UNLOCK (g_prgname);
1614 G_LOCK_DEFINE_STATIC (g_application_name);
1615 static gchar *g_application_name = NULL;
1618 * g_get_application_name:
1620 * Gets a human-readable name for the application, as set by
1621 * g_set_application_name(). This name should be localized if
1622 * possible, and is intended for display to the user. Contrast with
1623 * g_get_prgname(), which gets a non-localized name. If
1624 * g_set_application_name() has not been called, returns the result of
1625 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1628 * Return value: human-readable application name. may return %NULL
1632 G_CONST_RETURN gchar*
1633 g_get_application_name (void)
1637 G_LOCK (g_application_name);
1638 retval = g_application_name;
1639 G_UNLOCK (g_application_name);
1642 return g_get_prgname ();
1648 * g_set_application_name:
1649 * @application_name: localized name of the application
1651 * Sets a human-readable name for the application. This name should be
1652 * localized if possible, and is intended for display to the user.
1653 * Contrast with g_set_prgname(), which sets a non-localized name.
1654 * g_set_prgname() will be called automatically by gtk_init(),
1655 * but g_set_application_name() will not.
1657 * Note that for thread safety reasons, this function can only
1660 * The application name will be used in contexts such as error messages,
1661 * or when displaying an application's name in the task list.
1665 g_set_application_name (const gchar *application_name)
1667 gboolean already_set = FALSE;
1669 G_LOCK (g_application_name);
1670 if (g_application_name)
1673 g_application_name = g_strdup (application_name);
1674 G_UNLOCK (g_application_name);
1677 g_warning ("g_set_application() name called multiple times");
1681 * g_get_user_data_dir:
1683 * Returns a base directory in which to access application data such
1684 * as icons that is customized for a particular user.
1686 * On Unix platforms this is determined using the mechanisms described in
1687 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1688 * XDG Base Directory Specification</ulink>
1690 * Return value: a string owned by GLib that must not be modified
1694 G_CONST_RETURN gchar*
1695 g_get_user_data_dir (void)
1699 G_LOCK (g_utils_global);
1701 if (!g_user_data_dir)
1704 data_dir = get_special_folder (CSIDL_PERSONAL);
1706 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1709 if (data_dir && data_dir[0])
1710 data_dir = g_strdup (data_dir);
1716 data_dir = g_build_filename (g_home_dir, ".local",
1720 g_user_data_dir = data_dir;
1723 data_dir = g_user_data_dir;
1725 G_UNLOCK (g_utils_global);
1731 * g_get_user_config_dir:
1733 * Returns a base directory in which to store user-specific application
1734 * configuration information such as user preferences and settings.
1736 * On Unix platforms this is determined using the mechanisms described in
1737 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1738 * XDG Base Directory Specification</ulink>
1740 * Return value: a string owned by GLib that must not be modified
1744 G_CONST_RETURN gchar*
1745 g_get_user_config_dir (void)
1749 G_LOCK (g_utils_global);
1751 if (!g_user_config_dir)
1754 config_dir = get_special_folder (CSIDL_APPDATA);
1756 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1759 if (config_dir && config_dir[0])
1760 config_dir = g_strdup (config_dir);
1766 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1768 g_user_config_dir = config_dir;
1771 config_dir = g_user_config_dir;
1773 G_UNLOCK (g_utils_global);
1779 * g_get_user_cache_dir:
1781 * Returns a base directory in which to store non-essential, cached
1782 * data specific to particular user.
1784 * On Unix platforms this is determined using the mechanisms described in
1785 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1786 * XDG Base Directory Specification</ulink>
1788 * Return value: a string owned by GLib that must not be modified
1792 G_CONST_RETURN gchar*
1793 g_get_user_cache_dir (void)
1797 G_LOCK (g_utils_global);
1799 if (!g_user_cache_dir)
1802 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1804 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1806 if (cache_dir && cache_dir[0])
1807 cache_dir = g_strdup (cache_dir);
1813 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1815 g_user_cache_dir = cache_dir;
1818 cache_dir = g_user_cache_dir;
1820 G_UNLOCK (g_utils_global);
1826 * g_get_system_data_dirs:
1828 * Returns an ordered list of base directories in which to access
1829 * system-wide application data.
1831 * On Unix platforms this is determined using the mechanisms described in
1832 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1833 * XDG Base Directory Specification</ulink>
1835 * Return value: a %NULL-terminated array of strings owned by GLib that must
1836 * not be modified or freed.
1839 G_CONST_RETURN gchar * G_CONST_RETURN *
1840 g_get_system_data_dirs (void)
1842 gchar *data_dirs, **data_dir_vector;
1844 G_LOCK (g_utils_global);
1846 if (!g_system_data_dirs)
1849 data_dirs = g_strconcat (get_special_folder (CSIDL_COMMON_APPDATA),
1850 G_SEARCHPATH_SEPARATOR_S,
1851 get_special_folder (CSIDL_COMMON_DOCUMENTS),
1854 data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1856 if (!data_dirs || !data_dirs[0])
1857 data_dirs = "/usr/local/share/:/usr/share/";
1859 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1861 g_system_data_dirs = data_dir_vector;
1864 data_dir_vector = g_system_data_dirs;
1866 G_UNLOCK (g_utils_global);
1868 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
1872 * g_get_system_config_dirs:
1874 * Returns an ordered list of base directories in which to access
1875 * system-wide configuration information.
1877 * On Unix platforms this is determined using the mechanisms described in
1878 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1879 * XDG Base Directory Specification</ulink>
1881 * Return value: a %NULL-terminated array of strings owned by GLib that must
1882 * not be modified or freed.
1885 G_CONST_RETURN gchar * G_CONST_RETURN *
1886 g_get_system_config_dirs (void)
1888 gchar *conf_dirs, **conf_dir_vector;
1890 G_LOCK (g_utils_global);
1892 if (!g_system_config_dirs)
1895 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
1897 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
1899 if (!conf_dirs || !conf_dirs[0])
1900 conf_dirs = "/etc/xdg";
1902 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1904 g_system_config_dirs = conf_dir_vector;
1907 conf_dir_vector = g_system_config_dirs;
1908 G_UNLOCK (g_utils_global);
1910 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
1913 static GHashTable *alias_table = NULL;
1915 /* read an alias file for the locales */
1917 read_aliases (gchar *file)
1923 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
1924 fp = fopen (file,"r");
1927 while (fgets (buf, 256, fp))
1933 /* Line is a comment */
1934 if ((buf[0] == '#') || (buf[0] == '\0'))
1937 /* Reads first column */
1938 for (p = buf, q = NULL; *p; p++) {
1939 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
1942 while ((*q == '\t') || (*q == ' ')) {
1948 /* The line only had one column */
1949 if (!q || *q == '\0')
1952 /* Read second column */
1953 for (p = q; *p; p++) {
1954 if ((*p == '\t') || (*p == ' ')) {
1960 /* Add to alias table if necessary */
1961 if (!g_hash_table_lookup (alias_table, buf)) {
1962 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
1969 unalias_lang (char *lang)
1975 read_aliases ("/usr/share/locale/locale.alias");
1978 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
1983 static gboolean said_before = FALSE;
1985 g_warning ("Too many alias levels for a locale, "
1986 "may indicate a loop");
1994 /* Mask for components of locale spec. The ordering here is from
1995 * least significant to most significant
1999 COMPONENT_CODESET = 1 << 0,
2000 COMPONENT_TERRITORY = 1 << 1,
2001 COMPONENT_MODIFIER = 1 << 2
2004 /* Break an X/Open style locale specification into components
2007 explode_locale (const gchar *locale,
2013 const gchar *uscore_pos;
2014 const gchar *at_pos;
2015 const gchar *dot_pos;
2019 uscore_pos = strchr (locale, '_');
2020 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2021 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2025 mask |= COMPONENT_MODIFIER;
2026 *modifier = g_strdup (at_pos);
2029 at_pos = locale + strlen (locale);
2033 mask |= COMPONENT_CODESET;
2034 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2041 mask |= COMPONENT_TERRITORY;
2042 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2045 uscore_pos = dot_pos;
2047 *language = g_strndup (locale, uscore_pos - locale);
2053 * Compute all interesting variants for a given locale name -
2054 * by stripping off different components of the value.
2056 * For simplicity, we assume that the locale is in
2057 * X/Open format: language[_territory][.codeset][@modifier]
2059 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2060 * as well. We could just copy the code from glibc wholesale
2061 * but it is big, ugly, and complicated, so I'm reluctant
2062 * to do so when this should handle 99% of the time...
2065 _g_compute_locale_variants (const gchar *locale)
2067 GSList *retval = NULL;
2077 g_return_val_if_fail (locale != NULL, NULL);
2079 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2081 /* Iterate through all possible combinations, from least attractive
2082 * to most attractive.
2084 for (i = 0; i <= mask; i++)
2085 if ((i & ~mask) == 0)
2087 gchar *val = g_strconcat (language,
2088 (i & COMPONENT_TERRITORY) ? territory : "",
2089 (i & COMPONENT_CODESET) ? codeset : "",
2090 (i & COMPONENT_MODIFIER) ? modifier : "",
2092 retval = g_slist_prepend (retval, val);
2096 if (mask & COMPONENT_CODESET)
2098 if (mask & COMPONENT_TERRITORY)
2100 if (mask & COMPONENT_MODIFIER)
2106 /* The following is (partly) taken from the gettext package.
2107 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2109 static const gchar *
2110 guess_category_value (const gchar *category_name)
2112 const gchar *retval;
2114 /* The highest priority value is the `LANGUAGE' environment
2115 variable. This is a GNU extension. */
2116 retval = g_getenv ("LANGUAGE");
2117 if ((retval != NULL) && (retval[0] != '\0'))
2120 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2121 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2122 systems this can be done by the `setlocale' function itself. */
2124 /* Setting of LC_ALL overwrites all other. */
2125 retval = g_getenv ("LC_ALL");
2126 if ((retval != NULL) && (retval[0] != '\0'))
2129 /* Next comes the name of the desired category. */
2130 retval = g_getenv (category_name);
2131 if ((retval != NULL) && (retval[0] != '\0'))
2134 /* Last possibility is the LANG environment variable. */
2135 retval = g_getenv ("LANG");
2136 if ((retval != NULL) && (retval[0] != '\0'))
2139 #ifdef G_PLATFORM_WIN32
2140 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2141 * LANG, which we already did above. Oh well. The main point of
2142 * calling g_win32_getlocale() is to get the thread's locale as used
2143 * by Windows and the Microsoft C runtime (in the "English_United
2144 * States" format) translated into the Unixish format.
2146 retval = g_win32_getlocale ();
2147 if ((retval != NULL) && (retval[0] != '\0'))
2154 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2156 struct _GLanguageNamesCache {
2158 gchar **language_names;
2162 language_names_cache_free (gpointer data)
2164 GLanguageNamesCache *cache = data;
2165 g_free (cache->languages);
2166 g_strfreev (cache->language_names);
2171 * g_get_language_names:
2173 * Computes a list of applicable locale names, which can be used to
2174 * e.g. construct locale-dependent filenames or search paths. The returned
2175 * list is sorted from most desirable to least desirable and always contains
2176 * the default locale "C".
2178 * For example, if LANGUAGE=de:en_US, then the returned list is
2179 * "de", "en_US", "en", "C".
2181 * This function consults the environment variables <envar>LANGUAGE</envar>,
2182 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2183 * to find the list of locales specified by the user.
2185 * Return value: a %NULL-terminated array of strings owned by GLib
2186 * that must not be modified or freed.
2190 G_CONST_RETURN gchar * G_CONST_RETURN *
2191 g_get_language_names (void)
2193 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2194 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2199 cache = g_new0 (GLanguageNamesCache, 1);
2200 g_static_private_set (&cache_private, cache, language_names_cache_free);
2203 value = guess_category_value ("LC_MESSAGES");
2207 if (!(cache->languages && strcmp (cache->languages, value) == 0))
2214 g_free (cache->languages);
2215 g_strfreev (cache->language_names);
2216 cache->languages = g_strdup (value);
2218 alist = g_strsplit (value, ":", 0);
2220 for (a = alist; *a; a++)
2222 gchar *b = unalias_lang (*a);
2223 list = g_slist_concat (list, _g_compute_locale_variants (b));
2226 list = g_slist_append (list, g_strdup ("C"));
2228 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
2229 for (l = list, i = 0; l; l = l->next, i++)
2230 languages[i] = l->data;
2231 languages[i] = NULL;
2233 g_slist_free (list);
2236 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
2240 g_direct_hash (gconstpointer v)
2242 return GPOINTER_TO_UINT (v);
2246 g_direct_equal (gconstpointer v1,
2253 g_int_equal (gconstpointer v1,
2256 return *((const gint*) v1) == *((const gint*) v2);
2260 g_int_hash (gconstpointer v)
2262 return *(const gint*) v;
2266 * g_nullify_pointer:
2267 * @nullify_location: the memory address of the pointer.
2269 * Set the pointer at the specified location to %NULL.
2272 g_nullify_pointer (gpointer *nullify_location)
2274 g_return_if_fail (nullify_location != NULL);
2276 *nullify_location = NULL;
2282 * Get the codeset for the current locale.
2284 * Return value: a newly allocated string containing the name
2285 * of the codeset. This string must be freed with g_free().
2288 g_get_codeset (void)
2290 const gchar *charset;
2292 g_get_charset (&charset);
2294 return g_strdup (charset);
2297 /* This is called from g_thread_init(). It's used to
2298 * initialize some static data in a threadsafe way.
2301 _g_utils_thread_init (void)
2303 g_get_language_names ();
2308 #include <libintl.h>
2310 #ifdef G_PLATFORM_WIN32
2312 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
2314 static const gchar *
2315 _glib_get_locale_dir (void)
2317 static const gchar *cache = NULL;
2319 cache = g_win32_get_package_installation_subdirectory
2320 (GETTEXT_PACKAGE, dll_name, "lib\\locale");
2325 #undef GLIB_LOCALE_DIR
2326 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
2328 #endif /* G_PLATFORM_WIN32 */
2330 G_CONST_RETURN gchar *
2331 _glib_gettext (const gchar *str)
2333 static gboolean _glib_gettext_initialized = FALSE;
2335 if (!_glib_gettext_initialized)
2337 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
2338 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2339 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2341 _glib_gettext_initialized = TRUE;
2344 return dgettext (GETTEXT_PACKAGE, str);
2347 #endif /* ENABLE_NLS */
2351 /* Binary compatibility versions. Not for newly compiled code. */
2353 #undef g_find_program_in_path
2356 g_find_program_in_path (const gchar *program)
2358 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2359 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2362 g_free (utf8_program);
2363 if (utf8_retval == NULL)
2365 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2366 g_free (utf8_retval);
2371 #undef g_get_current_dir
2374 g_get_current_dir (void)
2376 gchar *utf8_dir = g_get_current_dir_utf8 ();
2377 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2384 G_CONST_RETURN gchar*
2385 g_getenv (const gchar *variable)
2387 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2388 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
2389 gchar *value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
2390 GQuark quark = g_quark_from_string (value);
2392 g_free (utf8_variable);
2395 return g_quark_to_string (quark);
2401 g_setenv (const gchar *variable,
2405 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2406 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
2407 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
2409 g_free (utf8_variable);
2410 g_free (utf8_value);
2418 g_unsetenv (const gchar *variable)
2420 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2422 g_unsetenv_utf8 (utf8_variable);
2424 g_free (utf8_variable);
2427 #undef g_get_user_name
2429 G_CONST_RETURN gchar*
2430 g_get_user_name (void)
2432 G_LOCK (g_utils_global);
2435 G_UNLOCK (g_utils_global);
2437 return g_user_name_cp;
2440 #undef g_get_real_name
2442 G_CONST_RETURN gchar*
2443 g_get_real_name (void)
2445 G_LOCK (g_utils_global);
2448 G_UNLOCK (g_utils_global);
2450 return g_real_name_cp;
2453 #undef g_get_home_dir
2455 G_CONST_RETURN gchar*
2456 g_get_home_dir (void)
2458 G_LOCK (g_utils_global);
2461 G_UNLOCK (g_utils_global);
2463 return g_home_dir_cp;
2466 #undef g_get_tmp_dir
2468 G_CONST_RETURN gchar*
2469 g_get_tmp_dir (void)
2471 G_LOCK (g_utils_global);
2474 G_UNLOCK (g_utils_global);
2476 return g_tmp_dir_cp;