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)
158 * @dest: the destination address to copy the bytes to.
159 * @src: the source address to copy the bytes from.
160 * @len: the number of bytes to copy.
162 * Copies a block of memory @len bytes long, from @src to @dest.
163 * The source and destination areas may overlap.
165 * In order to use this function, you must include
166 * <filename>string.h</filename> yourself, because this macro will
167 * typically simply resolve to memmove() and GLib does not include
168 * <filename>string.h</filename> for you.
171 g_memmove (gpointer dest,
175 gchar* destptr = dest;
176 const gchar* srcptr = src;
177 if (src + len < dest || dest + len < src)
179 bcopy (src, dest, len);
182 else if (dest <= src)
185 *(destptr++) = *(srcptr++);
192 *(--destptr) = *(--srcptr);
195 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
199 * @func: the function to call on normal program termination.
201 * Specifies a function to be called at normal program termination.
204 g_atexit (GVoidFunc func)
207 const gchar *error = NULL;
209 /* keep this in sync with glib.h */
211 #ifdef G_NATIVE_ATEXIT
212 result = ATEXIT (func);
214 error = g_strerror (errno);
215 #elif defined (HAVE_ATEXIT)
216 # ifdef NeXT /* @#%@! NeXTStep */
217 result = !atexit ((void (*)(void)) func);
219 error = g_strerror (errno);
221 result = atexit ((void (*)(void)) func);
223 error = g_strerror (errno);
225 #elif defined (HAVE_ON_EXIT)
226 result = on_exit ((void (*)(int, void *)) func, NULL);
228 error = g_strerror (errno);
231 error = "no implementation";
232 #endif /* G_NATIVE_ATEXIT */
235 g_error ("Could not register atexit() function: %s", error);
238 /* Based on execvp() from GNU Libc.
239 * Some of this code is cut-and-pasted into gspawn.c
243 my_strchrnul (const gchar *str,
246 gchar *p = (gchar*)str;
247 while (*p && (*p != c))
255 static gchar *inner_find_program_in_path (const gchar *program);
258 g_find_program_in_path (const gchar *program)
260 const gchar *last_dot = strrchr (program, '.');
262 if (last_dot == NULL ||
263 strchr (last_dot, '\\') != NULL ||
264 strchr (last_dot, '/') != NULL)
266 const gint program_length = strlen (program);
267 gchar *pathext = g_build_path (";",
268 ".exe;.cmd;.bat;.com",
269 g_getenv ("PATHEXT"),
272 gchar *decorated_program;
278 gchar *q = my_strchrnul (p, ';');
280 decorated_program = g_malloc (program_length + (q-p) + 1);
281 memcpy (decorated_program, program, program_length);
282 memcpy (decorated_program+program_length, p, q-p);
283 decorated_program [program_length + (q-p)] = '\0';
285 retval = inner_find_program_in_path (decorated_program);
286 g_free (decorated_program);
294 } while (*p++ != '\0');
299 return inner_find_program_in_path (program);
305 * g_find_program_in_path:
306 * @program: a program name in the GLib file name encoding
308 * Locates the first executable named @program in the user's path, in the
309 * same way that execvp() would locate it. Returns an allocated string
310 * with the absolute path name, or %NULL if the program is not found in
311 * the path. If @program is already an absolute path, returns a copy of
312 * @program if @program exists and is executable, and %NULL otherwise.
314 * On Windows, if @program does not have a file type suffix, tries
315 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
316 * the <envar>PATHEXT</envar> environment variable.
318 * On Windows, it looks for the file in the same way as CreateProcess()
319 * would. This means first in the directory where the executing
320 * program was loaded from, then in the current directory, then in the
321 * Windows 32-bit system directory, then in the Windows directory, and
322 * finally in the directories in the <envar>PATH</envar> environment
323 * variable. If the program is found, the return value contains the
324 * full name including the type suffix.
326 * Return value: absolute path, or %NULL
330 inner_find_program_in_path (const gchar *program)
333 g_find_program_in_path (const gchar *program)
336 const gchar *path, *p;
337 gchar *name, *freeme;
339 const gchar *path_copy;
340 gchar *filename = NULL, *appdir = NULL;
341 gchar *sysdir = NULL, *windir = NULL;
346 g_return_val_if_fail (program != NULL, NULL);
348 /* If it is an absolute path, or a relative path including subdirectories,
349 * don't look in PATH.
351 if (g_path_is_absolute (program)
352 || strchr (program, G_DIR_SEPARATOR) != NULL
354 || strchr (program, '/') != NULL
358 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
359 !g_file_test (program, G_FILE_TEST_IS_DIR))
360 return g_strdup (program);
365 path = g_getenv ("PATH");
369 /* There is no `PATH' in the environment. The default
370 * search path in GNU libc is the current directory followed by
371 * the path `confstr' returns for `_CS_PATH'.
374 /* In GLib we put . last, for security, and don't use the
375 * unportable confstr(); UNIX98 does not actually specify
376 * what to search if PATH is unset. POSIX may, dunno.
379 path = "/bin:/usr/bin:.";
382 if (G_WIN32_HAVE_WIDECHAR_API ())
385 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
388 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
389 if (n > 0 && n < MAXPATHLEN)
390 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
392 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
393 if (n > 0 && n < MAXPATHLEN)
394 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
396 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
397 if (n > 0 && n < MAXPATHLEN)
398 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
403 gchar cpfilename[MAXPATHLEN], cpsysdir[MAXPATHLEN],
404 cpwindir[MAXPATHLEN];
406 n = GetModuleFileNameA (NULL, cpfilename, MAXPATHLEN);
407 if (n > 0 && n < MAXPATHLEN)
408 filename = g_locale_to_utf8 (cpfilename, -1, NULL, NULL, NULL);
410 n = GetSystemDirectoryA (cpsysdir, MAXPATHLEN);
411 if (n > 0 && n < MAXPATHLEN)
412 sysdir = g_locale_to_utf8 (cpsysdir, -1, NULL, NULL, NULL);
414 n = GetWindowsDirectoryA (cpwindir, MAXPATHLEN);
415 if (n > 0 && n < MAXPATHLEN)
416 windir = g_locale_to_utf8 (cpwindir, -1, NULL, NULL, NULL);
421 appdir = g_path_get_dirname (filename);
425 path = g_strdup (path);
429 const gchar *tem = path;
430 path = g_strconcat (windir, ";", path, NULL);
431 g_free ((gchar *) tem);
437 const gchar *tem = path;
438 path = g_strconcat (sysdir, ";", path, NULL);
439 g_free ((gchar *) tem);
444 const gchar *tem = path;
445 path = g_strconcat (".;", path, NULL);
446 g_free ((gchar *) tem);
451 const gchar *tem = path;
452 path = g_strconcat (appdir, ";", path, NULL);
453 g_free ((gchar *) tem);
460 len = strlen (program) + 1;
461 pathlen = strlen (path);
462 freeme = name = g_malloc (pathlen + len + 1);
464 /* Copy the file name at the top, including '\0' */
465 memcpy (name + pathlen + 1, program, len);
466 name = name + pathlen;
467 /* And add the slash before the filename */
468 *name = G_DIR_SEPARATOR;
476 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
479 /* Two adjacent colons, or a colon at the beginning or the end
480 * of `PATH' means to search the current directory.
484 startp = memcpy (name - (p - path), path, p - path);
486 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
487 !g_file_test (startp, G_FILE_TEST_IS_DIR))
490 ret = g_strdup (startp);
493 g_free ((gchar *) path_copy);
498 while (*p++ != '\0');
502 g_free ((gchar *) path_copy);
509 * g_parse_debug_string:
510 * @string: a list of debug options separated by ':' or "all"
512 * @keys: pointer to an array of #GDebugKey which associate
513 * strings with bit flags.
514 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
516 * Parses a string containing debugging options separated
517 * by ':' into a %guint containing bit flags. This is used
518 * within GDK and GTK+ to parse the debug options passed on the
519 * command line or through environment variables.
521 * Returns: the combined set of bit flags.
524 g_parse_debug_string (const gchar *string,
525 const GDebugKey *keys,
531 g_return_val_if_fail (string != NULL, 0);
533 if (!g_ascii_strcasecmp (string, "all"))
535 for (i=0; i<nkeys; i++)
536 result |= keys[i].value;
540 const gchar *p = string;
542 gboolean done = FALSE;
553 for (i=0; i<nkeys; i++)
554 if (g_ascii_strncasecmp (keys[i].key, p, q - p) == 0 &&
555 keys[i].key[q - p] == '\0')
556 result |= keys[i].value;
567 * @file_name: the name of the file.
569 * Gets the name of the file without any leading directory components.
570 * It returns a pointer into the given file name string.
572 * Return value: the name of the file without any leading directory components.
574 * Deprecated: Use g_path_get_basename() instead, but notice that
575 * g_path_get_basename() allocates new memory for the returned string, unlike
576 * this function which returns a pointer into the argument.
578 G_CONST_RETURN gchar*
579 g_basename (const gchar *file_name)
581 register gchar *base;
583 g_return_val_if_fail (file_name != NULL, NULL);
585 base = strrchr (file_name, G_DIR_SEPARATOR);
589 gchar *q = strrchr (file_name, '/');
590 if (base == NULL || (q != NULL && q > base))
599 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
600 return (gchar*) file_name + 2;
601 #endif /* G_OS_WIN32 */
603 return (gchar*) file_name;
607 * g_path_get_basename:
608 * @file_name: the name of the file.
610 * Gets the last component of the filename. If @file_name ends with a
611 * directory separator it gets the component before the last slash. If
612 * @file_name consists only of directory separators (and on Windows,
613 * possibly a drive letter), a single separator is returned. If
614 * @file_name is empty, it gets ".".
616 * Return value: a newly allocated string containing the last component of
620 g_path_get_basename (const gchar *file_name)
622 register gssize base;
623 register gssize last_nonslash;
627 g_return_val_if_fail (file_name != NULL, NULL);
629 if (file_name[0] == '\0')
631 return g_strdup (".");
633 last_nonslash = strlen (file_name) - 1;
635 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
638 if (last_nonslash == -1)
639 /* string only containing slashes */
640 return g_strdup (G_DIR_SEPARATOR_S);
643 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
644 /* string only containing slashes and a drive */
645 return g_strdup (G_DIR_SEPARATOR_S);
646 #endif /* G_OS_WIN32 */
648 base = last_nonslash;
650 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
654 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
656 #endif /* G_OS_WIN32 */
658 len = last_nonslash - base;
659 retval = g_malloc (len + 1);
660 memcpy (retval, file_name + base + 1, len);
666 * g_path_is_absolute:
667 * @file_name: a file name.
669 * Returns %TRUE if the given @file_name is an absolute file name,
670 * i.e. it contains a full path from the root directory such as "/usr/local"
671 * on UNIX or "C:\windows" on Windows systems.
673 * Returns: %TRUE if @file_name is an absolute path.
676 g_path_is_absolute (const gchar *file_name)
678 g_return_val_if_fail (file_name != NULL, FALSE);
680 if (G_IS_DIR_SEPARATOR (file_name[0]))
684 /* Recognize drive letter on native Windows */
685 if (g_ascii_isalpha (file_name[0]) &&
686 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
688 #endif /* G_OS_WIN32 */
695 * @file_name: a file name.
697 * Returns a pointer into @file_name after the root component, i.e. after
698 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
699 * path it returns %NULL.
701 * Returns: a pointer into @file_name after the root component.
703 G_CONST_RETURN gchar*
704 g_path_skip_root (const gchar *file_name)
706 g_return_val_if_fail (file_name != NULL, NULL);
708 #ifdef G_PLATFORM_WIN32
709 /* Skip \\server\share or //server/share */
710 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
711 G_IS_DIR_SEPARATOR (file_name[1]) &&
713 !G_IS_DIR_SEPARATOR (file_name[2]))
717 p = strchr (file_name + 2, G_DIR_SEPARATOR);
720 gchar *q = strchr (file_name + 2, '/');
721 if (p == NULL || (q != NULL && q < p))
731 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
734 /* Possibly skip a backslash after the share name */
735 if (G_IS_DIR_SEPARATOR (file_name[0]))
738 return (gchar *)file_name;
743 /* Skip initial slashes */
744 if (G_IS_DIR_SEPARATOR (file_name[0]))
746 while (G_IS_DIR_SEPARATOR (file_name[0]))
748 return (gchar *)file_name;
753 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
754 return (gchar *)file_name + 3;
761 * g_path_get_dirname:
762 * @file_name: the name of the file.
764 * Gets the directory components of a file name. If the file name has no
765 * directory components "." is returned. The returned string should be
766 * freed when no longer needed.
768 * Returns: the directory components of the file.
771 g_path_get_dirname (const gchar *file_name)
773 register gchar *base;
776 g_return_val_if_fail (file_name != NULL, NULL);
778 base = strrchr (file_name, G_DIR_SEPARATOR);
781 gchar *q = strrchr (file_name, '/');
782 if (base == NULL || (q != NULL && q > base))
789 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
791 gchar drive_colon_dot[4];
793 drive_colon_dot[0] = file_name[0];
794 drive_colon_dot[1] = ':';
795 drive_colon_dot[2] = '.';
796 drive_colon_dot[3] = '\0';
798 return g_strdup (drive_colon_dot);
801 return g_strdup (".");
804 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
808 /* base points to the char before the last slash.
810 * In case file_name is the root of a drive (X:\) or a child of the
811 * root of a drive (X:\foo), include the slash.
813 * In case file_name is the root share of an UNC path
814 * (\\server\share), add a slash, returning \\server\share\ .
816 * In case file_name is a direct child of a share in an UNC path
817 * (\\server\share\foo), include the slash after the share name,
818 * returning \\server\share\ .
820 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
822 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
823 G_IS_DIR_SEPARATOR (file_name[1]) &&
825 !G_IS_DIR_SEPARATOR (file_name[2]) &&
826 base >= file_name + 2)
828 const gchar *p = file_name + 2;
829 while (*p && !G_IS_DIR_SEPARATOR (*p))
833 len = (guint) strlen (file_name) + 1;
834 base = g_new (gchar, len + 1);
835 strcpy (base, file_name);
836 base[len-1] = G_DIR_SEPARATOR;
840 if (G_IS_DIR_SEPARATOR (*p))
843 while (*p && !G_IS_DIR_SEPARATOR (*p))
851 len = (guint) 1 + base - file_name;
853 base = g_new (gchar, len + 1);
854 g_memmove (base, file_name, len);
863 * Gets the current directory.
864 * The returned string should be freed when no longer needed. The encoding
865 * of the returned string is system defined. On Windows, it is always UTF-8.
867 * Returns: the current directory.
870 g_get_current_dir (void)
876 if (G_WIN32_HAVE_WIDECHAR_API ())
878 wchar_t dummy[2], *wdir;
881 len = GetCurrentDirectoryW (2, dummy);
882 wdir = g_new (wchar_t, len);
884 if (GetCurrentDirectoryW (len, wdir) == len - 1)
885 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
891 gchar dummy[2], *cpdir;
894 len = GetCurrentDirectoryA (2, dummy);
895 cpdir = g_new (gchar, len);
897 if (GetCurrentDirectoryA (len, cpdir) == len - 1)
898 dir = g_locale_to_utf8 (cpdir, -1, NULL, NULL, NULL);
904 dir = g_strdup ("\\");
910 gchar *buffer = NULL;
912 static gulong max_len = 0;
915 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
917 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
918 * and, if that wasn't bad enough, hangs in doing so.
920 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
921 buffer = g_new (gchar, max_len + 1);
923 dir = getwd (buffer);
924 #else /* !sun || !HAVE_GETCWD */
925 while (max_len < G_MAXULONG / 2)
927 buffer = g_new (gchar, max_len + 1);
929 dir = getcwd (buffer, max_len);
931 if (dir || errno != ERANGE)
937 #endif /* !sun || !HAVE_GETCWD */
939 if (!dir || !*buffer)
941 /* hm, should we g_error() out here?
942 * this can happen if e.g. "./" has mode \0000
944 buffer[0] = G_DIR_SEPARATOR;
948 dir = g_strdup (buffer);
957 * @variable: the environment variable to get, in the GLib file name encoding.
959 * Returns the value of an environment variable. The name and value
960 * are in the GLib file name encoding. On UNIX, this means the actual
961 * bytes which might or might not be in some consistent character set
962 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
963 * environment variable's value contains references to other
964 * environment variables, they are expanded.
966 * Return value: the value of the environment variable, or %NULL if
967 * the environment variable is not found. The returned string may be
968 * overwritten by the next call to g_getenv(), g_setenv() or
971 G_CONST_RETURN gchar*
972 g_getenv (const gchar *variable)
976 g_return_val_if_fail (variable != NULL, NULL);
978 return getenv (variable);
980 #else /* G_OS_WIN32 */
985 g_return_val_if_fail (variable != NULL, NULL);
986 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
988 /* On Windows NT, it is relatively typical that environment
989 * variables contain references to other environment variables. If
990 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
991 * environment variables would be stored in the Registry as
992 * REG_EXPAND_SZ type values, and would then get automatically
993 * expanded before a program sees them. But there is broken software
994 * that stores environment variables as REG_SZ values even if they
995 * contain references to other environment variables.)
998 if (G_WIN32_HAVE_WIDECHAR_API ())
1000 wchar_t dummy[2], *wname, *wvalue;
1003 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1005 len = GetEnvironmentVariableW (wname, dummy, 2);
1013 wvalue = g_new (wchar_t, len);
1015 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1022 if (wcschr (wvalue, L'%') != NULL)
1024 wchar_t *tem = wvalue;
1026 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1030 wvalue = g_new (wchar_t, len);
1032 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1042 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1049 gchar dummy[3], *cpname, *cpvalue;
1052 cpname = g_locale_from_utf8 (variable, -1, NULL, NULL, NULL);
1054 g_return_val_if_fail (cpname != NULL, NULL);
1056 len = GetEnvironmentVariableA (cpname, dummy, 2);
1064 cpvalue = g_new (gchar, len);
1066 if (GetEnvironmentVariableA (cpname, cpvalue, len) != len - 1)
1073 if (strchr (cpvalue, '%') != NULL)
1075 gchar *tem = cpvalue;
1077 len = ExpandEnvironmentStringsA (cpvalue, dummy, 3);
1081 cpvalue = g_new (gchar, len);
1083 if (ExpandEnvironmentStringsA (tem, cpvalue, len) != len)
1093 value = g_locale_to_utf8 (cpvalue, -1, NULL, NULL, NULL);
1099 quark = g_quark_from_string (value);
1102 return g_quark_to_string (quark);
1104 #endif /* G_OS_WIN32 */
1109 * @variable: the environment variable to set, must not contain '='.
1110 * @value: the value for to set the variable to.
1111 * @overwrite: whether to change the variable if it already exists.
1113 * Sets an environment variable. Both the variable's name and value
1114 * should be in the GLib file name encoding. On UNIX, this means that
1115 * they can be any sequence of bytes. On Windows, they should be in
1118 * Note that on some systems, when variables are overwritten, the memory
1119 * used for the previous variables and its value isn't reclaimed.
1121 * Returns: %FALSE if the environment variable couldn't be set.
1126 g_setenv (const gchar *variable,
1137 g_return_val_if_fail (variable != NULL, FALSE);
1138 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1141 result = setenv (variable, value, overwrite);
1143 if (!overwrite && getenv (variable) != NULL)
1146 /* This results in a leak when you overwrite existing
1147 * settings. It would be fairly easy to fix this by keeping
1148 * our own parallel array or hash table.
1150 string = g_strconcat (variable, "=", value, NULL);
1151 result = putenv (string);
1155 #else /* G_OS_WIN32 */
1159 g_return_val_if_fail (variable != NULL, FALSE);
1160 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1161 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1162 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1164 if (!overwrite && g_getenv (variable) != NULL)
1167 /* We want to (if possible) set both the environment variable copy
1168 * kept by the C runtime and the one kept by the system.
1170 * We can't use only the C runtime's putenv or _wputenv() as that
1171 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1172 * (with main() and not wmain()). In a "main()" app the C runtime
1173 * initializes the C runtime's environment table by converting the
1174 * real (wide char) environment variables to system codepage, thus
1175 * breaking those that aren't representable in the system codepage.
1177 * As the C runtime's putenv() will also set the system copy, we do
1178 * the putenv() first, then call SetEnvironmentValueW ourselves.
1181 if (G_WIN32_HAVE_WIDECHAR_API ())
1183 wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1184 wchar_t *wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1185 gchar *tem = g_strconcat (variable, "=", value, NULL);
1186 wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1189 _wputenv (wassignment);
1190 g_free (wassignment);
1192 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1199 /* In the non-Unicode case (Win9x), just putenv() is good
1202 gchar *tem = g_strconcat (variable, "=", value, NULL);
1203 gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1207 retval = (putenv (cpassignment) == 0);
1209 g_free (cpassignment);
1214 #endif /* G_OS_WIN32 */
1219 /* According to the Single Unix Specification, environ is not in
1220 * any system header, although unistd.h often declares it.
1222 extern char **environ;
1228 * @variable: the environment variable to remove, must not contain '='.
1230 * Removes an environment variable from the environment.
1232 * Note that on some systems, when variables are overwritten, the memory
1233 * used for the previous variables and its value isn't reclaimed.
1234 * Furthermore, this function can't be guaranteed to operate in a
1240 g_unsetenv (const gchar *variable)
1244 #ifdef HAVE_UNSETENV
1245 g_return_if_fail (variable != NULL);
1246 g_return_if_fail (strchr (variable, '=') == NULL);
1248 unsetenv (variable);
1249 #else /* !HAVE_UNSETENV */
1253 g_return_if_fail (variable != NULL);
1254 g_return_if_fail (strchr (variable, '=') == NULL);
1256 len = strlen (variable);
1258 /* Mess directly with the environ array.
1259 * This seems to be the only portable way to do this.
1261 * Note that we remove *all* environment entries for
1262 * the variable name, not just the first.
1267 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1275 #endif /* !HAVE_UNSETENV */
1277 #else /* G_OS_WIN32 */
1279 g_return_if_fail (variable != NULL);
1280 g_return_if_fail (strchr (variable, '=') == NULL);
1281 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1283 if (G_WIN32_HAVE_WIDECHAR_API ())
1285 wchar_t *wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1286 gchar *tem = g_strconcat (variable, "=", NULL);
1287 wchar_t *wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1290 _wputenv (wassignment);
1291 g_free (wassignment);
1293 SetEnvironmentVariableW (wname, NULL);
1299 /* In the non-Unicode case (Win9x), just putenv() is good
1302 gchar *tem = g_strconcat (variable, "=", NULL);
1303 gchar *cpassignment = g_locale_from_utf8 (tem, -1, NULL, NULL, NULL);
1307 putenv (cpassignment);
1309 g_free (cpassignment);
1312 #endif /* G_OS_WIN32 */
1318 * Gets the names of all variables set in the environment.
1320 * Return: a NUL-terminated list of strings which must be freed
1321 * with g_strfreev().
1328 gchar **result, *eq;
1331 len = g_strv_length (environ);
1332 result = g_new0 (gchar *, len + 1);
1334 for (i = 0; i < len; i++)
1336 eq = strchr (environ[i], '=');
1337 result[i] = g_strndup (environ[i], eq - environ[i]);
1345 G_LOCK_DEFINE_STATIC (g_utils_global);
1347 static gchar *g_tmp_dir = NULL;
1348 static gchar *g_user_name = NULL;
1349 static gchar *g_real_name = NULL;
1350 static gchar *g_home_dir = NULL;
1353 /* System codepage versions of the above, kept at file level so that they,
1354 * too, are produced only once.
1356 static gchar *g_tmp_dir_cp = NULL;
1357 static gchar *g_user_name_cp = NULL;
1358 static gchar *g_real_name_cp = NULL;
1359 static gchar *g_home_dir_cp = NULL;
1362 static gchar *g_user_data_dir = NULL;
1363 static gchar **g_system_data_dirs = NULL;
1364 static gchar *g_user_cache_dir = NULL;
1365 static gchar *g_user_config_dir = NULL;
1366 static gchar **g_system_config_dirs = NULL;
1371 get_special_folder (int csidl)
1375 wchar_t wc[MAX_PATH+1];
1378 LPITEMIDLIST pidl = NULL;
1380 gchar *retval = NULL;
1382 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1385 if (G_WIN32_HAVE_WIDECHAR_API ())
1387 b = SHGetPathFromIDListW (pidl, path.wc);
1389 retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
1393 b = SHGetPathFromIDListA (pidl, path.c);
1395 retval = g_locale_to_utf8 (path.c, -1, NULL, NULL, NULL);
1397 CoTaskMemFree (pidl);
1404 /* HOLDS: g_utils_global_lock */
1406 g_get_any_init (void)
1410 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1412 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1414 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1420 g_tmp_dir = g_strdup (P_tmpdir);
1421 k = strlen (g_tmp_dir);
1422 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1423 g_tmp_dir[k - 1] = '\0';
1430 g_tmp_dir = g_strdup ("/tmp");
1431 #else /* G_OS_WIN32 */
1432 g_tmp_dir = g_strdup ("\\");
1433 #endif /* G_OS_WIN32 */
1437 /* We check $HOME first for Win32, though it is a last resort for Unix
1438 * where we prefer the results of getpwuid().
1440 g_home_dir = g_strdup (g_getenv ("HOME"));
1442 /* Only believe HOME if it is an absolute path and exists */
1445 if (!(g_path_is_absolute (g_home_dir) &&
1446 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1448 g_free (g_home_dir);
1453 /* In case HOME is Unix-style (it happens), convert it to
1459 while ((p = strchr (g_home_dir, '/')) != NULL)
1465 /* USERPROFILE is probably the closest equivalent to $HOME? */
1466 if (g_getenv ("USERPROFILE") != NULL)
1467 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1471 g_home_dir = get_special_folder (CSIDL_PROFILE);
1475 /* At least at some time, HOMEDRIVE and HOMEPATH were used
1476 * to point to the home directory, I think. But on Windows
1477 * 2000 HOMEDRIVE seems to be equal to SYSTEMDRIVE, and
1478 * HOMEPATH is its root "\"?
1480 if (g_getenv ("HOMEDRIVE") != NULL && g_getenv ("HOMEPATH") != NULL)
1481 g_home_dir = g_strconcat (g_getenv ("HOMEDRIVE"),
1482 g_getenv ("HOMEPATH"),
1485 #endif /* G_OS_WIN32 */
1489 struct passwd *pw = NULL;
1490 gpointer buffer = NULL;
1493 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1495 # ifdef _SC_GETPW_R_SIZE_MAX
1496 /* This reurns the maximum length */
1497 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1501 # else /* _SC_GETPW_R_SIZE_MAX */
1503 # endif /* _SC_GETPW_R_SIZE_MAX */
1508 /* we allocate 6 extra bytes to work around a bug in
1509 * Mac OS < 10.3. See #156446
1511 buffer = g_malloc (bufsize + 6);
1514 # ifdef HAVE_POSIX_GETPWUID_R
1515 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1516 error = error < 0 ? errno : error;
1517 # else /* HAVE_NONPOSIX_GETPWUID_R */
1518 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1519 # if defined(_AIX) || defined(__hpux)
1520 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1521 pw = error == 0 ? &pwd : NULL;
1523 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1524 error = pw ? 0 : errno;
1526 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1530 /* we bail out prematurely if the user id can't be found
1531 * (should be pretty rare case actually), or if the buffer
1532 * should be sufficiently big and lookups are still not
1535 if (error == 0 || error == ENOENT)
1537 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1538 (gulong) getuid ());
1541 if (bufsize > 32 * 1024)
1543 g_warning ("getpwuid_r(): failed due to: %s.",
1544 g_strerror (error));
1552 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1557 pw = getpwuid (getuid ());
1562 g_user_name = g_strdup (pw->pw_name);
1564 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1566 gchar **gecos_fields;
1569 /* split the gecos field and substitute '&' */
1570 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1571 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1572 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1573 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1574 g_strfreev (gecos_fields);
1575 g_strfreev (name_parts);
1579 g_home_dir = g_strdup (pw->pw_dir);
1584 #else /* !HAVE_PWD_H */
1587 if (G_WIN32_HAVE_WIDECHAR_API ())
1589 guint len = UNLEN+1;
1590 wchar_t buffer[UNLEN+1];
1592 if (GetUserNameW (buffer, (LPDWORD) &len))
1594 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1595 g_real_name = g_strdup (g_user_name);
1600 guint len = UNLEN+1;
1601 char buffer[UNLEN+1];
1603 if (GetUserNameA (buffer, (LPDWORD) &len))
1605 g_user_name = g_locale_to_utf8 (buffer, -1, NULL, NULL, NULL);
1606 g_real_name = g_strdup (g_user_name);
1609 #endif /* G_OS_WIN32 */
1611 #endif /* !HAVE_PWD_H */
1615 g_home_dir = g_strdup (g_getenv ("HOME"));
1619 /* change '\\' in %HOME% to '/' */
1620 g_strdelimit (g_home_dir, "\\",'/');
1623 g_user_name = g_strdup ("somebody");
1625 g_real_name = g_strdup ("Unknown");
1628 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1629 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1630 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1633 g_tmp_dir_cp = g_strdup ("\\");
1634 if (!g_user_name_cp)
1635 g_user_name_cp = g_strdup ("somebody");
1636 if (!g_real_name_cp)
1637 g_real_name_cp = g_strdup ("Unknown");
1639 /* home_dir might be NULL, unlike tmp_dir, user_name and
1643 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1645 g_home_dir_cp = NULL;
1646 #endif /* G_OS_WIN32 */
1653 * Gets the user name of the current user. The encoding of the returned
1654 * string is system-defined. On UNIX, it might be the preferred file name
1655 * encoding, or something else, and there is no guarantee that it is even
1656 * consistent on a machine. On Windows, it is always UTF-8.
1658 * Returns: the user name of the current user.
1660 G_CONST_RETURN gchar*
1661 g_get_user_name (void)
1663 G_LOCK (g_utils_global);
1666 G_UNLOCK (g_utils_global);
1674 * Gets the real name of the user. This usually comes from the user's entry
1675 * in the <filename>passwd</filename> file. The encoding of the returned
1676 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1677 * If the real user name cannot be determined, the string "Unknown" is
1680 * Returns: the user's real name.
1682 G_CONST_RETURN gchar*
1683 g_get_real_name (void)
1685 G_LOCK (g_utils_global);
1688 G_UNLOCK (g_utils_global);
1696 * Gets the current user's home directory.
1698 * Note that in contrast to traditional UNIX tools, this function
1699 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1700 * environment variable.
1702 * Returns: the current user's home directory.
1704 G_CONST_RETURN gchar*
1705 g_get_home_dir (void)
1707 G_LOCK (g_utils_global);
1710 G_UNLOCK (g_utils_global);
1718 * Gets the directory to use for temporary files. This is found from
1719 * inspecting the environment variables <envar>TMPDIR</envar>,
1720 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1721 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1722 * The encoding of the returned string is system-defined. On Windows,
1723 * it is always UTF-8. The return value is never %NULL.
1725 * Returns: the directory to use for temporary files.
1727 G_CONST_RETURN gchar*
1728 g_get_tmp_dir (void)
1730 G_LOCK (g_utils_global);
1733 G_UNLOCK (g_utils_global);
1738 G_LOCK_DEFINE_STATIC (g_prgname);
1739 static gchar *g_prgname = NULL;
1744 * Gets the name of the program. This name should <emphasis>not</emphasis>
1745 * be localized, contrast with g_get_application_name().
1746 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1747 * which is called by gtk_init(). The program name is found by taking
1748 * the last component of <literal>argv[0]</literal>.)
1750 * Returns: the name of the program. The returned string belongs
1751 * to GLib and must not be modified or freed.
1754 g_get_prgname (void)
1760 G_UNLOCK (g_prgname);
1767 * @prgname: the name of the program.
1769 * Sets the name of the program. This name should <emphasis>not</emphasis>
1770 * be localized, contrast with g_set_application_name(). Note that for
1771 * thread-safety reasons this function can only be called once.
1774 g_set_prgname (const gchar *prgname)
1778 g_prgname = g_strdup (prgname);
1779 G_UNLOCK (g_prgname);
1782 G_LOCK_DEFINE_STATIC (g_application_name);
1783 static gchar *g_application_name = NULL;
1786 * g_get_application_name:
1788 * Gets a human-readable name for the application, as set by
1789 * g_set_application_name(). This name should be localized if
1790 * possible, and is intended for display to the user. Contrast with
1791 * g_get_prgname(), which gets a non-localized name. If
1792 * g_set_application_name() has not been called, returns the result of
1793 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1796 * Return value: human-readable application name. may return %NULL
1800 G_CONST_RETURN gchar*
1801 g_get_application_name (void)
1805 G_LOCK (g_application_name);
1806 retval = g_application_name;
1807 G_UNLOCK (g_application_name);
1810 return g_get_prgname ();
1816 * g_set_application_name:
1817 * @application_name: localized name of the application
1819 * Sets a human-readable name for the application. This name should be
1820 * localized if possible, and is intended for display to the user.
1821 * Contrast with g_set_prgname(), which sets a non-localized name.
1822 * g_set_prgname() will be called automatically by gtk_init(),
1823 * but g_set_application_name() will not.
1825 * Note that for thread safety reasons, this function can only
1828 * The application name will be used in contexts such as error messages,
1829 * or when displaying an application's name in the task list.
1833 g_set_application_name (const gchar *application_name)
1835 gboolean already_set = FALSE;
1837 G_LOCK (g_application_name);
1838 if (g_application_name)
1841 g_application_name = g_strdup (application_name);
1842 G_UNLOCK (g_application_name);
1845 g_warning ("g_set_application() name called multiple times");
1849 * g_get_user_data_dir:
1851 * Returns a base directory in which to access application data such
1852 * as icons that is customized for a particular user.
1854 * On UNIX platforms this is determined using the mechanisms described in
1855 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1856 * XDG Base Directory Specification</ulink>
1858 * Return value: a string owned by GLib that must not be modified
1862 G_CONST_RETURN gchar*
1863 g_get_user_data_dir (void)
1867 G_LOCK (g_utils_global);
1869 if (!g_user_data_dir)
1872 data_dir = get_special_folder (CSIDL_PERSONAL);
1874 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1877 if (data_dir && data_dir[0])
1878 data_dir = g_strdup (data_dir);
1884 data_dir = g_build_filename (g_home_dir, ".local",
1888 g_user_data_dir = data_dir;
1891 data_dir = g_user_data_dir;
1893 G_UNLOCK (g_utils_global);
1899 * g_get_user_config_dir:
1901 * Returns a base directory in which to store user-specific application
1902 * configuration information such as user preferences and settings.
1904 * On UNIX platforms this is determined using the mechanisms described in
1905 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1906 * XDG Base Directory Specification</ulink>
1908 * Return value: a string owned by GLib that must not be modified
1912 G_CONST_RETURN gchar*
1913 g_get_user_config_dir (void)
1917 G_LOCK (g_utils_global);
1919 if (!g_user_config_dir)
1922 config_dir = get_special_folder (CSIDL_APPDATA);
1924 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1927 if (config_dir && config_dir[0])
1928 config_dir = g_strdup (config_dir);
1934 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1936 g_user_config_dir = config_dir;
1939 config_dir = g_user_config_dir;
1941 G_UNLOCK (g_utils_global);
1947 * g_get_user_cache_dir:
1949 * Returns a base directory in which to store non-essential, cached
1950 * data specific to particular user.
1952 * On UNIX platforms this is determined using the mechanisms described in
1953 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1954 * XDG Base Directory Specification</ulink>
1956 * Return value: a string owned by GLib that must not be modified
1960 G_CONST_RETURN gchar*
1961 g_get_user_cache_dir (void)
1965 G_LOCK (g_utils_global);
1967 if (!g_user_cache_dir)
1970 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1972 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1974 if (cache_dir && cache_dir[0])
1975 cache_dir = g_strdup (cache_dir);
1981 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1983 g_user_cache_dir = cache_dir;
1986 cache_dir = g_user_cache_dir;
1988 G_UNLOCK (g_utils_global);
1994 * g_get_system_data_dirs:
1996 * Returns an ordered list of base directories in which to access
1997 * system-wide application data.
1999 * On UNIX platforms this is determined using the mechanisms described in
2000 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2001 * XDG Base Directory Specification</ulink>
2003 * Return value: a %NULL-terminated array of strings owned by GLib that must
2004 * not be modified or freed.
2007 G_CONST_RETURN gchar * G_CONST_RETURN *
2008 g_get_system_data_dirs (void)
2010 gchar *data_dirs, **data_dir_vector;
2012 G_LOCK (g_utils_global);
2014 if (!g_system_data_dirs)
2017 data_dirs = g_strconcat (get_special_folder (CSIDL_COMMON_APPDATA),
2018 G_SEARCHPATH_SEPARATOR_S,
2019 get_special_folder (CSIDL_COMMON_DOCUMENTS),
2022 data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2024 if (!data_dirs || !data_dirs[0])
2025 data_dirs = "/usr/local/share/:/usr/share/";
2027 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2029 g_system_data_dirs = data_dir_vector;
2032 data_dir_vector = g_system_data_dirs;
2034 G_UNLOCK (g_utils_global);
2036 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2040 * g_get_system_config_dirs:
2042 * Returns an ordered list of base directories in which to access
2043 * system-wide configuration information.
2045 * On UNIX platforms this is determined using the mechanisms described in
2046 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2047 * XDG Base Directory Specification</ulink>
2049 * Return value: a %NULL-terminated array of strings owned by GLib that must
2050 * not be modified or freed.
2053 G_CONST_RETURN gchar * G_CONST_RETURN *
2054 g_get_system_config_dirs (void)
2056 gchar *conf_dirs, **conf_dir_vector;
2058 G_LOCK (g_utils_global);
2060 if (!g_system_config_dirs)
2063 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2065 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2067 if (!conf_dirs || !conf_dirs[0])
2068 conf_dirs = "/etc/xdg";
2070 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2072 g_system_config_dirs = conf_dir_vector;
2075 conf_dir_vector = g_system_config_dirs;
2076 G_UNLOCK (g_utils_global);
2078 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2081 static GHashTable *alias_table = NULL;
2083 /* read an alias file for the locales */
2085 read_aliases (gchar *file)
2091 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2092 fp = fopen (file,"r");
2095 while (fgets (buf, 256, fp))
2101 /* Line is a comment */
2102 if ((buf[0] == '#') || (buf[0] == '\0'))
2105 /* Reads first column */
2106 for (p = buf, q = NULL; *p; p++) {
2107 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2110 while ((*q == '\t') || (*q == ' ')) {
2116 /* The line only had one column */
2117 if (!q || *q == '\0')
2120 /* Read second column */
2121 for (p = q; *p; p++) {
2122 if ((*p == '\t') || (*p == ' ')) {
2128 /* Add to alias table if necessary */
2129 if (!g_hash_table_lookup (alias_table, buf)) {
2130 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2137 unalias_lang (char *lang)
2143 read_aliases ("/usr/share/locale/locale.alias");
2146 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2151 static gboolean said_before = FALSE;
2153 g_warning ("Too many alias levels for a locale, "
2154 "may indicate a loop");
2162 /* Mask for components of locale spec. The ordering here is from
2163 * least significant to most significant
2167 COMPONENT_CODESET = 1 << 0,
2168 COMPONENT_TERRITORY = 1 << 1,
2169 COMPONENT_MODIFIER = 1 << 2
2172 /* Break an X/Open style locale specification into components
2175 explode_locale (const gchar *locale,
2181 const gchar *uscore_pos;
2182 const gchar *at_pos;
2183 const gchar *dot_pos;
2187 uscore_pos = strchr (locale, '_');
2188 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2189 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2193 mask |= COMPONENT_MODIFIER;
2194 *modifier = g_strdup (at_pos);
2197 at_pos = locale + strlen (locale);
2201 mask |= COMPONENT_CODESET;
2202 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2209 mask |= COMPONENT_TERRITORY;
2210 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2213 uscore_pos = dot_pos;
2215 *language = g_strndup (locale, uscore_pos - locale);
2221 * Compute all interesting variants for a given locale name -
2222 * by stripping off different components of the value.
2224 * For simplicity, we assume that the locale is in
2225 * X/Open format: language[_territory][.codeset][@modifier]
2227 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2228 * as well. We could just copy the code from glibc wholesale
2229 * but it is big, ugly, and complicated, so I'm reluctant
2230 * to do so when this should handle 99% of the time...
2233 _g_compute_locale_variants (const gchar *locale)
2235 GSList *retval = NULL;
2245 g_return_val_if_fail (locale != NULL, NULL);
2247 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2249 /* Iterate through all possible combinations, from least attractive
2250 * to most attractive.
2252 for (i = 0; i <= mask; i++)
2253 if ((i & ~mask) == 0)
2255 gchar *val = g_strconcat (language,
2256 (i & COMPONENT_TERRITORY) ? territory : "",
2257 (i & COMPONENT_CODESET) ? codeset : "",
2258 (i & COMPONENT_MODIFIER) ? modifier : "",
2260 retval = g_slist_prepend (retval, val);
2264 if (mask & COMPONENT_CODESET)
2266 if (mask & COMPONENT_TERRITORY)
2268 if (mask & COMPONENT_MODIFIER)
2274 /* The following is (partly) taken from the gettext package.
2275 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2277 static const gchar *
2278 guess_category_value (const gchar *category_name)
2280 const gchar *retval;
2282 /* The highest priority value is the `LANGUAGE' environment
2283 variable. This is a GNU extension. */
2284 retval = g_getenv ("LANGUAGE");
2285 if ((retval != NULL) && (retval[0] != '\0'))
2288 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2289 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2290 systems this can be done by the `setlocale' function itself. */
2292 /* Setting of LC_ALL overwrites all other. */
2293 retval = g_getenv ("LC_ALL");
2294 if ((retval != NULL) && (retval[0] != '\0'))
2297 /* Next comes the name of the desired category. */
2298 retval = g_getenv (category_name);
2299 if ((retval != NULL) && (retval[0] != '\0'))
2302 /* Last possibility is the LANG environment variable. */
2303 retval = g_getenv ("LANG");
2304 if ((retval != NULL) && (retval[0] != '\0'))
2307 #ifdef G_PLATFORM_WIN32
2308 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2309 * LANG, which we already did above. Oh well. The main point of
2310 * calling g_win32_getlocale() is to get the thread's locale as used
2311 * by Windows and the Microsoft C runtime (in the "English_United
2312 * States" format) translated into the Unixish format.
2314 retval = g_win32_getlocale ();
2315 if ((retval != NULL) && (retval[0] != '\0'))
2322 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2324 struct _GLanguageNamesCache {
2326 gchar **language_names;
2330 language_names_cache_free (gpointer data)
2332 GLanguageNamesCache *cache = data;
2333 g_free (cache->languages);
2334 g_strfreev (cache->language_names);
2339 * g_get_language_names:
2341 * Computes a list of applicable locale names, which can be used to
2342 * e.g. construct locale-dependent filenames or search paths. The returned
2343 * list is sorted from most desirable to least desirable and always contains
2344 * the default locale "C".
2346 * For example, if LANGUAGE=de:en_US, then the returned list is
2347 * "de", "en_US", "en", "C".
2349 * This function consults the environment variables <envar>LANGUAGE</envar>,
2350 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2351 * to find the list of locales specified by the user.
2353 * Return value: a %NULL-terminated array of strings owned by GLib
2354 * that must not be modified or freed.
2358 G_CONST_RETURN gchar * G_CONST_RETURN *
2359 g_get_language_names (void)
2361 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2362 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2367 cache = g_new0 (GLanguageNamesCache, 1);
2368 g_static_private_set (&cache_private, cache, language_names_cache_free);
2371 value = guess_category_value ("LC_MESSAGES");
2375 if (!(cache->languages && strcmp (cache->languages, value) == 0))
2382 g_free (cache->languages);
2383 g_strfreev (cache->language_names);
2384 cache->languages = g_strdup (value);
2386 alist = g_strsplit (value, ":", 0);
2388 for (a = alist; *a; a++)
2390 gchar *b = unalias_lang (*a);
2391 list = g_slist_concat (list, _g_compute_locale_variants (b));
2394 list = g_slist_append (list, g_strdup ("C"));
2396 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
2397 for (l = list, i = 0; l; l = l->next, i++)
2398 languages[i] = l->data;
2399 languages[i] = NULL;
2401 g_slist_free (list);
2404 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
2409 * @v: a #gpointer key
2411 * Converts a gpointer to a hash value.
2412 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2413 * when using pointers as keys in a #GHashTable.
2415 * Returns: a hash value corresponding to the key.
2418 g_direct_hash (gconstpointer v)
2420 return GPOINTER_TO_UINT (v);
2426 * @v2: a key to compare with @v1.
2428 * Compares two #gpointer arguments and returns %TRUE if they are equal.
2429 * It can be passed to g_hash_table_new() as the @key_equal_func
2430 * parameter, when using pointers as keys in a #GHashTable.
2432 * Returns: %TRUE if the two keys match.
2435 g_direct_equal (gconstpointer v1,
2443 * @v1: a pointer to a #gint key.
2444 * @v2: a pointer to a #gint key to compare with @v1.
2446 * Compares the two #gint values being pointed to and returns
2447 * %TRUE if they are equal.
2448 * It can be passed to g_hash_table_new() as the @key_equal_func
2449 * parameter, when using pointers to integers as keys in a #GHashTable.
2451 * Returns: %TRUE if the two keys match.
2454 g_int_equal (gconstpointer v1,
2457 return *((const gint*) v1) == *((const gint*) v2);
2462 * @v: a pointer to a #gint key
2464 * Converts a pointer to a #gint to a hash value.
2465 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2466 * when using pointers to integers values as keys in a #GHashTable.
2468 * Returns: a hash value corresponding to the key.
2471 g_int_hash (gconstpointer v)
2473 return *(const gint*) v;
2477 * g_nullify_pointer:
2478 * @nullify_location: the memory address of the pointer.
2480 * Set the pointer at the specified location to %NULL.
2483 g_nullify_pointer (gpointer *nullify_location)
2485 g_return_if_fail (nullify_location != NULL);
2487 *nullify_location = NULL;
2493 * Get the codeset for the current locale.
2495 * Return value: a newly allocated string containing the name
2496 * of the codeset. This string must be freed with g_free().
2499 g_get_codeset (void)
2501 const gchar *charset;
2503 g_get_charset (&charset);
2505 return g_strdup (charset);
2508 /* This is called from g_thread_init(). It's used to
2509 * initialize some static data in a threadsafe way.
2512 _g_utils_thread_init (void)
2514 g_get_language_names ();
2519 #include <libintl.h>
2521 #ifdef G_PLATFORM_WIN32
2523 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
2525 static const gchar *
2526 _glib_get_locale_dir (void)
2528 static const gchar *cache = NULL;
2530 cache = g_win32_get_package_installation_subdirectory
2531 (GETTEXT_PACKAGE, dll_name, "lib\\locale");
2536 #undef GLIB_LOCALE_DIR
2537 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
2539 #endif /* G_PLATFORM_WIN32 */
2541 G_CONST_RETURN gchar *
2542 _glib_gettext (const gchar *str)
2544 static gboolean _glib_gettext_initialized = FALSE;
2546 if (!_glib_gettext_initialized)
2548 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
2549 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2550 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2552 _glib_gettext_initialized = TRUE;
2555 return dgettext (GETTEXT_PACKAGE, str);
2558 #endif /* ENABLE_NLS */
2562 /* Binary compatibility versions. Not for newly compiled code. */
2564 #undef g_find_program_in_path
2567 g_find_program_in_path (const gchar *program)
2569 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2570 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2573 g_free (utf8_program);
2574 if (utf8_retval == NULL)
2576 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2577 g_free (utf8_retval);
2582 #undef g_get_current_dir
2585 g_get_current_dir (void)
2587 gchar *utf8_dir = g_get_current_dir_utf8 ();
2588 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2595 G_CONST_RETURN gchar*
2596 g_getenv (const gchar *variable)
2598 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2599 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
2603 g_free (utf8_variable);
2606 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
2607 quark = g_quark_from_string (value);
2610 return g_quark_to_string (quark);
2616 g_setenv (const gchar *variable,
2620 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2621 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
2622 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
2624 g_free (utf8_variable);
2625 g_free (utf8_value);
2633 g_unsetenv (const gchar *variable)
2635 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2637 g_unsetenv_utf8 (utf8_variable);
2639 g_free (utf8_variable);
2642 #undef g_get_user_name
2644 G_CONST_RETURN gchar*
2645 g_get_user_name (void)
2647 G_LOCK (g_utils_global);
2650 G_UNLOCK (g_utils_global);
2652 return g_user_name_cp;
2655 #undef g_get_real_name
2657 G_CONST_RETURN gchar*
2658 g_get_real_name (void)
2660 G_LOCK (g_utils_global);
2663 G_UNLOCK (g_utils_global);
2665 return g_real_name_cp;
2668 #undef g_get_home_dir
2670 G_CONST_RETURN gchar*
2671 g_get_home_dir (void)
2673 G_LOCK (g_utils_global);
2676 G_UNLOCK (g_utils_global);
2678 return g_home_dir_cp;
2681 #undef g_get_tmp_dir
2683 G_CONST_RETURN gchar*
2684 g_get_tmp_dir (void)
2686 G_LOCK (g_utils_global);
2689 G_UNLOCK (g_utils_global);
2691 return g_tmp_dir_cp;