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.
41 #include <ctype.h> /* For tolower() */
46 #include <sys/types.h>
47 #ifdef HAVE_SYS_PARAM_H
48 #include <sys/param.h>
50 #ifdef HAVE_CRT_EXTERNS_H
51 #include <crt_externs.h> /* for _NSGetEnviron */
54 /* implement gutils's inline functions
56 #define G_IMPLEMENT_INLINES 1
59 #include "gprintfint.h"
60 #include "gthreadprivate.h"
64 #define G_PATH_LENGTH MAXPATHLEN
65 #elif defined (PATH_MAX)
66 #define G_PATH_LENGTH PATH_MAX
67 #elif defined (_PC_PATH_MAX)
68 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
70 #define G_PATH_LENGTH 2048
73 #ifdef G_PLATFORM_WIN32
74 # define STRICT /* Strict typing, please */
77 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
78 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
79 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
81 # include <lmcons.h> /* For UNLEN */
82 #endif /* G_PLATFORM_WIN32 */
87 /* older SDK (e.g. msvc 5.0) does not have these*/
88 # ifndef CSIDL_INTERNET_CACHE
89 # define CSIDL_INTERNET_CACHE 32
91 # ifndef CSIDL_COMMON_APPDATA
92 # define CSIDL_COMMON_APPDATA 35
94 # ifndef CSIDL_COMMON_DOCUMENTS
95 # define CSIDL_COMMON_DOCUMENTS 46
97 # ifndef CSIDL_PROFILE
98 # define CSIDL_PROFILE 40
100 # include <process.h>
104 #include <langinfo.h>
107 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
111 const guint glib_major_version = GLIB_MAJOR_VERSION;
112 const guint glib_minor_version = GLIB_MINOR_VERSION;
113 const guint glib_micro_version = GLIB_MICRO_VERSION;
114 const guint glib_interface_age = GLIB_INTERFACE_AGE;
115 const guint glib_binary_age = GLIB_BINARY_AGE;
117 #ifdef G_PLATFORM_WIN32
119 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
124 * glib_check_version:
125 * @required_major: the required major version.
126 * @required_minor: the required minor version.
127 * @required_micro: the required micro version.
129 * Checks that the GLib library in use is compatible with the
130 * given version. Generally you would pass in the constants
131 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
132 * as the three arguments to this function; that produces
133 * a check that the library in use is compatible with
134 * the version of GLib the application or module was compiled
137 * Compatibility is defined by two things: first the version
138 * of the running library is newer than the version
139 * @required_major.required_minor.@required_micro. Second
140 * the running library must be binary compatible with the
141 * version @required_major.required_minor.@required_micro
142 * (same major version.)
144 * Return value: %NULL if the GLib library is compatible with the
145 * given version, or a string describing the version mismatch.
146 * The returned string is owned by GLib and must not be modified
152 glib_check_version (guint required_major,
153 guint required_minor,
154 guint required_micro)
156 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
157 gint required_effective_micro = 100 * required_minor + required_micro;
159 if (required_major > GLIB_MAJOR_VERSION)
160 return "GLib version too old (major mismatch)";
161 if (required_major < GLIB_MAJOR_VERSION)
162 return "GLib version too new (major mismatch)";
163 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
164 return "GLib version too new (micro mismatch)";
165 if (required_effective_micro > glib_effective_micro)
166 return "GLib version too old (micro mismatch)";
170 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
173 * @dest: the destination address to copy the bytes to.
174 * @src: the source address to copy the bytes from.
175 * @len: the number of bytes to copy.
177 * Copies a block of memory @len bytes long, from @src to @dest.
178 * The source and destination areas may overlap.
180 * In order to use this function, you must include
181 * <filename>string.h</filename> yourself, because this macro will
182 * typically simply resolve to memmove() and GLib does not include
183 * <filename>string.h</filename> for you.
186 g_memmove (gpointer dest,
190 gchar* destptr = dest;
191 const gchar* srcptr = src;
192 if (src + len < dest || dest + len < src)
194 bcopy (src, dest, len);
197 else if (dest <= src)
200 *(destptr++) = *(srcptr++);
207 *(--destptr) = *(--srcptr);
210 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
218 * @func: the function to call on normal program termination.
220 * Specifies a function to be called at normal program termination.
222 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
223 * macro that maps to a call to the atexit() function in the C
224 * library. This means that in case the code that calls g_atexit(),
225 * i.e. atexit(), is in a DLL, the function will be called when the
226 * DLL is detached from the program. This typically makes more sense
227 * than that the function is called when the GLib DLL is detached,
228 * which happened earlier when g_atexit() was a function in the GLib
231 * The behaviour of atexit() in the context of dynamically loaded
232 * modules is not formally specified and varies wildly.
234 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
235 * loaded module which is unloaded before the program terminates might
236 * well cause a crash at program exit.
238 * Some POSIX systems implement atexit() like Windows, and have each
239 * dynamically loaded module maintain an own atexit chain that is
240 * called when the module is unloaded.
242 * On other POSIX systems, before a dynamically loaded module is
243 * unloaded, the registered atexit functions (if any) residing in that
244 * module are called, regardless where the code that registered them
245 * resided. This is presumably the most robust approach.
247 * As can be seen from the above, for portability it's best to avoid
248 * calling g_atexit() (or atexit()) except in the main executable of a
252 g_atexit (GVoidFunc func)
255 const gchar *error = NULL;
257 /* keep this in sync with glib.h */
259 #ifdef G_NATIVE_ATEXIT
260 result = ATEXIT (func);
262 error = g_strerror (errno);
263 #elif defined (HAVE_ATEXIT)
264 # ifdef NeXT /* @#%@! NeXTStep */
265 result = !atexit ((void (*)(void)) func);
267 error = g_strerror (errno);
269 result = atexit ((void (*)(void)) func);
271 error = g_strerror (errno);
273 #elif defined (HAVE_ON_EXIT)
274 result = on_exit ((void (*)(int, void *)) func, NULL);
276 error = g_strerror (errno);
279 error = "no implementation";
280 #endif /* G_NATIVE_ATEXIT */
283 g_error ("Could not register atexit() function: %s", error);
286 /* Based on execvp() from GNU Libc.
287 * Some of this code is cut-and-pasted into gspawn.c
291 my_strchrnul (const gchar *str,
294 gchar *p = (gchar*)str;
295 while (*p && (*p != c))
303 static gchar *inner_find_program_in_path (const gchar *program);
306 g_find_program_in_path (const gchar *program)
308 const gchar *last_dot = strrchr (program, '.');
310 if (last_dot == NULL ||
311 strchr (last_dot, '\\') != NULL ||
312 strchr (last_dot, '/') != NULL)
314 const gint program_length = strlen (program);
315 gchar *pathext = g_build_path (";",
316 ".exe;.cmd;.bat;.com",
317 g_getenv ("PATHEXT"),
320 gchar *decorated_program;
326 gchar *q = my_strchrnul (p, ';');
328 decorated_program = g_malloc (program_length + (q-p) + 1);
329 memcpy (decorated_program, program, program_length);
330 memcpy (decorated_program+program_length, p, q-p);
331 decorated_program [program_length + (q-p)] = '\0';
333 retval = inner_find_program_in_path (decorated_program);
334 g_free (decorated_program);
342 } while (*p++ != '\0');
347 return inner_find_program_in_path (program);
353 * g_find_program_in_path:
354 * @program: a program name in the GLib file name encoding
356 * Locates the first executable named @program in the user's path, in the
357 * same way that execvp() would locate it. Returns an allocated string
358 * with the absolute path name, or %NULL if the program is not found in
359 * the path. If @program is already an absolute path, returns a copy of
360 * @program if @program exists and is executable, and %NULL otherwise.
362 * On Windows, if @program does not have a file type suffix, tries
363 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
364 * the <envar>PATHEXT</envar> environment variable.
366 * On Windows, it looks for the file in the same way as CreateProcess()
367 * would. This means first in the directory where the executing
368 * program was loaded from, then in the current directory, then in the
369 * Windows 32-bit system directory, then in the Windows directory, and
370 * finally in the directories in the <envar>PATH</envar> environment
371 * variable. If the program is found, the return value contains the
372 * full name including the type suffix.
374 * Return value: absolute path, or %NULL
378 inner_find_program_in_path (const gchar *program)
381 g_find_program_in_path (const gchar *program)
384 const gchar *path, *p;
385 gchar *name, *freeme;
387 const gchar *path_copy;
388 gchar *filename = NULL, *appdir = NULL;
389 gchar *sysdir = NULL, *windir = NULL;
391 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
397 g_return_val_if_fail (program != NULL, NULL);
399 /* If it is an absolute path, or a relative path including subdirectories,
400 * don't look in PATH.
402 if (g_path_is_absolute (program)
403 || strchr (program, G_DIR_SEPARATOR) != NULL
405 || strchr (program, '/') != NULL
409 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
410 !g_file_test (program, G_FILE_TEST_IS_DIR))
411 return g_strdup (program);
416 path = g_getenv ("PATH");
417 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
420 /* There is no `PATH' in the environment. The default
421 * search path in GNU libc is the current directory followed by
422 * the path `confstr' returns for `_CS_PATH'.
425 /* In GLib we put . last, for security, and don't use the
426 * unportable confstr(); UNIX98 does not actually specify
427 * what to search if PATH is unset. POSIX may, dunno.
430 path = "/bin:/usr/bin:.";
433 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
434 if (n > 0 && n < MAXPATHLEN)
435 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
437 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
438 if (n > 0 && n < MAXPATHLEN)
439 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
441 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
442 if (n > 0 && n < MAXPATHLEN)
443 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
447 appdir = g_path_get_dirname (filename);
451 path = g_strdup (path);
455 const gchar *tem = path;
456 path = g_strconcat (windir, ";", path, NULL);
457 g_free ((gchar *) tem);
463 const gchar *tem = path;
464 path = g_strconcat (sysdir, ";", path, NULL);
465 g_free ((gchar *) tem);
470 const gchar *tem = path;
471 path = g_strconcat (".;", path, NULL);
472 g_free ((gchar *) tem);
477 const gchar *tem = path;
478 path = g_strconcat (appdir, ";", path, NULL);
479 g_free ((gchar *) tem);
486 len = strlen (program) + 1;
487 pathlen = strlen (path);
488 freeme = name = g_malloc (pathlen + len + 1);
490 /* Copy the file name at the top, including '\0' */
491 memcpy (name + pathlen + 1, program, len);
492 name = name + pathlen;
493 /* And add the slash before the filename */
494 *name = G_DIR_SEPARATOR;
502 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
505 /* Two adjacent colons, or a colon at the beginning or the end
506 * of `PATH' means to search the current directory.
510 startp = memcpy (name - (p - path), path, p - path);
512 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
513 !g_file_test (startp, G_FILE_TEST_IS_DIR))
516 ret = g_strdup (startp);
519 g_free ((gchar *) path_copy);
524 while (*p++ != '\0');
528 g_free ((gchar *) path_copy);
535 debug_key_matches (const gchar *key,
539 for (; length; length--, key++, token++)
541 char k = (*key == '_') ? '-' : tolower (*key );
542 char t = (*token == '_') ? '-' : tolower (*token);
552 * g_parse_debug_string:
553 * @string: a list of debug options separated by colons, spaces, or
554 * commas; or the string "all" to set all flags.
555 * @keys: pointer to an array of #GDebugKey which associate
556 * strings with bit flags.
557 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
559 * Parses a string containing debugging options
560 * into a %guint containing bit flags. This is used
561 * within GDK and GTK+ to parse the debug options passed on the
562 * command line or through environment variables.
564 * Returns: the combined set of bit flags.
567 g_parse_debug_string (const gchar *string,
568 const GDebugKey *keys,
574 g_return_val_if_fail (string != NULL, 0);
576 /* this function is used by gmem.c/gslice.c initialization code,
577 * so introducing malloc dependencies here would require adaptions
578 * of those code portions.
581 if (!g_ascii_strcasecmp (string, "all"))
583 for (i=0; i<nkeys; i++)
584 result |= keys[i].value;
588 const gchar *p = string;
593 q = strpbrk (p, ":;, \t");
597 for (i = 0; i < nkeys; i++)
598 if (debug_key_matches (keys[i].key, p, q - p))
599 result |= keys[i].value;
612 * @file_name: the name of the file.
614 * Gets the name of the file without any leading directory components.
615 * It returns a pointer into the given file name string.
617 * Return value: the name of the file without any leading directory components.
619 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
620 * g_path_get_basename() allocates new memory for the returned string, unlike
621 * this function which returns a pointer into the argument.
623 G_CONST_RETURN gchar*
624 g_basename (const gchar *file_name)
626 register gchar *base;
628 g_return_val_if_fail (file_name != NULL, NULL);
630 base = strrchr (file_name, G_DIR_SEPARATOR);
634 gchar *q = strrchr (file_name, '/');
635 if (base == NULL || (q != NULL && q > base))
644 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
645 return (gchar*) file_name + 2;
646 #endif /* G_OS_WIN32 */
648 return (gchar*) file_name;
652 * g_path_get_basename:
653 * @file_name: the name of the file.
655 * Gets the last component of the filename. If @file_name ends with a
656 * directory separator it gets the component before the last slash. If
657 * @file_name consists only of directory separators (and on Windows,
658 * possibly a drive letter), a single separator is returned. If
659 * @file_name is empty, it gets ".".
661 * Return value: a newly allocated string containing the last component of
665 g_path_get_basename (const gchar *file_name)
667 register gssize base;
668 register gssize last_nonslash;
672 g_return_val_if_fail (file_name != NULL, NULL);
674 if (file_name[0] == '\0')
676 return g_strdup (".");
678 last_nonslash = strlen (file_name) - 1;
680 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
683 if (last_nonslash == -1)
684 /* string only containing slashes */
685 return g_strdup (G_DIR_SEPARATOR_S);
688 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
689 /* string only containing slashes and a drive */
690 return g_strdup (G_DIR_SEPARATOR_S);
691 #endif /* G_OS_WIN32 */
693 base = last_nonslash;
695 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
699 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
701 #endif /* G_OS_WIN32 */
703 len = last_nonslash - base;
704 retval = g_malloc (len + 1);
705 memcpy (retval, file_name + base + 1, len);
711 * g_path_is_absolute:
712 * @file_name: a file name.
714 * Returns %TRUE if the given @file_name is an absolute file name,
715 * i.e. it contains a full path from the root directory such as "/usr/local"
716 * on UNIX or "C:\windows" on Windows systems.
718 * Returns: %TRUE if @file_name is an absolute path.
721 g_path_is_absolute (const gchar *file_name)
723 g_return_val_if_fail (file_name != NULL, FALSE);
725 if (G_IS_DIR_SEPARATOR (file_name[0]))
729 /* Recognize drive letter on native Windows */
730 if (g_ascii_isalpha (file_name[0]) &&
731 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
733 #endif /* G_OS_WIN32 */
740 * @file_name: a file name.
742 * Returns a pointer into @file_name after the root component, i.e. after
743 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
744 * path it returns %NULL.
746 * Returns: a pointer into @file_name after the root component.
748 G_CONST_RETURN gchar*
749 g_path_skip_root (const gchar *file_name)
751 g_return_val_if_fail (file_name != NULL, NULL);
753 #ifdef G_PLATFORM_WIN32
754 /* Skip \\server\share or //server/share */
755 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
756 G_IS_DIR_SEPARATOR (file_name[1]) &&
758 !G_IS_DIR_SEPARATOR (file_name[2]))
762 p = strchr (file_name + 2, G_DIR_SEPARATOR);
765 gchar *q = strchr (file_name + 2, '/');
766 if (p == NULL || (q != NULL && q < p))
776 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
779 /* Possibly skip a backslash after the share name */
780 if (G_IS_DIR_SEPARATOR (file_name[0]))
783 return (gchar *)file_name;
788 /* Skip initial slashes */
789 if (G_IS_DIR_SEPARATOR (file_name[0]))
791 while (G_IS_DIR_SEPARATOR (file_name[0]))
793 return (gchar *)file_name;
798 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
799 return (gchar *)file_name + 3;
806 * g_path_get_dirname:
807 * @file_name: the name of the file.
809 * Gets the directory components of a file name. If the file name has no
810 * directory components "." is returned. The returned string should be
811 * freed when no longer needed.
813 * Returns: the directory components of the file.
816 g_path_get_dirname (const gchar *file_name)
818 register gchar *base;
821 g_return_val_if_fail (file_name != NULL, NULL);
823 base = strrchr (file_name, G_DIR_SEPARATOR);
826 gchar *q = strrchr (file_name, '/');
827 if (base == NULL || (q != NULL && q > base))
834 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
836 gchar drive_colon_dot[4];
838 drive_colon_dot[0] = file_name[0];
839 drive_colon_dot[1] = ':';
840 drive_colon_dot[2] = '.';
841 drive_colon_dot[3] = '\0';
843 return g_strdup (drive_colon_dot);
846 return g_strdup (".");
849 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
853 /* base points to the char before the last slash.
855 * In case file_name is the root of a drive (X:\) or a child of the
856 * root of a drive (X:\foo), include the slash.
858 * In case file_name is the root share of an UNC path
859 * (\\server\share), add a slash, returning \\server\share\ .
861 * In case file_name is a direct child of a share in an UNC path
862 * (\\server\share\foo), include the slash after the share name,
863 * returning \\server\share\ .
865 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
867 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
868 G_IS_DIR_SEPARATOR (file_name[1]) &&
870 !G_IS_DIR_SEPARATOR (file_name[2]) &&
871 base >= file_name + 2)
873 const gchar *p = file_name + 2;
874 while (*p && !G_IS_DIR_SEPARATOR (*p))
878 len = (guint) strlen (file_name) + 1;
879 base = g_new (gchar, len + 1);
880 strcpy (base, file_name);
881 base[len-1] = G_DIR_SEPARATOR;
885 if (G_IS_DIR_SEPARATOR (*p))
888 while (*p && !G_IS_DIR_SEPARATOR (*p))
896 len = (guint) 1 + base - file_name;
898 base = g_new (gchar, len + 1);
899 g_memmove (base, file_name, len);
908 * Gets the current directory.
909 * The returned string should be freed when no longer needed. The encoding
910 * of the returned string is system defined. On Windows, it is always UTF-8.
912 * Returns: the current directory.
915 g_get_current_dir (void)
920 wchar_t dummy[2], *wdir;
923 len = GetCurrentDirectoryW (2, dummy);
924 wdir = g_new (wchar_t, len);
926 if (GetCurrentDirectoryW (len, wdir) == len - 1)
927 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
932 dir = g_strdup ("\\");
938 gchar *buffer = NULL;
940 static gulong max_len = 0;
943 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
945 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
946 * and, if that wasn't bad enough, hangs in doing so.
948 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
949 buffer = g_new (gchar, max_len + 1);
951 dir = getwd (buffer);
952 #else /* !sun || !HAVE_GETCWD */
953 while (max_len < G_MAXULONG / 2)
955 buffer = g_new (gchar, max_len + 1);
957 dir = getcwd (buffer, max_len);
959 if (dir || errno != ERANGE)
965 #endif /* !sun || !HAVE_GETCWD */
967 if (!dir || !*buffer)
969 /* hm, should we g_error() out here?
970 * this can happen if e.g. "./" has mode \0000
972 buffer[0] = G_DIR_SEPARATOR;
976 dir = g_strdup (buffer);
985 * @variable: the environment variable to get, in the GLib file name encoding.
987 * Returns the value of an environment variable. The name and value
988 * are in the GLib file name encoding. On UNIX, this means the actual
989 * bytes which might or might not be in some consistent character set
990 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
991 * environment variable's value contains references to other
992 * environment variables, they are expanded.
994 * Return value: the value of the environment variable, or %NULL if
995 * the environment variable is not found. The returned string may be
996 * overwritten by the next call to g_getenv(), g_setenv() or
999 G_CONST_RETURN gchar*
1000 g_getenv (const gchar *variable)
1004 g_return_val_if_fail (variable != NULL, NULL);
1006 return getenv (variable);
1008 #else /* G_OS_WIN32 */
1012 wchar_t dummy[2], *wname, *wvalue;
1015 g_return_val_if_fail (variable != NULL, NULL);
1016 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1018 /* On Windows NT, it is relatively typical that environment
1019 * variables contain references to other environment variables. If
1020 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1021 * environment variables would be stored in the Registry as
1022 * REG_EXPAND_SZ type values, and would then get automatically
1023 * expanded before a program sees them. But there is broken software
1024 * that stores environment variables as REG_SZ values even if they
1025 * contain references to other environment variables.)
1028 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1030 len = GetEnvironmentVariableW (wname, dummy, 2);
1040 wvalue = g_new (wchar_t, len);
1042 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1049 if (wcschr (wvalue, L'%') != NULL)
1051 wchar_t *tem = wvalue;
1053 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1057 wvalue = g_new (wchar_t, len);
1059 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1069 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1074 quark = g_quark_from_string (value);
1077 return g_quark_to_string (quark);
1079 #endif /* G_OS_WIN32 */
1082 /* _g_getenv_nomalloc
1083 * this function does a getenv() without doing any kind of allocation
1084 * through glib. it's suitable for chars <= 127 only (both, for the
1085 * variable name and the contents) and for contents < 1024 chars in
1086 * length. also, it aliases "" to a NULL return value.
1089 _g_getenv_nomalloc (const gchar *variable,
1092 const gchar *retval = getenv (variable);
1093 if (retval && retval[0])
1095 gint l = strlen (retval);
1098 strncpy (buffer, retval, l);
1108 * @variable: the environment variable to set, must not contain '='.
1109 * @value: the value for to set the variable to.
1110 * @overwrite: whether to change the variable if it already exists.
1112 * Sets an environment variable. Both the variable's name and value
1113 * should be in the GLib file name encoding. On UNIX, this means that
1114 * they can be any sequence of bytes. On Windows, they should be in
1117 * Note that on some systems, when variables are overwritten, the memory
1118 * used for the previous variables and its value isn't reclaimed.
1120 * Returns: %FALSE if the environment variable couldn't be set.
1125 g_setenv (const gchar *variable,
1136 g_return_val_if_fail (variable != NULL, FALSE);
1137 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1140 result = setenv (variable, value, overwrite);
1142 if (!overwrite && getenv (variable) != NULL)
1145 /* This results in a leak when you overwrite existing
1146 * settings. It would be fairly easy to fix this by keeping
1147 * our own parallel array or hash table.
1149 string = g_strconcat (variable, "=", value, NULL);
1150 result = putenv (string);
1154 #else /* G_OS_WIN32 */
1157 wchar_t *wname, *wvalue, *wassignment;
1160 g_return_val_if_fail (variable != NULL, FALSE);
1161 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1162 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1163 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1165 if (!overwrite && g_getenv (variable) != NULL)
1168 /* We want to (if possible) set both the environment variable copy
1169 * kept by the C runtime and the one kept by the system.
1171 * We can't use only the C runtime's putenv or _wputenv() as that
1172 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1173 * (with main() and not wmain()). In a "main()" app the C runtime
1174 * initializes the C runtime's environment table by converting the
1175 * real (wide char) environment variables to system codepage, thus
1176 * breaking those that aren't representable in the system codepage.
1178 * As the C runtime's putenv() will also set the system copy, we do
1179 * the putenv() first, then call SetEnvironmentValueW ourselves.
1182 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1183 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1184 tem = g_strconcat (variable, "=", value, NULL);
1185 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1188 _wputenv (wassignment);
1189 g_free (wassignment);
1191 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1198 #endif /* G_OS_WIN32 */
1201 #ifdef HAVE__NSGETENVIRON
1202 #define environ (*_NSGetEnviron())
1203 #elif !defined(G_OS_WIN32)
1205 /* According to the Single Unix Specification, environ is not in
1206 * any system header, although unistd.h often declares it.
1208 extern char **environ;
1213 * @variable: the environment variable to remove, must not contain '='.
1215 * Removes an environment variable from the environment.
1217 * Note that on some systems, when variables are overwritten, the memory
1218 * used for the previous variables and its value isn't reclaimed.
1219 * Furthermore, this function can't be guaranteed to operate in a
1225 g_unsetenv (const gchar *variable)
1229 #ifdef HAVE_UNSETENV
1230 g_return_if_fail (variable != NULL);
1231 g_return_if_fail (strchr (variable, '=') == NULL);
1233 unsetenv (variable);
1234 #else /* !HAVE_UNSETENV */
1238 g_return_if_fail (variable != NULL);
1239 g_return_if_fail (strchr (variable, '=') == NULL);
1241 len = strlen (variable);
1243 /* Mess directly with the environ array.
1244 * This seems to be the only portable way to do this.
1246 * Note that we remove *all* environment entries for
1247 * the variable name, not just the first.
1252 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1260 #endif /* !HAVE_UNSETENV */
1262 #else /* G_OS_WIN32 */
1264 wchar_t *wname, *wassignment;
1267 g_return_if_fail (variable != NULL);
1268 g_return_if_fail (strchr (variable, '=') == NULL);
1269 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1271 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1272 tem = g_strconcat (variable, "=", NULL);
1273 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1276 _wputenv (wassignment);
1277 g_free (wassignment);
1279 SetEnvironmentVariableW (wname, NULL);
1283 #endif /* G_OS_WIN32 */
1289 * Gets the names of all variables set in the environment.
1291 * Returns: a %NULL-terminated list of strings which must be freed
1292 * with g_strfreev().
1294 * Programs that want to be portable to Windows should typically use
1295 * this function and g_getenv() instead of using the environ array
1296 * from the C library directly. On Windows, the strings in the environ
1297 * array are in system codepage encoding, while in most of the typical
1298 * use cases for environment variables in GLib-using programs you want
1299 * the UTF-8 encoding that this function and g_getenv() provide.
1307 gchar **result, *eq;
1310 len = g_strv_length (environ);
1311 result = g_new0 (gchar *, len + 1);
1314 for (i = 0; i < len; i++)
1316 eq = strchr (environ[i], '=');
1318 result[j++] = g_strndup (environ[i], eq - environ[i]);
1325 gchar **result, *eq;
1329 p = (wchar_t *) GetEnvironmentStringsW ();
1335 q += wcslen (q) + 1;
1339 result = g_new0 (gchar *, len + 1);
1345 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1346 if (result[j] != NULL)
1348 eq = strchr (result[j], '=');
1349 if (eq && eq > result[j])
1357 q += wcslen (q) + 1;
1360 FreeEnvironmentStringsW (p);
1366 G_LOCK_DEFINE_STATIC (g_utils_global);
1368 static gchar *g_tmp_dir = NULL;
1369 static gchar *g_user_name = NULL;
1370 static gchar *g_real_name = NULL;
1371 static gchar *g_home_dir = NULL;
1372 static gchar *g_host_name = NULL;
1375 /* System codepage versions of the above, kept at file level so that they,
1376 * too, are produced only once.
1378 static gchar *g_tmp_dir_cp = NULL;
1379 static gchar *g_user_name_cp = NULL;
1380 static gchar *g_real_name_cp = NULL;
1381 static gchar *g_home_dir_cp = NULL;
1384 static gchar *g_user_data_dir = NULL;
1385 static gchar **g_system_data_dirs = NULL;
1386 static gchar *g_user_cache_dir = NULL;
1387 static gchar *g_user_config_dir = NULL;
1388 static gchar **g_system_config_dirs = NULL;
1393 get_special_folder (int csidl)
1397 wchar_t wc[MAX_PATH+1];
1400 LPITEMIDLIST pidl = NULL;
1402 gchar *retval = NULL;
1404 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1407 b = SHGetPathFromIDListW (pidl, path.wc);
1409 retval = g_utf16_to_utf8 (path.wc, -1, NULL, NULL, NULL);
1410 CoTaskMemFree (pidl);
1416 get_windows_directory_root (void)
1418 wchar_t wwindowsdir[MAX_PATH];
1420 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1422 /* Usually X:\Windows, but in terminal server environments
1423 * might be an UNC path, AFAIK.
1425 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1428 if (windowsdir == NULL)
1429 return g_strdup ("C:\\");
1431 p = (char *) g_path_skip_root (windowsdir);
1432 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1438 return g_strdup ("C:\\");
1443 /* HOLDS: g_utils_global_lock */
1445 g_get_any_init_do (void)
1447 gchar hostname[100];
1449 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1451 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1453 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1457 g_tmp_dir = get_windows_directory_root ();
1463 g_tmp_dir = g_strdup (P_tmpdir);
1464 k = strlen (g_tmp_dir);
1465 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1466 g_tmp_dir[k - 1] = '\0';
1472 g_tmp_dir = g_strdup ("/tmp");
1474 #endif /* !G_OS_WIN32 */
1477 /* We check $HOME first for Win32, though it is a last resort for Unix
1478 * where we prefer the results of getpwuid().
1480 g_home_dir = g_strdup (g_getenv ("HOME"));
1482 /* Only believe HOME if it is an absolute path and exists */
1485 if (!(g_path_is_absolute (g_home_dir) &&
1486 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1488 g_free (g_home_dir);
1493 /* In case HOME is Unix-style (it happens), convert it to
1499 while ((p = strchr (g_home_dir, '/')) != NULL)
1505 /* USERPROFILE is probably the closest equivalent to $HOME? */
1506 if (g_getenv ("USERPROFILE") != NULL)
1507 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1511 g_home_dir = get_special_folder (CSIDL_PROFILE);
1514 g_home_dir = get_windows_directory_root ();
1515 #endif /* G_OS_WIN32 */
1519 struct passwd *pw = NULL;
1520 gpointer buffer = NULL;
1524 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1526 # ifdef _SC_GETPW_R_SIZE_MAX
1527 /* This reurns the maximum length */
1528 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1532 # else /* _SC_GETPW_R_SIZE_MAX */
1534 # endif /* _SC_GETPW_R_SIZE_MAX */
1536 logname = (gchar *) g_getenv ("LOGNAME");
1541 /* we allocate 6 extra bytes to work around a bug in
1542 * Mac OS < 10.3. See #156446
1544 buffer = g_malloc (bufsize + 6);
1547 # ifdef HAVE_POSIX_GETPWUID_R
1549 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1550 if (!pw || (pw->pw_uid != getuid ())) {
1551 /* LOGNAME is lying, fall back to looking up the uid */
1552 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1555 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1557 error = error < 0 ? errno : error;
1558 # else /* HAVE_NONPOSIX_GETPWUID_R */
1559 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1560 # if defined(_AIX) || defined(__hpux)
1561 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1562 pw = error == 0 ? &pwd : NULL;
1565 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1566 if (!pw || (pw->pw_uid != getuid ())) {
1567 /* LOGNAME is lying, fall back to looking up the uid */
1568 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1571 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1573 error = pw ? 0 : errno;
1575 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1579 /* we bail out prematurely if the user id can't be found
1580 * (should be pretty rare case actually), or if the buffer
1581 * should be sufficiently big and lookups are still not
1584 if (error == 0 || error == ENOENT)
1586 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1587 (gulong) getuid ());
1590 if (bufsize > 32 * 1024)
1592 g_warning ("getpwuid_r(): failed due to: %s.",
1593 g_strerror (error));
1601 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1606 pw = getpwuid (getuid ());
1611 g_user_name = g_strdup (pw->pw_name);
1613 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1615 gchar **gecos_fields;
1618 /* split the gecos field and substitute '&' */
1619 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1620 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1621 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1622 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1623 g_strfreev (gecos_fields);
1624 g_strfreev (name_parts);
1628 g_home_dir = g_strdup (pw->pw_dir);
1633 #else /* !HAVE_PWD_H */
1637 guint len = UNLEN+1;
1638 wchar_t buffer[UNLEN+1];
1640 if (GetUserNameW (buffer, (LPDWORD) &len))
1642 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1643 g_real_name = g_strdup (g_user_name);
1646 #endif /* G_OS_WIN32 */
1648 #endif /* !HAVE_PWD_H */
1652 g_home_dir = g_strdup (g_getenv ("HOME"));
1656 /* change '\\' in %HOME% to '/' */
1657 g_strdelimit (g_home_dir, "\\",'/');
1660 g_user_name = g_strdup ("somebody");
1662 g_real_name = g_strdup ("Unknown");
1666 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1668 DWORD size = sizeof (hostname);
1669 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1671 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1675 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1676 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1677 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1680 g_tmp_dir_cp = g_strdup ("\\");
1681 if (!g_user_name_cp)
1682 g_user_name_cp = g_strdup ("somebody");
1683 if (!g_real_name_cp)
1684 g_real_name_cp = g_strdup ("Unknown");
1686 /* home_dir might be NULL, unlike tmp_dir, user_name and
1690 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1692 g_home_dir_cp = NULL;
1693 #endif /* G_OS_WIN32 */
1697 g_get_any_init (void)
1700 g_get_any_init_do ();
1704 g_get_any_init_locked (void)
1706 G_LOCK (g_utils_global);
1708 G_UNLOCK (g_utils_global);
1715 * Gets the user name of the current user. The encoding of the returned
1716 * string is system-defined. On UNIX, it might be the preferred file name
1717 * encoding, or something else, and there is no guarantee that it is even
1718 * consistent on a machine. On Windows, it is always UTF-8.
1720 * Returns: the user name of the current user.
1722 G_CONST_RETURN gchar*
1723 g_get_user_name (void)
1725 g_get_any_init_locked ();
1732 * Gets the real name of the user. This usually comes from the user's entry
1733 * in the <filename>passwd</filename> file. The encoding of the returned
1734 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1735 * If the real user name cannot be determined, the string "Unknown" is
1738 * Returns: the user's real name.
1740 G_CONST_RETURN gchar*
1741 g_get_real_name (void)
1743 g_get_any_init_locked ();
1750 * Gets the current user's home directory as defined in the
1751 * password database.
1753 * Note that in contrast to traditional UNIX tools, this function
1754 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1755 * environment variable.
1757 * Returns: the current user's home directory.
1759 G_CONST_RETURN gchar*
1760 g_get_home_dir (void)
1762 g_get_any_init_locked ();
1769 * Gets the directory to use for temporary files. This is found from
1770 * inspecting the environment variables <envar>TMPDIR</envar>,
1771 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1772 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1773 * The encoding of the returned string is system-defined. On Windows,
1774 * it is always UTF-8. The return value is never %NULL.
1776 * Returns: the directory to use for temporary files.
1778 G_CONST_RETURN gchar*
1779 g_get_tmp_dir (void)
1781 g_get_any_init_locked ();
1788 * Return a name for the machine.
1790 * The returned name is not necessarily a fully-qualified domain name,
1791 * or even present in DNS or some other name service at all. It need
1792 * not even be unique on your local network or site, but usually it
1793 * is. Callers should not rely on the return value having any specific
1794 * properties like uniqueness for security purposes. Even if the name
1795 * of the machine is changed while an application is running, the
1796 * return value from this function does not change. The returned
1797 * string is owned by GLib and should not be modified or freed. If no
1798 * name can be determined, a default fixed string "localhost" is
1801 * Returns: the host name of the machine.
1806 g_get_host_name (void)
1808 g_get_any_init_locked ();
1812 G_LOCK_DEFINE_STATIC (g_prgname);
1813 static gchar *g_prgname = NULL;
1818 * Gets the name of the program. This name should <emphasis>not</emphasis>
1819 * be localized, contrast with g_get_application_name().
1820 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1821 * which is called by gtk_init(). The program name is found by taking
1822 * the last component of <literal>argv[0]</literal>.)
1824 * Returns: the name of the program. The returned string belongs
1825 * to GLib and must not be modified or freed.
1828 g_get_prgname (void)
1834 if (g_prgname == NULL)
1836 static gboolean beenhere = FALSE;
1840 gchar *utf8_buf = NULL;
1841 wchar_t buf[MAX_PATH+1];
1844 if (GetModuleFileNameW (GetModuleHandle (NULL),
1845 buf, G_N_ELEMENTS (buf)) > 0)
1846 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1850 g_prgname = g_path_get_basename (utf8_buf);
1857 G_UNLOCK (g_prgname);
1864 * @prgname: the name of the program.
1866 * Sets the name of the program. This name should <emphasis>not</emphasis>
1867 * be localized, contrast with g_set_application_name(). Note that for
1868 * thread-safety reasons this function can only be called once.
1871 g_set_prgname (const gchar *prgname)
1875 g_prgname = g_strdup (prgname);
1876 G_UNLOCK (g_prgname);
1879 G_LOCK_DEFINE_STATIC (g_application_name);
1880 static gchar *g_application_name = NULL;
1883 * g_get_application_name:
1885 * Gets a human-readable name for the application, as set by
1886 * g_set_application_name(). This name should be localized if
1887 * possible, and is intended for display to the user. Contrast with
1888 * g_get_prgname(), which gets a non-localized name. If
1889 * g_set_application_name() has not been called, returns the result of
1890 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1893 * Return value: human-readable application name. may return %NULL
1897 G_CONST_RETURN gchar*
1898 g_get_application_name (void)
1902 G_LOCK (g_application_name);
1903 retval = g_application_name;
1904 G_UNLOCK (g_application_name);
1907 return g_get_prgname ();
1913 * g_set_application_name:
1914 * @application_name: localized name of the application
1916 * Sets a human-readable name for the application. This name should be
1917 * localized if possible, and is intended for display to the user.
1918 * Contrast with g_set_prgname(), which sets a non-localized name.
1919 * g_set_prgname() will be called automatically by gtk_init(),
1920 * but g_set_application_name() will not.
1922 * Note that for thread safety reasons, this function can only
1925 * The application name will be used in contexts such as error messages,
1926 * or when displaying an application's name in the task list.
1930 g_set_application_name (const gchar *application_name)
1932 gboolean already_set = FALSE;
1934 G_LOCK (g_application_name);
1935 if (g_application_name)
1938 g_application_name = g_strdup (application_name);
1939 G_UNLOCK (g_application_name);
1942 g_warning ("g_set_application() name called multiple times");
1946 * g_get_user_data_dir:
1948 * Returns a base directory in which to access application data such
1949 * as icons that is customized for a particular user.
1951 * On UNIX platforms this is determined using the mechanisms described in
1952 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1953 * XDG Base Directory Specification</ulink>
1955 * Return value: a string owned by GLib that must not be modified
1959 G_CONST_RETURN gchar*
1960 g_get_user_data_dir (void)
1964 G_LOCK (g_utils_global);
1966 if (!g_user_data_dir)
1969 data_dir = get_special_folder (CSIDL_PERSONAL);
1971 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1973 if (data_dir && data_dir[0])
1974 data_dir = g_strdup (data_dir);
1976 if (!data_dir || !data_dir[0])
1981 data_dir = g_build_filename (g_home_dir, ".local",
1984 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
1988 g_user_data_dir = data_dir;
1991 data_dir = g_user_data_dir;
1993 G_UNLOCK (g_utils_global);
1999 * g_get_user_config_dir:
2001 * Returns a base directory in which to store user-specific application
2002 * configuration information such as user preferences and settings.
2004 * On UNIX platforms this is determined using the mechanisms described in
2005 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2006 * XDG Base Directory Specification</ulink>
2008 * Return value: a string owned by GLib that must not be modified
2012 G_CONST_RETURN gchar*
2013 g_get_user_config_dir (void)
2017 G_LOCK (g_utils_global);
2019 if (!g_user_config_dir)
2022 config_dir = get_special_folder (CSIDL_APPDATA);
2024 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2026 if (config_dir && config_dir[0])
2027 config_dir = g_strdup (config_dir);
2029 if (!config_dir || !config_dir[0])
2034 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2036 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2038 g_user_config_dir = config_dir;
2041 config_dir = g_user_config_dir;
2043 G_UNLOCK (g_utils_global);
2049 * g_get_user_cache_dir:
2051 * Returns a base directory in which to store non-essential, cached
2052 * data specific to particular user.
2054 * On UNIX platforms this is determined using the mechanisms described in
2055 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2056 * XDG Base Directory Specification</ulink>
2058 * Return value: a string owned by GLib that must not be modified
2062 G_CONST_RETURN gchar*
2063 g_get_user_cache_dir (void)
2067 G_LOCK (g_utils_global);
2069 if (!g_user_cache_dir)
2072 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2074 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2076 if (cache_dir && cache_dir[0])
2077 cache_dir = g_strdup (cache_dir);
2079 if (!cache_dir || !cache_dir[0])
2084 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2086 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2088 g_user_cache_dir = cache_dir;
2091 cache_dir = g_user_cache_dir;
2093 G_UNLOCK (g_utils_global);
2100 #undef g_get_system_data_dirs
2103 get_module_for_address (gconstpointer address)
2105 /* Holds the g_utils_global lock */
2107 static gboolean beenhere = FALSE;
2108 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2109 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2117 p_GetModuleHandleExA =
2118 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2119 "GetModuleHandleExA");
2123 if (p_GetModuleHandleExA == NULL ||
2124 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2125 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2128 MEMORY_BASIC_INFORMATION mbi;
2129 VirtualQuery (address, &mbi, sizeof (mbi));
2130 hmodule = (HMODULE) mbi.AllocationBase;
2137 get_module_share_dir (gconstpointer address)
2140 gchar *filename = NULL;
2142 wchar_t wfilename[MAX_PATH];
2144 hmodule = get_module_for_address (address);
2145 if (hmodule == NULL)
2148 if (GetModuleFileNameW (hmodule, wfilename, G_N_ELEMENTS (wfilename)))
2149 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
2151 if (filename == NULL)
2154 if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
2157 p = strrchr (filename, G_DIR_SEPARATOR);
2158 if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
2161 retval = g_build_filename (filename, "share", NULL);
2167 G_CONST_RETURN gchar * G_CONST_RETURN *
2168 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2172 static GHashTable *per_module_data_dirs = NULL;
2178 G_LOCK (g_utils_global);
2179 hmodule = get_module_for_address (address);
2180 if (hmodule != NULL)
2182 if (per_module_data_dirs == NULL)
2183 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2186 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2190 G_UNLOCK (g_utils_global);
2191 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2197 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2199 /* Documents and Settings\All Users\Application Data */
2200 p = get_special_folder (CSIDL_COMMON_APPDATA);
2202 g_array_append_val (data_dirs, p);
2204 /* Documents and Settings\All Users\Documents */
2205 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2207 g_array_append_val (data_dirs, p);
2209 /* Using the above subfolders of Documents and Settings perhaps
2210 * makes sense from a Windows perspective.
2212 * But looking at the actual use cases of this function in GTK+
2213 * and GNOME software, what we really want is the "share"
2214 * subdirectory of the installation directory for the package
2215 * our caller is a part of.
2217 * The address parameter, if non-NULL, points to a function in the
2218 * calling module. Use that to determine that module's installation
2219 * folder, and use its "share" subfolder.
2221 * Additionally, also use the "share" subfolder of the installation
2222 * locations of GLib and the .exe file being run.
2224 * To guard against none of the above being what is really wanted,
2225 * callers of this function should have Win32-specific code to look
2226 * up their installation folder themselves, and handle a subfolder
2227 * "share" of it in the same way as the folders returned from this
2231 p = get_module_share_dir (address);
2233 g_array_append_val (data_dirs, p);
2235 p = g_win32_get_package_installation_subdirectory (NULL, dll_name, "share");
2237 g_array_append_val (data_dirs, p);
2239 p = g_win32_get_package_installation_subdirectory (NULL, NULL, "share");
2241 g_array_append_val (data_dirs, p);
2243 retval = (gchar **) g_array_free (data_dirs, FALSE);
2247 if (hmodule != NULL)
2248 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2249 G_UNLOCK (g_utils_global);
2252 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2258 * g_get_system_data_dirs:
2260 * Returns an ordered list of base directories in which to access
2261 * system-wide application data.
2263 * On UNIX platforms this is determined using the mechanisms described in
2264 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2265 * XDG Base Directory Specification</ulink>
2267 * On Windows the first elements in the list are the Application Data
2268 * and Documents folders for All Users. (These can be determined only
2269 * on Windows 2000 or later and are not present in the list on other
2270 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2271 * CSIDL_COMMON_DOCUMENTS.
2273 * Then follows the "share" subfolder in the installation folder for
2274 * the package containing the DLL that calls this function, if it can
2277 * Finally the list contains the "share" subfolder in the installation
2278 * folder for GLib, and in the installation folder for the package the
2279 * application's .exe file belongs to.
2281 * The installation folders above are determined by looking up the
2282 * folder where the module (DLL or EXE) in question is located. If the
2283 * folder's name is "bin", its parent is used, otherwise the folder
2286 * Note that on Windows the returned list can vary depending on where
2287 * this function is called.
2289 * Return value: a %NULL-terminated array of strings owned by GLib that must
2290 * not be modified or freed.
2293 G_CONST_RETURN gchar * G_CONST_RETURN *
2294 g_get_system_data_dirs (void)
2296 gchar **data_dir_vector;
2298 G_LOCK (g_utils_global);
2300 if (!g_system_data_dirs)
2303 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2305 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2307 if (!data_dirs || !data_dirs[0])
2308 data_dirs = "/usr/local/share/:/usr/share/";
2310 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2313 g_system_data_dirs = data_dir_vector;
2316 data_dir_vector = g_system_data_dirs;
2318 G_UNLOCK (g_utils_global);
2320 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2324 * g_get_system_config_dirs:
2326 * Returns an ordered list of base directories in which to access
2327 * system-wide configuration information.
2329 * On UNIX platforms this is determined using the mechanisms described in
2330 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2331 * XDG Base Directory Specification</ulink>
2333 * Return value: a %NULL-terminated array of strings owned by GLib that must
2334 * not be modified or freed.
2337 G_CONST_RETURN gchar * G_CONST_RETURN *
2338 g_get_system_config_dirs (void)
2340 gchar *conf_dirs, **conf_dir_vector;
2342 G_LOCK (g_utils_global);
2344 if (!g_system_config_dirs)
2347 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2350 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2355 /* Return empty list */
2356 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2359 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2361 if (!conf_dirs || !conf_dirs[0])
2362 conf_dirs = "/etc/xdg";
2364 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2367 g_system_config_dirs = conf_dir_vector;
2370 conf_dir_vector = g_system_config_dirs;
2371 G_UNLOCK (g_utils_global);
2373 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2378 static GHashTable *alias_table = NULL;
2380 /* read an alias file for the locales */
2382 read_aliases (gchar *file)
2388 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2389 fp = fopen (file,"r");
2392 while (fgets (buf, 256, fp))
2398 /* Line is a comment */
2399 if ((buf[0] == '#') || (buf[0] == '\0'))
2402 /* Reads first column */
2403 for (p = buf, q = NULL; *p; p++) {
2404 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2407 while ((*q == '\t') || (*q == ' ')) {
2413 /* The line only had one column */
2414 if (!q || *q == '\0')
2417 /* Read second column */
2418 for (p = q; *p; p++) {
2419 if ((*p == '\t') || (*p == ' ')) {
2425 /* Add to alias table if necessary */
2426 if (!g_hash_table_lookup (alias_table, buf)) {
2427 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2436 unalias_lang (char *lang)
2443 read_aliases ("/usr/share/locale/locale.alias");
2446 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2451 static gboolean said_before = FALSE;
2453 g_warning ("Too many alias levels for a locale, "
2454 "may indicate a loop");
2463 /* Mask for components of locale spec. The ordering here is from
2464 * least significant to most significant
2468 COMPONENT_CODESET = 1 << 0,
2469 COMPONENT_TERRITORY = 1 << 1,
2470 COMPONENT_MODIFIER = 1 << 2
2473 /* Break an X/Open style locale specification into components
2476 explode_locale (const gchar *locale,
2482 const gchar *uscore_pos;
2483 const gchar *at_pos;
2484 const gchar *dot_pos;
2488 uscore_pos = strchr (locale, '_');
2489 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2490 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2494 mask |= COMPONENT_MODIFIER;
2495 *modifier = g_strdup (at_pos);
2498 at_pos = locale + strlen (locale);
2502 mask |= COMPONENT_CODESET;
2503 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2510 mask |= COMPONENT_TERRITORY;
2511 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2514 uscore_pos = dot_pos;
2516 *language = g_strndup (locale, uscore_pos - locale);
2522 * Compute all interesting variants for a given locale name -
2523 * by stripping off different components of the value.
2525 * For simplicity, we assume that the locale is in
2526 * X/Open format: language[_territory][.codeset][@modifier]
2528 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2529 * as well. We could just copy the code from glibc wholesale
2530 * but it is big, ugly, and complicated, so I'm reluctant
2531 * to do so when this should handle 99% of the time...
2534 _g_compute_locale_variants (const gchar *locale)
2536 GSList *retval = NULL;
2538 gchar *language = NULL;
2539 gchar *territory = NULL;
2540 gchar *codeset = NULL;
2541 gchar *modifier = NULL;
2546 g_return_val_if_fail (locale != NULL, NULL);
2548 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2550 /* Iterate through all possible combinations, from least attractive
2551 * to most attractive.
2553 for (i = 0; i <= mask; i++)
2554 if ((i & ~mask) == 0)
2556 gchar *val = g_strconcat (language,
2557 (i & COMPONENT_TERRITORY) ? territory : "",
2558 (i & COMPONENT_CODESET) ? codeset : "",
2559 (i & COMPONENT_MODIFIER) ? modifier : "",
2561 retval = g_slist_prepend (retval, val);
2565 if (mask & COMPONENT_CODESET)
2567 if (mask & COMPONENT_TERRITORY)
2569 if (mask & COMPONENT_MODIFIER)
2575 /* The following is (partly) taken from the gettext package.
2576 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2578 static const gchar *
2579 guess_category_value (const gchar *category_name)
2581 const gchar *retval;
2583 /* The highest priority value is the `LANGUAGE' environment
2584 variable. This is a GNU extension. */
2585 retval = g_getenv ("LANGUAGE");
2586 if ((retval != NULL) && (retval[0] != '\0'))
2589 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2590 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2591 systems this can be done by the `setlocale' function itself. */
2593 /* Setting of LC_ALL overwrites all other. */
2594 retval = g_getenv ("LC_ALL");
2595 if ((retval != NULL) && (retval[0] != '\0'))
2598 /* Next comes the name of the desired category. */
2599 retval = g_getenv (category_name);
2600 if ((retval != NULL) && (retval[0] != '\0'))
2603 /* Last possibility is the LANG environment variable. */
2604 retval = g_getenv ("LANG");
2605 if ((retval != NULL) && (retval[0] != '\0'))
2608 #ifdef G_PLATFORM_WIN32
2609 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2610 * LANG, which we already did above. Oh well. The main point of
2611 * calling g_win32_getlocale() is to get the thread's locale as used
2612 * by Windows and the Microsoft C runtime (in the "English_United
2613 * States" format) translated into the Unixish format.
2615 retval = g_win32_getlocale ();
2616 if ((retval != NULL) && (retval[0] != '\0'))
2623 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2625 struct _GLanguageNamesCache {
2627 gchar **language_names;
2631 language_names_cache_free (gpointer data)
2633 GLanguageNamesCache *cache = data;
2634 g_free (cache->languages);
2635 g_strfreev (cache->language_names);
2640 * g_get_language_names:
2642 * Computes a list of applicable locale names, which can be used to
2643 * e.g. construct locale-dependent filenames or search paths. The returned
2644 * list is sorted from most desirable to least desirable and always contains
2645 * the default locale "C".
2647 * For example, if LANGUAGE=de:en_US, then the returned list is
2648 * "de", "en_US", "en", "C".
2650 * This function consults the environment variables <envar>LANGUAGE</envar>,
2651 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2652 * to find the list of locales specified by the user.
2654 * Return value: a %NULL-terminated array of strings owned by GLib
2655 * that must not be modified or freed.
2659 G_CONST_RETURN gchar * G_CONST_RETURN *
2660 g_get_language_names (void)
2662 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2663 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2668 cache = g_new0 (GLanguageNamesCache, 1);
2669 g_static_private_set (&cache_private, cache, language_names_cache_free);
2672 value = guess_category_value ("LC_MESSAGES");
2676 if (!(cache->languages && strcmp (cache->languages, value) == 0))
2683 g_free (cache->languages);
2684 g_strfreev (cache->language_names);
2685 cache->languages = g_strdup (value);
2687 alist = g_strsplit (value, ":", 0);
2689 for (a = alist; *a; a++)
2691 gchar *b = unalias_lang (*a);
2692 list = g_slist_concat (list, _g_compute_locale_variants (b));
2695 list = g_slist_append (list, g_strdup ("C"));
2697 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
2698 for (l = list, i = 0; l; l = l->next, i++)
2699 languages[i] = l->data;
2700 languages[i] = NULL;
2702 g_slist_free (list);
2705 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
2710 * @v: a #gpointer key
2712 * Converts a gpointer to a hash value.
2713 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2714 * when using pointers as keys in a #GHashTable.
2716 * Returns: a hash value corresponding to the key.
2719 g_direct_hash (gconstpointer v)
2721 return GPOINTER_TO_UINT (v);
2727 * @v2: a key to compare with @v1.
2729 * Compares two #gpointer arguments and returns %TRUE if they are equal.
2730 * It can be passed to g_hash_table_new() as the @key_equal_func
2731 * parameter, when using pointers as keys in a #GHashTable.
2733 * Returns: %TRUE if the two keys match.
2736 g_direct_equal (gconstpointer v1,
2744 * @v1: a pointer to a #gint key.
2745 * @v2: a pointer to a #gint key to compare with @v1.
2747 * Compares the two #gint values being pointed to and returns
2748 * %TRUE if they are equal.
2749 * It can be passed to g_hash_table_new() as the @key_equal_func
2750 * parameter, when using pointers to integers as keys in a #GHashTable.
2752 * Returns: %TRUE if the two keys match.
2755 g_int_equal (gconstpointer v1,
2758 return *((const gint*) v1) == *((const gint*) v2);
2763 * @v: a pointer to a #gint key
2765 * Converts a pointer to a #gint to a hash value.
2766 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2767 * when using pointers to integers values as keys in a #GHashTable.
2769 * Returns: a hash value corresponding to the key.
2772 g_int_hash (gconstpointer v)
2774 return *(const gint*) v;
2778 * g_nullify_pointer:
2779 * @nullify_location: the memory address of the pointer.
2781 * Set the pointer at the specified location to %NULL.
2784 g_nullify_pointer (gpointer *nullify_location)
2786 g_return_if_fail (nullify_location != NULL);
2788 *nullify_location = NULL;
2794 * Get the codeset for the current locale.
2796 * Return value: a newly allocated string containing the name
2797 * of the codeset. This string must be freed with g_free().
2800 g_get_codeset (void)
2802 const gchar *charset;
2804 g_get_charset (&charset);
2806 return g_strdup (charset);
2809 /* This is called from g_thread_init(). It's used to
2810 * initialize some static data in a threadsafe way.
2813 _g_utils_thread_init (void)
2815 g_get_language_names ();
2820 #include <libintl.h>
2825 * _glib_get_locale_dir:
2827 * Return the path to the lib\locale subfolder of the GLib
2828 * installation folder. The path is in the system codepage. We have to
2829 * use system codepage as bindtextdomain() doesn't have a UTF-8
2832 static const gchar *
2833 _glib_get_locale_dir (void)
2835 gchar *dir, *cp_dir;
2836 gchar *retval = NULL;
2838 dir = g_win32_get_package_installation_directory (GETTEXT_PACKAGE, dll_name);
2839 cp_dir = g_win32_locale_filename_from_utf8 (dir);
2844 /* Don't use g_build_filename() on pathnames in the system
2845 * codepage. In CJK locales cp_dir might end with a double-byte
2846 * character whose trailing byte is a backslash.
2848 retval = g_strconcat (cp_dir, "\\lib\\locale", NULL);
2855 return g_strdup ("");
2858 #undef GLIB_LOCALE_DIR
2859 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
2861 #endif /* G_OS_WIN32 */
2863 G_CONST_RETURN gchar *
2864 _glib_gettext (const gchar *str)
2866 static gboolean _glib_gettext_initialized = FALSE;
2868 if (!_glib_gettext_initialized)
2870 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
2871 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2872 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2874 _glib_gettext_initialized = TRUE;
2877 return dgettext (GETTEXT_PACKAGE, str);
2880 #endif /* ENABLE_NLS */
2884 /* Binary compatibility versions. Not for newly compiled code. */
2886 #undef g_find_program_in_path
2889 g_find_program_in_path (const gchar *program)
2891 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2892 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2895 g_free (utf8_program);
2896 if (utf8_retval == NULL)
2898 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2899 g_free (utf8_retval);
2904 #undef g_get_current_dir
2907 g_get_current_dir (void)
2909 gchar *utf8_dir = g_get_current_dir_utf8 ();
2910 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2917 G_CONST_RETURN gchar*
2918 g_getenv (const gchar *variable)
2920 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2921 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
2925 g_free (utf8_variable);
2928 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
2929 quark = g_quark_from_string (value);
2932 return g_quark_to_string (quark);
2938 g_setenv (const gchar *variable,
2942 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2943 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
2944 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
2946 g_free (utf8_variable);
2947 g_free (utf8_value);
2955 g_unsetenv (const gchar *variable)
2957 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2959 g_unsetenv_utf8 (utf8_variable);
2961 g_free (utf8_variable);
2964 #undef g_get_user_name
2966 G_CONST_RETURN gchar*
2967 g_get_user_name (void)
2969 g_get_any_init_locked ();
2970 return g_user_name_cp;
2973 #undef g_get_real_name
2975 G_CONST_RETURN gchar*
2976 g_get_real_name (void)
2978 g_get_any_init_locked ();
2979 return g_real_name_cp;
2982 #undef g_get_home_dir
2984 G_CONST_RETURN gchar*
2985 g_get_home_dir (void)
2987 g_get_any_init_locked ();
2988 return g_home_dir_cp;
2991 #undef g_get_tmp_dir
2993 G_CONST_RETURN gchar*
2994 g_get_tmp_dir (void)
2996 g_get_any_init_locked ();
2997 return g_tmp_dir_cp;
3002 #define __G_UTILS_C__
3003 #include "galiasdef.c"