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 char windowsdir[MAX_PATH];
1420 if (GetWindowsDirectory (windowsdir, sizeof (windowsdir)))
1422 /* Usually X:\Windows, but in terminal server environments
1423 * might be an UNC path, AFAIK.
1425 char *p = (char *) g_path_skip_root (windowsdir);
1426 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1429 return g_strdup (windowsdir);
1432 return g_strdup ("C:\\");
1437 /* HOLDS: g_utils_global_lock */
1439 g_get_any_init_do (void)
1441 gchar hostname[100];
1443 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1445 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1447 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1451 g_tmp_dir = get_windows_directory_root ();
1457 g_tmp_dir = g_strdup (P_tmpdir);
1458 k = strlen (g_tmp_dir);
1459 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1460 g_tmp_dir[k - 1] = '\0';
1466 g_tmp_dir = g_strdup ("/tmp");
1468 #endif /* !G_OS_WIN32 */
1471 /* We check $HOME first for Win32, though it is a last resort for Unix
1472 * where we prefer the results of getpwuid().
1474 g_home_dir = g_strdup (g_getenv ("HOME"));
1476 /* Only believe HOME if it is an absolute path and exists */
1479 if (!(g_path_is_absolute (g_home_dir) &&
1480 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1482 g_free (g_home_dir);
1487 /* In case HOME is Unix-style (it happens), convert it to
1493 while ((p = strchr (g_home_dir, '/')) != NULL)
1499 /* USERPROFILE is probably the closest equivalent to $HOME? */
1500 if (g_getenv ("USERPROFILE") != NULL)
1501 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1505 g_home_dir = get_special_folder (CSIDL_PROFILE);
1508 g_home_dir = get_windows_directory_root ();
1509 #endif /* G_OS_WIN32 */
1513 struct passwd *pw = NULL;
1514 gpointer buffer = NULL;
1518 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1520 # ifdef _SC_GETPW_R_SIZE_MAX
1521 /* This reurns the maximum length */
1522 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1526 # else /* _SC_GETPW_R_SIZE_MAX */
1528 # endif /* _SC_GETPW_R_SIZE_MAX */
1530 logname = (gchar *) g_getenv ("LOGNAME");
1535 /* we allocate 6 extra bytes to work around a bug in
1536 * Mac OS < 10.3. See #156446
1538 buffer = g_malloc (bufsize + 6);
1541 # ifdef HAVE_POSIX_GETPWUID_R
1543 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1544 if (!pw || (pw->pw_uid != getuid ())) {
1545 /* LOGNAME is lying, fall back to looking up the uid */
1546 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1549 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1551 error = error < 0 ? errno : error;
1552 # else /* HAVE_NONPOSIX_GETPWUID_R */
1553 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1554 # if defined(_AIX) || defined(__hpux)
1555 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1556 pw = error == 0 ? &pwd : NULL;
1559 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1560 if (!pw || (pw->pw_uid != getuid ())) {
1561 /* LOGNAME is lying, fall back to looking up the uid */
1562 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1565 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1567 error = pw ? 0 : errno;
1569 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1573 /* we bail out prematurely if the user id can't be found
1574 * (should be pretty rare case actually), or if the buffer
1575 * should be sufficiently big and lookups are still not
1578 if (error == 0 || error == ENOENT)
1580 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1581 (gulong) getuid ());
1584 if (bufsize > 32 * 1024)
1586 g_warning ("getpwuid_r(): failed due to: %s.",
1587 g_strerror (error));
1595 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1600 pw = getpwuid (getuid ());
1605 g_user_name = g_strdup (pw->pw_name);
1607 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1609 gchar **gecos_fields;
1612 /* split the gecos field and substitute '&' */
1613 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1614 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1615 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1616 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1617 g_strfreev (gecos_fields);
1618 g_strfreev (name_parts);
1622 g_home_dir = g_strdup (pw->pw_dir);
1627 #else /* !HAVE_PWD_H */
1630 guint len = UNLEN+1;
1631 wchar_t buffer[UNLEN+1];
1633 if (GetUserNameW (buffer, (LPDWORD) &len))
1635 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1636 g_real_name = g_strdup (g_user_name);
1638 #endif /* G_OS_WIN32 */
1640 #endif /* !HAVE_PWD_H */
1644 g_home_dir = g_strdup (g_getenv ("HOME"));
1648 /* change '\\' in %HOME% to '/' */
1649 g_strdelimit (g_home_dir, "\\",'/');
1652 g_user_name = g_strdup ("somebody");
1654 g_real_name = g_strdup ("Unknown");
1658 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1660 DWORD size = sizeof (hostname);
1661 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1663 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1667 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1668 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1669 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1672 g_tmp_dir_cp = g_strdup ("\\");
1673 if (!g_user_name_cp)
1674 g_user_name_cp = g_strdup ("somebody");
1675 if (!g_real_name_cp)
1676 g_real_name_cp = g_strdup ("Unknown");
1678 /* home_dir might be NULL, unlike tmp_dir, user_name and
1682 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1684 g_home_dir_cp = NULL;
1685 #endif /* G_OS_WIN32 */
1689 g_get_any_init (void)
1692 g_get_any_init_do ();
1696 g_get_any_init_locked (void)
1698 G_LOCK (g_utils_global);
1700 G_UNLOCK (g_utils_global);
1707 * Gets the user name of the current user. The encoding of the returned
1708 * string is system-defined. On UNIX, it might be the preferred file name
1709 * encoding, or something else, and there is no guarantee that it is even
1710 * consistent on a machine. On Windows, it is always UTF-8.
1712 * Returns: the user name of the current user.
1714 G_CONST_RETURN gchar*
1715 g_get_user_name (void)
1717 g_get_any_init_locked ();
1724 * Gets the real name of the user. This usually comes from the user's entry
1725 * in the <filename>passwd</filename> file. The encoding of the returned
1726 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1727 * If the real user name cannot be determined, the string "Unknown" is
1730 * Returns: the user's real name.
1732 G_CONST_RETURN gchar*
1733 g_get_real_name (void)
1735 g_get_any_init_locked ();
1742 * Gets the current user's home directory.
1744 * Note that in contrast to traditional UNIX tools, this function
1745 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1746 * environment variable.
1748 * Returns: the current user's home directory.
1750 G_CONST_RETURN gchar*
1751 g_get_home_dir (void)
1753 g_get_any_init_locked ();
1760 * Gets the directory to use for temporary files. This is found from
1761 * inspecting the environment variables <envar>TMPDIR</envar>,
1762 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1763 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1764 * The encoding of the returned string is system-defined. On Windows,
1765 * it is always UTF-8. The return value is never %NULL.
1767 * Returns: the directory to use for temporary files.
1769 G_CONST_RETURN gchar*
1770 g_get_tmp_dir (void)
1772 g_get_any_init_locked ();
1779 * Return a name for the machine.
1781 * The returned name is not necessarily a fully-qualified domain name,
1782 * or even present in DNS or some other name service at all. It need
1783 * not even be unique on your local network or site, but usually it
1784 * is. Callers should not rely on the return value having any specific
1785 * properties like uniqueness for security purposes. Even if the name
1786 * of the machine is changed while an application is running, the
1787 * return value from this function does not change. The returned
1788 * string is owned by GLib and should not be modified or freed. If no
1789 * name can be determined, a default fixed string "localhost" is
1792 * Returns: the host name of the machine.
1797 g_get_host_name (void)
1799 g_get_any_init_locked ();
1803 G_LOCK_DEFINE_STATIC (g_prgname);
1804 static gchar *g_prgname = NULL;
1809 * Gets the name of the program. This name should <emphasis>not</emphasis>
1810 * be localized, contrast with g_get_application_name().
1811 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1812 * which is called by gtk_init(). The program name is found by taking
1813 * the last component of <literal>argv[0]</literal>.)
1815 * Returns: the name of the program. The returned string belongs
1816 * to GLib and must not be modified or freed.
1819 g_get_prgname (void)
1825 if (g_prgname == NULL)
1827 static gboolean beenhere = FALSE;
1831 gchar *utf8_buf = NULL;
1832 wchar_t buf[MAX_PATH+1];
1835 if (GetModuleFileNameW (GetModuleHandle (NULL),
1836 buf, G_N_ELEMENTS (buf)) > 0)
1837 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1841 g_prgname = g_path_get_basename (utf8_buf);
1848 G_UNLOCK (g_prgname);
1855 * @prgname: the name of the program.
1857 * Sets the name of the program. This name should <emphasis>not</emphasis>
1858 * be localized, contrast with g_set_application_name(). Note that for
1859 * thread-safety reasons this function can only be called once.
1862 g_set_prgname (const gchar *prgname)
1866 g_prgname = g_strdup (prgname);
1867 G_UNLOCK (g_prgname);
1870 G_LOCK_DEFINE_STATIC (g_application_name);
1871 static gchar *g_application_name = NULL;
1874 * g_get_application_name:
1876 * Gets a human-readable name for the application, as set by
1877 * g_set_application_name(). This name should be localized if
1878 * possible, and is intended for display to the user. Contrast with
1879 * g_get_prgname(), which gets a non-localized name. If
1880 * g_set_application_name() has not been called, returns the result of
1881 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1884 * Return value: human-readable application name. may return %NULL
1888 G_CONST_RETURN gchar*
1889 g_get_application_name (void)
1893 G_LOCK (g_application_name);
1894 retval = g_application_name;
1895 G_UNLOCK (g_application_name);
1898 return g_get_prgname ();
1904 * g_set_application_name:
1905 * @application_name: localized name of the application
1907 * Sets a human-readable name for the application. This name should be
1908 * localized if possible, and is intended for display to the user.
1909 * Contrast with g_set_prgname(), which sets a non-localized name.
1910 * g_set_prgname() will be called automatically by gtk_init(),
1911 * but g_set_application_name() will not.
1913 * Note that for thread safety reasons, this function can only
1916 * The application name will be used in contexts such as error messages,
1917 * or when displaying an application's name in the task list.
1921 g_set_application_name (const gchar *application_name)
1923 gboolean already_set = FALSE;
1925 G_LOCK (g_application_name);
1926 if (g_application_name)
1929 g_application_name = g_strdup (application_name);
1930 G_UNLOCK (g_application_name);
1933 g_warning ("g_set_application() name called multiple times");
1937 * g_get_user_data_dir:
1939 * Returns a base directory in which to access application data such
1940 * as icons that is customized for a particular user.
1942 * On UNIX platforms this is determined using the mechanisms described in
1943 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1944 * XDG Base Directory Specification</ulink>
1946 * Return value: a string owned by GLib that must not be modified
1950 G_CONST_RETURN gchar*
1951 g_get_user_data_dir (void)
1955 G_LOCK (g_utils_global);
1957 if (!g_user_data_dir)
1960 data_dir = get_special_folder (CSIDL_PERSONAL);
1962 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1964 if (data_dir && data_dir[0])
1965 data_dir = g_strdup (data_dir);
1967 if (!data_dir || !data_dir[0])
1972 data_dir = g_build_filename (g_home_dir, ".local",
1975 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
1979 g_user_data_dir = data_dir;
1982 data_dir = g_user_data_dir;
1984 G_UNLOCK (g_utils_global);
1990 * g_get_user_config_dir:
1992 * Returns a base directory in which to store user-specific application
1993 * configuration information such as user preferences and settings.
1995 * On UNIX platforms this is determined using the mechanisms described in
1996 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1997 * XDG Base Directory Specification</ulink>
1999 * Return value: a string owned by GLib that must not be modified
2003 G_CONST_RETURN gchar*
2004 g_get_user_config_dir (void)
2008 G_LOCK (g_utils_global);
2010 if (!g_user_config_dir)
2013 config_dir = get_special_folder (CSIDL_APPDATA);
2015 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2017 if (config_dir && config_dir[0])
2018 config_dir = g_strdup (config_dir);
2020 if (!config_dir || !config_dir[0])
2025 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2027 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2029 g_user_config_dir = config_dir;
2032 config_dir = g_user_config_dir;
2034 G_UNLOCK (g_utils_global);
2040 * g_get_user_cache_dir:
2042 * Returns a base directory in which to store non-essential, cached
2043 * data specific to particular user.
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 string owned by GLib that must not be modified
2053 G_CONST_RETURN gchar*
2054 g_get_user_cache_dir (void)
2058 G_LOCK (g_utils_global);
2060 if (!g_user_cache_dir)
2063 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2065 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2067 if (cache_dir && cache_dir[0])
2068 cache_dir = g_strdup (cache_dir);
2070 if (!cache_dir || !cache_dir[0])
2075 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2077 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2079 g_user_cache_dir = cache_dir;
2082 cache_dir = g_user_cache_dir;
2084 G_UNLOCK (g_utils_global);
2091 #undef g_get_system_data_dirs
2094 get_module_for_address (gconstpointer address)
2096 /* Holds the g_utils_global lock */
2098 static gboolean beenhere = FALSE;
2099 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2100 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2108 p_GetModuleHandleExA =
2109 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2110 "GetModuleHandleExA");
2114 if (p_GetModuleHandleExA == NULL ||
2115 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2116 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2119 MEMORY_BASIC_INFORMATION mbi;
2120 VirtualQuery (address, &mbi, sizeof (mbi));
2121 hmodule = (HMODULE) mbi.AllocationBase;
2128 get_module_share_dir (gconstpointer address)
2131 gchar *filename = NULL;
2133 wchar_t wfilename[MAX_PATH];
2135 hmodule = get_module_for_address (address);
2136 if (hmodule == NULL)
2139 if (GetModuleFileNameW (hmodule, wfilename, G_N_ELEMENTS (wfilename)))
2140 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
2142 if (filename == NULL)
2145 if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
2148 p = strrchr (filename, G_DIR_SEPARATOR);
2149 if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
2152 retval = g_build_filename (filename, "share", NULL);
2158 G_CONST_RETURN gchar * G_CONST_RETURN *
2159 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2163 static GHashTable *per_module_data_dirs = NULL;
2169 G_LOCK (g_utils_global);
2170 hmodule = get_module_for_address (address);
2171 if (hmodule != NULL)
2173 if (per_module_data_dirs == NULL)
2174 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2177 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2181 G_UNLOCK (g_utils_global);
2182 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2188 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2190 /* Documents and Settings\All Users\Application Data */
2191 p = get_special_folder (CSIDL_COMMON_APPDATA);
2193 g_array_append_val (data_dirs, p);
2195 /* Documents and Settings\All Users\Documents */
2196 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2198 g_array_append_val (data_dirs, p);
2200 /* Using the above subfolders of Documents and Settings perhaps
2201 * makes sense from a Windows perspective.
2203 * But looking at the actual use cases of this function in GTK+
2204 * and GNOME software, what we really want is the "share"
2205 * subdirectory of the installation directory for the package
2206 * our caller is a part of.
2208 * The address parameter, if non-NULL, points to a function in the
2209 * calling module. Use that to determine that module's installation
2210 * folder, and use its "share" subfolder.
2212 * Additionally, also use the "share" subfolder of the installation
2213 * locations of GLib and the .exe file being run.
2215 * To guard against none of the above being what is really wanted,
2216 * callers of this function should have Win32-specific code to look
2217 * up their installation folder themselves, and handle a subfolder
2218 * "share" of it in the same way as the folders returned from this
2222 p = get_module_share_dir (address);
2224 g_array_append_val (data_dirs, p);
2226 p = g_win32_get_package_installation_subdirectory (NULL, dll_name, "share");
2228 g_array_append_val (data_dirs, p);
2230 p = g_win32_get_package_installation_subdirectory (NULL, NULL, "share");
2232 g_array_append_val (data_dirs, p);
2234 retval = (gchar **) g_array_free (data_dirs, FALSE);
2238 if (hmodule != NULL)
2239 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2240 G_UNLOCK (g_utils_global);
2243 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2249 * g_get_system_data_dirs:
2251 * Returns an ordered list of base directories in which to access
2252 * system-wide application data.
2254 * On UNIX platforms this is determined using the mechanisms described in
2255 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2256 * XDG Base Directory Specification</ulink>
2258 * On Windows the first elements in the list are the Application Data
2259 * and Documents folders for All Users. (These can be determined only
2260 * on Windows 2000 or later and are not present in the list on other
2261 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2262 * CSIDL_COMMON_DOCUMENTS.
2264 * Then follows the "share" subfolder in the installation folder for
2265 * the package containing the DLL that calls this function, if it can
2268 * Finally the list contains the "share" subfolder in the installation
2269 * folder for GLib, and in the installation folder for the package the
2270 * application's .exe file belongs to.
2272 * The installation folders above are determined by looking up the
2273 * folder where the module (DLL or EXE) in question is located. If the
2274 * folder's name is "bin", its parent is used, otherwise the folder
2277 * Note that on Windows the returned list can vary depending on where
2278 * this function is called.
2280 * Return value: a %NULL-terminated array of strings owned by GLib that must
2281 * not be modified or freed.
2284 G_CONST_RETURN gchar * G_CONST_RETURN *
2285 g_get_system_data_dirs (void)
2287 gchar **data_dir_vector;
2289 G_LOCK (g_utils_global);
2291 if (!g_system_data_dirs)
2294 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2296 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2298 if (!data_dirs || !data_dirs[0])
2299 data_dirs = "/usr/local/share/:/usr/share/";
2301 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2304 g_system_data_dirs = data_dir_vector;
2307 data_dir_vector = g_system_data_dirs;
2309 G_UNLOCK (g_utils_global);
2311 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2315 * g_get_system_config_dirs:
2317 * Returns an ordered list of base directories in which to access
2318 * system-wide configuration information.
2320 * On UNIX platforms this is determined using the mechanisms described in
2321 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2322 * XDG Base Directory Specification</ulink>
2324 * Return value: a %NULL-terminated array of strings owned by GLib that must
2325 * not be modified or freed.
2328 G_CONST_RETURN gchar * G_CONST_RETURN *
2329 g_get_system_config_dirs (void)
2331 gchar *conf_dirs, **conf_dir_vector;
2333 G_LOCK (g_utils_global);
2335 if (!g_system_config_dirs)
2338 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2341 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2346 /* Return empty list */
2347 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2350 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2352 if (!conf_dirs || !conf_dirs[0])
2353 conf_dirs = "/etc/xdg";
2355 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2358 g_system_config_dirs = conf_dir_vector;
2361 conf_dir_vector = g_system_config_dirs;
2362 G_UNLOCK (g_utils_global);
2364 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2369 static GHashTable *alias_table = NULL;
2371 /* read an alias file for the locales */
2373 read_aliases (gchar *file)
2379 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2380 fp = fopen (file,"r");
2383 while (fgets (buf, 256, fp))
2389 /* Line is a comment */
2390 if ((buf[0] == '#') || (buf[0] == '\0'))
2393 /* Reads first column */
2394 for (p = buf, q = NULL; *p; p++) {
2395 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2398 while ((*q == '\t') || (*q == ' ')) {
2404 /* The line only had one column */
2405 if (!q || *q == '\0')
2408 /* Read second column */
2409 for (p = q; *p; p++) {
2410 if ((*p == '\t') || (*p == ' ')) {
2416 /* Add to alias table if necessary */
2417 if (!g_hash_table_lookup (alias_table, buf)) {
2418 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2427 unalias_lang (char *lang)
2434 read_aliases ("/usr/share/locale/locale.alias");
2437 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2442 static gboolean said_before = FALSE;
2444 g_warning ("Too many alias levels for a locale, "
2445 "may indicate a loop");
2454 /* Mask for components of locale spec. The ordering here is from
2455 * least significant to most significant
2459 COMPONENT_CODESET = 1 << 0,
2460 COMPONENT_TERRITORY = 1 << 1,
2461 COMPONENT_MODIFIER = 1 << 2
2464 /* Break an X/Open style locale specification into components
2467 explode_locale (const gchar *locale,
2473 const gchar *uscore_pos;
2474 const gchar *at_pos;
2475 const gchar *dot_pos;
2479 uscore_pos = strchr (locale, '_');
2480 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2481 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2485 mask |= COMPONENT_MODIFIER;
2486 *modifier = g_strdup (at_pos);
2489 at_pos = locale + strlen (locale);
2493 mask |= COMPONENT_CODESET;
2494 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2501 mask |= COMPONENT_TERRITORY;
2502 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2505 uscore_pos = dot_pos;
2507 *language = g_strndup (locale, uscore_pos - locale);
2513 * Compute all interesting variants for a given locale name -
2514 * by stripping off different components of the value.
2516 * For simplicity, we assume that the locale is in
2517 * X/Open format: language[_territory][.codeset][@modifier]
2519 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2520 * as well. We could just copy the code from glibc wholesale
2521 * but it is big, ugly, and complicated, so I'm reluctant
2522 * to do so when this should handle 99% of the time...
2525 _g_compute_locale_variants (const gchar *locale)
2527 GSList *retval = NULL;
2529 gchar *language = NULL;
2530 gchar *territory = NULL;
2531 gchar *codeset = NULL;
2532 gchar *modifier = NULL;
2537 g_return_val_if_fail (locale != NULL, NULL);
2539 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2541 /* Iterate through all possible combinations, from least attractive
2542 * to most attractive.
2544 for (i = 0; i <= mask; i++)
2545 if ((i & ~mask) == 0)
2547 gchar *val = g_strconcat (language,
2548 (i & COMPONENT_TERRITORY) ? territory : "",
2549 (i & COMPONENT_CODESET) ? codeset : "",
2550 (i & COMPONENT_MODIFIER) ? modifier : "",
2552 retval = g_slist_prepend (retval, val);
2556 if (mask & COMPONENT_CODESET)
2558 if (mask & COMPONENT_TERRITORY)
2560 if (mask & COMPONENT_MODIFIER)
2566 /* The following is (partly) taken from the gettext package.
2567 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2569 static const gchar *
2570 guess_category_value (const gchar *category_name)
2572 const gchar *retval;
2574 /* The highest priority value is the `LANGUAGE' environment
2575 variable. This is a GNU extension. */
2576 retval = g_getenv ("LANGUAGE");
2577 if ((retval != NULL) && (retval[0] != '\0'))
2580 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2581 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2582 systems this can be done by the `setlocale' function itself. */
2584 /* Setting of LC_ALL overwrites all other. */
2585 retval = g_getenv ("LC_ALL");
2586 if ((retval != NULL) && (retval[0] != '\0'))
2589 /* Next comes the name of the desired category. */
2590 retval = g_getenv (category_name);
2591 if ((retval != NULL) && (retval[0] != '\0'))
2594 /* Last possibility is the LANG environment variable. */
2595 retval = g_getenv ("LANG");
2596 if ((retval != NULL) && (retval[0] != '\0'))
2599 #ifdef G_PLATFORM_WIN32
2600 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2601 * LANG, which we already did above. Oh well. The main point of
2602 * calling g_win32_getlocale() is to get the thread's locale as used
2603 * by Windows and the Microsoft C runtime (in the "English_United
2604 * States" format) translated into the Unixish format.
2606 retval = g_win32_getlocale ();
2607 if ((retval != NULL) && (retval[0] != '\0'))
2614 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2616 struct _GLanguageNamesCache {
2618 gchar **language_names;
2622 language_names_cache_free (gpointer data)
2624 GLanguageNamesCache *cache = data;
2625 g_free (cache->languages);
2626 g_strfreev (cache->language_names);
2631 * g_get_language_names:
2633 * Computes a list of applicable locale names, which can be used to
2634 * e.g. construct locale-dependent filenames or search paths. The returned
2635 * list is sorted from most desirable to least desirable and always contains
2636 * the default locale "C".
2638 * For example, if LANGUAGE=de:en_US, then the returned list is
2639 * "de", "en_US", "en", "C".
2641 * This function consults the environment variables <envar>LANGUAGE</envar>,
2642 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2643 * to find the list of locales specified by the user.
2645 * Return value: a %NULL-terminated array of strings owned by GLib
2646 * that must not be modified or freed.
2650 G_CONST_RETURN gchar * G_CONST_RETURN *
2651 g_get_language_names (void)
2653 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2654 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2659 cache = g_new0 (GLanguageNamesCache, 1);
2660 g_static_private_set (&cache_private, cache, language_names_cache_free);
2663 value = guess_category_value ("LC_MESSAGES");
2667 if (!(cache->languages && strcmp (cache->languages, value) == 0))
2674 g_free (cache->languages);
2675 g_strfreev (cache->language_names);
2676 cache->languages = g_strdup (value);
2678 alist = g_strsplit (value, ":", 0);
2680 for (a = alist; *a; a++)
2682 gchar *b = unalias_lang (*a);
2683 list = g_slist_concat (list, _g_compute_locale_variants (b));
2686 list = g_slist_append (list, g_strdup ("C"));
2688 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
2689 for (l = list, i = 0; l; l = l->next, i++)
2690 languages[i] = l->data;
2691 languages[i] = NULL;
2693 g_slist_free (list);
2696 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
2701 * @v: a #gpointer key
2703 * Converts a gpointer to a hash value.
2704 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2705 * when using pointers as keys in a #GHashTable.
2707 * Returns: a hash value corresponding to the key.
2710 g_direct_hash (gconstpointer v)
2712 return GPOINTER_TO_UINT (v);
2718 * @v2: a key to compare with @v1.
2720 * Compares two #gpointer arguments and returns %TRUE if they are equal.
2721 * It can be passed to g_hash_table_new() as the @key_equal_func
2722 * parameter, when using pointers as keys in a #GHashTable.
2724 * Returns: %TRUE if the two keys match.
2727 g_direct_equal (gconstpointer v1,
2735 * @v1: a pointer to a #gint key.
2736 * @v2: a pointer to a #gint key to compare with @v1.
2738 * Compares the two #gint values being pointed to and returns
2739 * %TRUE if they are equal.
2740 * It can be passed to g_hash_table_new() as the @key_equal_func
2741 * parameter, when using pointers to integers as keys in a #GHashTable.
2743 * Returns: %TRUE if the two keys match.
2746 g_int_equal (gconstpointer v1,
2749 return *((const gint*) v1) == *((const gint*) v2);
2754 * @v: a pointer to a #gint key
2756 * Converts a pointer to a #gint to a hash value.
2757 * It can be passed to g_hash_table_new() as the @hash_func parameter,
2758 * when using pointers to integers values as keys in a #GHashTable.
2760 * Returns: a hash value corresponding to the key.
2763 g_int_hash (gconstpointer v)
2765 return *(const gint*) v;
2769 * g_nullify_pointer:
2770 * @nullify_location: the memory address of the pointer.
2772 * Set the pointer at the specified location to %NULL.
2775 g_nullify_pointer (gpointer *nullify_location)
2777 g_return_if_fail (nullify_location != NULL);
2779 *nullify_location = NULL;
2785 * Get the codeset for the current locale.
2787 * Return value: a newly allocated string containing the name
2788 * of the codeset. This string must be freed with g_free().
2791 g_get_codeset (void)
2793 const gchar *charset;
2795 g_get_charset (&charset);
2797 return g_strdup (charset);
2800 /* This is called from g_thread_init(). It's used to
2801 * initialize some static data in a threadsafe way.
2804 _g_utils_thread_init (void)
2806 g_get_language_names ();
2811 #include <libintl.h>
2816 * _glib_get_locale_dir:
2818 * Return the path to the lib\locale subfolder of the GLib
2819 * installation folder. The path is in the system codepage. We have to
2820 * use system codepage as bindtextdomain() doesn't have a UTF-8
2823 static const gchar *
2824 _glib_get_locale_dir (void)
2826 gchar *dir, *cp_dir;
2827 gchar *retval = NULL;
2829 dir = g_win32_get_package_installation_directory (GETTEXT_PACKAGE, dll_name);
2830 cp_dir = g_win32_locale_filename_from_utf8 (dir);
2835 /* Don't use g_build_filename() on pathnames in the system
2836 * codepage. In CJK locales cp_dir might end with a double-byte
2837 * character whose trailing byte is a backslash.
2839 retval = g_strconcat (cp_dir, "\\lib\\locale", NULL);
2846 return g_strdup ("");
2849 #undef GLIB_LOCALE_DIR
2850 #define GLIB_LOCALE_DIR _glib_get_locale_dir ()
2852 #endif /* G_OS_WIN32 */
2854 G_CONST_RETURN gchar *
2855 _glib_gettext (const gchar *str)
2857 static gboolean _glib_gettext_initialized = FALSE;
2859 if (!_glib_gettext_initialized)
2861 bindtextdomain(GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
2862 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2863 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
2865 _glib_gettext_initialized = TRUE;
2868 return dgettext (GETTEXT_PACKAGE, str);
2871 #endif /* ENABLE_NLS */
2875 /* Binary compatibility versions. Not for newly compiled code. */
2877 #undef g_find_program_in_path
2880 g_find_program_in_path (const gchar *program)
2882 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2883 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2886 g_free (utf8_program);
2887 if (utf8_retval == NULL)
2889 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2890 g_free (utf8_retval);
2895 #undef g_get_current_dir
2898 g_get_current_dir (void)
2900 gchar *utf8_dir = g_get_current_dir_utf8 ();
2901 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
2908 G_CONST_RETURN gchar*
2909 g_getenv (const gchar *variable)
2911 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2912 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
2916 g_free (utf8_variable);
2919 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
2920 quark = g_quark_from_string (value);
2923 return g_quark_to_string (quark);
2929 g_setenv (const gchar *variable,
2933 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2934 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
2935 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
2937 g_free (utf8_variable);
2938 g_free (utf8_value);
2946 g_unsetenv (const gchar *variable)
2948 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
2950 g_unsetenv_utf8 (utf8_variable);
2952 g_free (utf8_variable);
2955 #undef g_get_user_name
2957 G_CONST_RETURN gchar*
2958 g_get_user_name (void)
2960 g_get_any_init_locked ();
2961 return g_user_name_cp;
2964 #undef g_get_real_name
2966 G_CONST_RETURN gchar*
2967 g_get_real_name (void)
2969 g_get_any_init_locked ();
2970 return g_real_name_cp;
2973 #undef g_get_home_dir
2975 G_CONST_RETURN gchar*
2976 g_get_home_dir (void)
2978 g_get_any_init_locked ();
2979 return g_home_dir_cp;
2982 #undef g_get_tmp_dir
2984 G_CONST_RETURN gchar*
2985 g_get_tmp_dir (void)
2987 g_get_any_init_locked ();
2988 return g_tmp_dir_cp;
2993 #define __G_UTILS_C__
2994 #include "galiasdef.c"