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() */
43 #include <sys/types.h>
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
52 #ifdef HAVE_CRT_EXTERNS_H
53 #include <crt_externs.h> /* for _NSGetEnviron */
56 /* implement gutils's inline functions
58 #define G_IMPLEMENT_INLINES 1
62 #include "gfileutils.h"
65 #include "gprintfint.h"
67 #include "gthreadprivate.h"
68 #include "gtestutils.h"
70 #include "gstrfuncs.h"
74 #define G_PATH_LENGTH MAXPATHLEN
75 #elif defined (PATH_MAX)
76 #define G_PATH_LENGTH PATH_MAX
77 #elif defined (_PC_PATH_MAX)
78 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
80 #define G_PATH_LENGTH 2048
83 #ifdef G_PLATFORM_WIN32
84 # define STRICT /* Strict typing, please */
87 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
88 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
89 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
91 # include <lmcons.h> /* For UNLEN */
92 #endif /* G_PLATFORM_WIN32 */
97 /* older SDK (e.g. msvc 5.0) does not have these*/
98 # ifndef CSIDL_MYMUSIC
99 # define CSIDL_MYMUSIC 13
101 # ifndef CSIDL_MYVIDEO
102 # define CSIDL_MYVIDEO 14
104 # ifndef CSIDL_INTERNET_CACHE
105 # define CSIDL_INTERNET_CACHE 32
107 # ifndef CSIDL_COMMON_APPDATA
108 # define CSIDL_COMMON_APPDATA 35
110 # ifndef CSIDL_MYPICTURES
111 # define CSIDL_MYPICTURES 0x27
113 # ifndef CSIDL_COMMON_DOCUMENTS
114 # define CSIDL_COMMON_DOCUMENTS 46
116 # ifndef CSIDL_PROFILE
117 # define CSIDL_PROFILE 40
119 # include <process.h>
123 #include <CoreServices/CoreServices.h>
127 #include <langinfo.h>
130 const guint glib_major_version = GLIB_MAJOR_VERSION;
131 const guint glib_minor_version = GLIB_MINOR_VERSION;
132 const guint glib_micro_version = GLIB_MICRO_VERSION;
133 const guint glib_interface_age = GLIB_INTERFACE_AGE;
134 const guint glib_binary_age = GLIB_BINARY_AGE;
136 #ifdef G_PLATFORM_WIN32
138 static HMODULE glib_dll = NULL;
143 DllMain (HINSTANCE hinstDLL,
147 if (fdwReason == DLL_PROCESS_ATTACH)
156 _glib_get_dll_directory (void)
160 wchar_t wc_fn[MAX_PATH];
163 if (glib_dll == NULL)
167 /* This code is different from that in
168 * g_win32_get_package_installation_directory_of_module() in that
169 * here we return the actual folder where the GLib DLL is. We don't
170 * do the check for it being in a "bin" or "lib" subfolder and then
171 * returning the parent of that.
173 * In a statically built GLib, glib_dll will be NULL and we will
174 * thus look up the application's .exe file's location.
176 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
179 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
181 p = strrchr (retval, G_DIR_SEPARATOR);
195 * glib_check_version:
196 * @required_major: the required major version.
197 * @required_minor: the required minor version.
198 * @required_micro: the required micro version.
200 * Checks that the GLib library in use is compatible with the
201 * given version. Generally you would pass in the constants
202 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
203 * as the three arguments to this function; that produces
204 * a check that the library in use is compatible with
205 * the version of GLib the application or module was compiled
208 * Compatibility is defined by two things: first the version
209 * of the running library is newer than the version
210 * @required_major.required_minor.@required_micro. Second
211 * the running library must be binary compatible with the
212 * version @required_major.required_minor.@required_micro
213 * (same major version.)
215 * Return value: %NULL if the GLib library is compatible with the
216 * given version, or a string describing the version mismatch.
217 * The returned string is owned by GLib and must not be modified
223 glib_check_version (guint required_major,
224 guint required_minor,
225 guint required_micro)
227 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
228 gint required_effective_micro = 100 * required_minor + required_micro;
230 if (required_major > GLIB_MAJOR_VERSION)
231 return "GLib version too old (major mismatch)";
232 if (required_major < GLIB_MAJOR_VERSION)
233 return "GLib version too new (major mismatch)";
234 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
235 return "GLib version too new (micro mismatch)";
236 if (required_effective_micro > glib_effective_micro)
237 return "GLib version too old (micro mismatch)";
241 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
244 * @dest: the destination address to copy the bytes to.
245 * @src: the source address to copy the bytes from.
246 * @len: the number of bytes to copy.
248 * Copies a block of memory @len bytes long, from @src to @dest.
249 * The source and destination areas may overlap.
251 * In order to use this function, you must include
252 * <filename>string.h</filename> yourself, because this macro will
253 * typically simply resolve to memmove() and GLib does not include
254 * <filename>string.h</filename> for you.
257 g_memmove (gpointer dest,
261 gchar* destptr = dest;
262 const gchar* srcptr = src;
263 if (src + len < dest || dest + len < src)
265 bcopy (src, dest, len);
268 else if (dest <= src)
271 *(destptr++) = *(srcptr++);
278 *(--destptr) = *(--srcptr);
281 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
289 * @func: the function to call on normal program termination.
291 * Specifies a function to be called at normal program termination.
293 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
294 * macro that maps to a call to the atexit() function in the C
295 * library. This means that in case the code that calls g_atexit(),
296 * i.e. atexit(), is in a DLL, the function will be called when the
297 * DLL is detached from the program. This typically makes more sense
298 * than that the function is called when the GLib DLL is detached,
299 * which happened earlier when g_atexit() was a function in the GLib
302 * The behaviour of atexit() in the context of dynamically loaded
303 * modules is not formally specified and varies wildly.
305 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
306 * loaded module which is unloaded before the program terminates might
307 * well cause a crash at program exit.
309 * Some POSIX systems implement atexit() like Windows, and have each
310 * dynamically loaded module maintain an own atexit chain that is
311 * called when the module is unloaded.
313 * On other POSIX systems, before a dynamically loaded module is
314 * unloaded, the registered atexit functions (if any) residing in that
315 * module are called, regardless where the code that registered them
316 * resided. This is presumably the most robust approach.
318 * As can be seen from the above, for portability it's best to avoid
319 * calling g_atexit() (or atexit()) except in the main executable of a
323 g_atexit (GVoidFunc func)
326 const gchar *error = NULL;
328 /* keep this in sync with glib.h */
330 #ifdef G_NATIVE_ATEXIT
331 result = ATEXIT (func);
333 error = g_strerror (errno);
334 #elif defined (HAVE_ATEXIT)
335 # ifdef NeXT /* @#%@! NeXTStep */
336 result = !atexit ((void (*)(void)) func);
338 error = g_strerror (errno);
340 result = atexit ((void (*)(void)) func);
342 error = g_strerror (errno);
344 #elif defined (HAVE_ON_EXIT)
345 result = on_exit ((void (*)(int, void *)) func, NULL);
347 error = g_strerror (errno);
350 error = "no implementation";
351 #endif /* G_NATIVE_ATEXIT */
354 g_error ("Could not register atexit() function: %s", error);
357 /* Based on execvp() from GNU Libc.
358 * Some of this code is cut-and-pasted into gspawn.c
362 my_strchrnul (const gchar *str,
365 gchar *p = (gchar*)str;
366 while (*p && (*p != c))
374 static gchar *inner_find_program_in_path (const gchar *program);
377 g_find_program_in_path (const gchar *program)
379 const gchar *last_dot = strrchr (program, '.');
381 if (last_dot == NULL ||
382 strchr (last_dot, '\\') != NULL ||
383 strchr (last_dot, '/') != NULL)
385 const gint program_length = strlen (program);
386 gchar *pathext = g_build_path (";",
387 ".exe;.cmd;.bat;.com",
388 g_getenv ("PATHEXT"),
391 gchar *decorated_program;
397 gchar *q = my_strchrnul (p, ';');
399 decorated_program = g_malloc (program_length + (q-p) + 1);
400 memcpy (decorated_program, program, program_length);
401 memcpy (decorated_program+program_length, p, q-p);
402 decorated_program [program_length + (q-p)] = '\0';
404 retval = inner_find_program_in_path (decorated_program);
405 g_free (decorated_program);
413 } while (*p++ != '\0');
418 return inner_find_program_in_path (program);
424 * g_find_program_in_path:
425 * @program: a program name in the GLib file name encoding
427 * Locates the first executable named @program in the user's path, in the
428 * same way that execvp() would locate it. Returns an allocated string
429 * with the absolute path name, or %NULL if the program is not found in
430 * the path. If @program is already an absolute path, returns a copy of
431 * @program if @program exists and is executable, and %NULL otherwise.
433 * On Windows, if @program does not have a file type suffix, tries
434 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
435 * the <envar>PATHEXT</envar> environment variable.
437 * On Windows, it looks for the file in the same way as CreateProcess()
438 * would. This means first in the directory where the executing
439 * program was loaded from, then in the current directory, then in the
440 * Windows 32-bit system directory, then in the Windows directory, and
441 * finally in the directories in the <envar>PATH</envar> environment
442 * variable. If the program is found, the return value contains the
443 * full name including the type suffix.
445 * Return value: absolute path, or %NULL
449 inner_find_program_in_path (const gchar *program)
452 g_find_program_in_path (const gchar *program)
455 const gchar *path, *p;
456 gchar *name, *freeme;
458 const gchar *path_copy;
459 gchar *filename = NULL, *appdir = NULL;
460 gchar *sysdir = NULL, *windir = NULL;
462 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
468 g_return_val_if_fail (program != NULL, NULL);
470 /* If it is an absolute path, or a relative path including subdirectories,
471 * don't look in PATH.
473 if (g_path_is_absolute (program)
474 || strchr (program, G_DIR_SEPARATOR) != NULL
476 || strchr (program, '/') != NULL
480 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
481 !g_file_test (program, G_FILE_TEST_IS_DIR))
482 return g_strdup (program);
487 path = g_getenv ("PATH");
488 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
491 /* There is no `PATH' in the environment. The default
492 * search path in GNU libc is the current directory followed by
493 * the path `confstr' returns for `_CS_PATH'.
496 /* In GLib we put . last, for security, and don't use the
497 * unportable confstr(); UNIX98 does not actually specify
498 * what to search if PATH is unset. POSIX may, dunno.
501 path = "/bin:/usr/bin:.";
504 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
505 if (n > 0 && n < MAXPATHLEN)
506 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
508 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
509 if (n > 0 && n < MAXPATHLEN)
510 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
512 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
513 if (n > 0 && n < MAXPATHLEN)
514 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
518 appdir = g_path_get_dirname (filename);
522 path = g_strdup (path);
526 const gchar *tem = path;
527 path = g_strconcat (windir, ";", path, NULL);
528 g_free ((gchar *) tem);
534 const gchar *tem = path;
535 path = g_strconcat (sysdir, ";", path, NULL);
536 g_free ((gchar *) tem);
541 const gchar *tem = path;
542 path = g_strconcat (".;", path, NULL);
543 g_free ((gchar *) tem);
548 const gchar *tem = path;
549 path = g_strconcat (appdir, ";", path, NULL);
550 g_free ((gchar *) tem);
557 len = strlen (program) + 1;
558 pathlen = strlen (path);
559 freeme = name = g_malloc (pathlen + len + 1);
561 /* Copy the file name at the top, including '\0' */
562 memcpy (name + pathlen + 1, program, len);
563 name = name + pathlen;
564 /* And add the slash before the filename */
565 *name = G_DIR_SEPARATOR;
573 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
576 /* Two adjacent colons, or a colon at the beginning or the end
577 * of `PATH' means to search the current directory.
581 startp = memcpy (name - (p - path), path, p - path);
583 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
584 !g_file_test (startp, G_FILE_TEST_IS_DIR))
587 ret = g_strdup (startp);
590 g_free ((gchar *) path_copy);
595 while (*p++ != '\0');
599 g_free ((gchar *) path_copy);
606 debug_key_matches (const gchar *key,
610 for (; length; length--, key++, token++)
612 char k = (*key == '_') ? '-' : tolower (*key );
613 char t = (*token == '_') ? '-' : tolower (*token);
623 * g_parse_debug_string:
624 * @string: a list of debug options separated by colons, spaces, or
626 * @keys: pointer to an array of #GDebugKey which associate
627 * strings with bit flags.
628 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
630 * Parses a string containing debugging options
631 * into a %guint containing bit flags. This is used
632 * within GDK and GTK+ to parse the debug options passed on the
633 * command line or through environment variables.
635 * If @string is equal to "all", all flags are set. If @string
636 * is equal to "help", all the available keys in @keys are printed
637 * out to standard error.
639 * Returns: the combined set of bit flags.
642 g_parse_debug_string (const gchar *string,
643 const GDebugKey *keys,
652 /* this function is used by gmem.c/gslice.c initialization code,
653 * so introducing malloc dependencies here would require adaptions
654 * of those code portions.
657 if (!g_ascii_strcasecmp (string, "all"))
659 for (i=0; i<nkeys; i++)
660 result |= keys[i].value;
662 else if (!g_ascii_strcasecmp (string, "help"))
664 /* using stdio directly for the reason stated above */
665 fprintf (stderr, "Supported debug values: ");
666 for (i=0; i<nkeys; i++)
667 fprintf (stderr, " %s", keys[i].key);
668 fprintf (stderr, "\n");
672 const gchar *p = string;
677 q = strpbrk (p, ":;, \t");
681 for (i = 0; i < nkeys; i++)
682 if (debug_key_matches (keys[i].key, p, q - p))
683 result |= keys[i].value;
696 * @file_name: the name of the file.
698 * Gets the name of the file without any leading directory components.
699 * It returns a pointer into the given file name string.
701 * Return value: the name of the file without any leading directory components.
703 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
704 * g_path_get_basename() allocates new memory for the returned string, unlike
705 * this function which returns a pointer into the argument.
707 G_CONST_RETURN gchar*
708 g_basename (const gchar *file_name)
710 register gchar *base;
712 g_return_val_if_fail (file_name != NULL, NULL);
714 base = strrchr (file_name, G_DIR_SEPARATOR);
718 gchar *q = strrchr (file_name, '/');
719 if (base == NULL || (q != NULL && q > base))
728 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
729 return (gchar*) file_name + 2;
730 #endif /* G_OS_WIN32 */
732 return (gchar*) file_name;
736 * g_path_get_basename:
737 * @file_name: the name of the file.
739 * Gets the last component of the filename. If @file_name ends with a
740 * directory separator it gets the component before the last slash. If
741 * @file_name consists only of directory separators (and on Windows,
742 * possibly a drive letter), a single separator is returned. If
743 * @file_name is empty, it gets ".".
745 * Return value: a newly allocated string containing the last component of
749 g_path_get_basename (const gchar *file_name)
751 register gssize base;
752 register gssize last_nonslash;
756 g_return_val_if_fail (file_name != NULL, NULL);
758 if (file_name[0] == '\0')
760 return g_strdup (".");
762 last_nonslash = strlen (file_name) - 1;
764 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
767 if (last_nonslash == -1)
768 /* string only containing slashes */
769 return g_strdup (G_DIR_SEPARATOR_S);
772 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
773 /* string only containing slashes and a drive */
774 return g_strdup (G_DIR_SEPARATOR_S);
775 #endif /* G_OS_WIN32 */
777 base = last_nonslash;
779 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
783 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
785 #endif /* G_OS_WIN32 */
787 len = last_nonslash - base;
788 retval = g_malloc (len + 1);
789 memcpy (retval, file_name + base + 1, len);
795 * g_path_is_absolute:
796 * @file_name: a file name.
798 * Returns %TRUE if the given @file_name is an absolute file name,
799 * i.e. it contains a full path from the root directory such as "/usr/local"
800 * on UNIX or "C:\windows" on Windows systems.
802 * Returns: %TRUE if @file_name is an absolute path.
805 g_path_is_absolute (const gchar *file_name)
807 g_return_val_if_fail (file_name != NULL, FALSE);
809 if (G_IS_DIR_SEPARATOR (file_name[0]))
813 /* Recognize drive letter on native Windows */
814 if (g_ascii_isalpha (file_name[0]) &&
815 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
817 #endif /* G_OS_WIN32 */
824 * @file_name: a file name.
826 * Returns a pointer into @file_name after the root component, i.e. after
827 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
828 * path it returns %NULL.
830 * Returns: a pointer into @file_name after the root component.
832 G_CONST_RETURN gchar*
833 g_path_skip_root (const gchar *file_name)
835 g_return_val_if_fail (file_name != NULL, NULL);
837 #ifdef G_PLATFORM_WIN32
838 /* Skip \\server\share or //server/share */
839 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
840 G_IS_DIR_SEPARATOR (file_name[1]) &&
842 !G_IS_DIR_SEPARATOR (file_name[2]))
846 p = strchr (file_name + 2, G_DIR_SEPARATOR);
849 gchar *q = strchr (file_name + 2, '/');
850 if (p == NULL || (q != NULL && q < p))
860 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
863 /* Possibly skip a backslash after the share name */
864 if (G_IS_DIR_SEPARATOR (file_name[0]))
867 return (gchar *)file_name;
872 /* Skip initial slashes */
873 if (G_IS_DIR_SEPARATOR (file_name[0]))
875 while (G_IS_DIR_SEPARATOR (file_name[0]))
877 return (gchar *)file_name;
882 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
883 return (gchar *)file_name + 3;
890 * g_path_get_dirname:
891 * @file_name: the name of the file.
893 * Gets the directory components of a file name. If the file name has no
894 * directory components "." is returned. The returned string should be
895 * freed when no longer needed.
897 * Returns: the directory components of the file.
900 g_path_get_dirname (const gchar *file_name)
902 register gchar *base;
905 g_return_val_if_fail (file_name != NULL, NULL);
907 base = strrchr (file_name, G_DIR_SEPARATOR);
910 gchar *q = strrchr (file_name, '/');
911 if (base == NULL || (q != NULL && q > base))
918 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
920 gchar drive_colon_dot[4];
922 drive_colon_dot[0] = file_name[0];
923 drive_colon_dot[1] = ':';
924 drive_colon_dot[2] = '.';
925 drive_colon_dot[3] = '\0';
927 return g_strdup (drive_colon_dot);
930 return g_strdup (".");
933 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
937 /* base points to the char before the last slash.
939 * In case file_name is the root of a drive (X:\) or a child of the
940 * root of a drive (X:\foo), include the slash.
942 * In case file_name is the root share of an UNC path
943 * (\\server\share), add a slash, returning \\server\share\ .
945 * In case file_name is a direct child of a share in an UNC path
946 * (\\server\share\foo), include the slash after the share name,
947 * returning \\server\share\ .
949 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
951 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
952 G_IS_DIR_SEPARATOR (file_name[1]) &&
954 !G_IS_DIR_SEPARATOR (file_name[2]) &&
955 base >= file_name + 2)
957 const gchar *p = file_name + 2;
958 while (*p && !G_IS_DIR_SEPARATOR (*p))
962 len = (guint) strlen (file_name) + 1;
963 base = g_new (gchar, len + 1);
964 strcpy (base, file_name);
965 base[len-1] = G_DIR_SEPARATOR;
969 if (G_IS_DIR_SEPARATOR (*p))
972 while (*p && !G_IS_DIR_SEPARATOR (*p))
980 len = (guint) 1 + base - file_name;
982 base = g_new (gchar, len + 1);
983 g_memmove (base, file_name, len);
992 * Gets the current directory.
993 * The returned string should be freed when no longer needed. The encoding
994 * of the returned string is system defined. On Windows, it is always UTF-8.
996 * Returns: the current directory.
999 g_get_current_dir (void)
1004 wchar_t dummy[2], *wdir;
1007 len = GetCurrentDirectoryW (2, dummy);
1008 wdir = g_new (wchar_t, len);
1010 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1011 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1016 dir = g_strdup ("\\");
1022 gchar *buffer = NULL;
1024 static gulong max_len = 0;
1027 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1029 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1030 * and, if that wasn't bad enough, hangs in doing so.
1032 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1033 buffer = g_new (gchar, max_len + 1);
1035 dir = getwd (buffer);
1036 #else /* !sun || !HAVE_GETCWD */
1037 while (max_len < G_MAXULONG / 2)
1040 buffer = g_new (gchar, max_len + 1);
1042 dir = getcwd (buffer, max_len);
1044 if (dir || errno != ERANGE)
1049 #endif /* !sun || !HAVE_GETCWD */
1051 if (!dir || !*buffer)
1053 /* hm, should we g_error() out here?
1054 * this can happen if e.g. "./" has mode \0000
1056 buffer[0] = G_DIR_SEPARATOR;
1060 dir = g_strdup (buffer);
1069 * @variable: the environment variable to get, in the GLib file name encoding.
1071 * Returns the value of an environment variable. The name and value
1072 * are in the GLib file name encoding. On UNIX, this means the actual
1073 * bytes which might or might not be in some consistent character set
1074 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1075 * environment variable's value contains references to other
1076 * environment variables, they are expanded.
1078 * Return value: the value of the environment variable, or %NULL if
1079 * the environment variable is not found. The returned string may be
1080 * overwritten by the next call to g_getenv(), g_setenv() or
1083 G_CONST_RETURN gchar*
1084 g_getenv (const gchar *variable)
1088 g_return_val_if_fail (variable != NULL, NULL);
1090 return getenv (variable);
1092 #else /* G_OS_WIN32 */
1096 wchar_t dummy[2], *wname, *wvalue;
1099 g_return_val_if_fail (variable != NULL, NULL);
1100 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1102 /* On Windows NT, it is relatively typical that environment
1103 * variables contain references to other environment variables. If
1104 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1105 * environment variables would be stored in the Registry as
1106 * REG_EXPAND_SZ type values, and would then get automatically
1107 * expanded before a program sees them. But there is broken software
1108 * that stores environment variables as REG_SZ values even if they
1109 * contain references to other environment variables.)
1112 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1114 len = GetEnvironmentVariableW (wname, dummy, 2);
1124 wvalue = g_new (wchar_t, len);
1126 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1133 if (wcschr (wvalue, L'%') != NULL)
1135 wchar_t *tem = wvalue;
1137 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1141 wvalue = g_new (wchar_t, len);
1143 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1153 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1158 quark = g_quark_from_string (value);
1161 return g_quark_to_string (quark);
1163 #endif /* G_OS_WIN32 */
1166 /* _g_getenv_nomalloc
1167 * this function does a getenv() without doing any kind of allocation
1168 * through glib. it's suitable for chars <= 127 only (both, for the
1169 * variable name and the contents) and for contents < 1024 chars in
1170 * length. also, it aliases "" to a NULL return value.
1173 _g_getenv_nomalloc (const gchar *variable,
1176 const gchar *retval = getenv (variable);
1177 if (retval && retval[0])
1179 gint l = strlen (retval);
1182 strncpy (buffer, retval, l);
1192 * @variable: the environment variable to set, must not contain '='.
1193 * @value: the value for to set the variable to.
1194 * @overwrite: whether to change the variable if it already exists.
1196 * Sets an environment variable. Both the variable's name and value
1197 * should be in the GLib file name encoding. On UNIX, this means that
1198 * they can be any sequence of bytes. On Windows, they should be in
1201 * Note that on some systems, when variables are overwritten, the memory
1202 * used for the previous variables and its value isn't reclaimed.
1204 * Returns: %FALSE if the environment variable couldn't be set.
1209 g_setenv (const gchar *variable,
1220 g_return_val_if_fail (variable != NULL, FALSE);
1221 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1224 result = setenv (variable, value, overwrite);
1226 if (!overwrite && getenv (variable) != NULL)
1229 /* This results in a leak when you overwrite existing
1230 * settings. It would be fairly easy to fix this by keeping
1231 * our own parallel array or hash table.
1233 string = g_strconcat (variable, "=", value, NULL);
1234 result = putenv (string);
1238 #else /* G_OS_WIN32 */
1241 wchar_t *wname, *wvalue, *wassignment;
1244 g_return_val_if_fail (variable != NULL, FALSE);
1245 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1246 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1247 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1249 if (!overwrite && g_getenv (variable) != NULL)
1252 /* We want to (if possible) set both the environment variable copy
1253 * kept by the C runtime and the one kept by the system.
1255 * We can't use only the C runtime's putenv or _wputenv() as that
1256 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1257 * (with main() and not wmain()). In a "main()" app the C runtime
1258 * initializes the C runtime's environment table by converting the
1259 * real (wide char) environment variables to system codepage, thus
1260 * breaking those that aren't representable in the system codepage.
1262 * As the C runtime's putenv() will also set the system copy, we do
1263 * the putenv() first, then call SetEnvironmentValueW ourselves.
1266 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1267 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1268 tem = g_strconcat (variable, "=", value, NULL);
1269 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1272 _wputenv (wassignment);
1273 g_free (wassignment);
1275 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1282 #endif /* G_OS_WIN32 */
1285 #ifdef HAVE__NSGETENVIRON
1286 #define environ (*_NSGetEnviron())
1287 #elif !defined(G_OS_WIN32)
1289 /* According to the Single Unix Specification, environ is not in
1290 * any system header, although unistd.h often declares it.
1292 extern char **environ;
1297 * @variable: the environment variable to remove, must not contain '='.
1299 * Removes an environment variable from the environment.
1301 * Note that on some systems, when variables are overwritten, the memory
1302 * used for the previous variables and its value isn't reclaimed.
1303 * Furthermore, this function can't be guaranteed to operate in a
1309 g_unsetenv (const gchar *variable)
1313 #ifdef HAVE_UNSETENV
1314 g_return_if_fail (variable != NULL);
1315 g_return_if_fail (strchr (variable, '=') == NULL);
1317 unsetenv (variable);
1318 #else /* !HAVE_UNSETENV */
1322 g_return_if_fail (variable != NULL);
1323 g_return_if_fail (strchr (variable, '=') == NULL);
1325 len = strlen (variable);
1327 /* Mess directly with the environ array.
1328 * This seems to be the only portable way to do this.
1330 * Note that we remove *all* environment entries for
1331 * the variable name, not just the first.
1336 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1344 #endif /* !HAVE_UNSETENV */
1346 #else /* G_OS_WIN32 */
1348 wchar_t *wname, *wassignment;
1351 g_return_if_fail (variable != NULL);
1352 g_return_if_fail (strchr (variable, '=') == NULL);
1353 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1355 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1356 tem = g_strconcat (variable, "=", NULL);
1357 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1360 _wputenv (wassignment);
1361 g_free (wassignment);
1363 SetEnvironmentVariableW (wname, NULL);
1367 #endif /* G_OS_WIN32 */
1373 * Gets the names of all variables set in the environment.
1375 * Returns: a %NULL-terminated list of strings which must be freed
1376 * with g_strfreev().
1378 * Programs that want to be portable to Windows should typically use
1379 * this function and g_getenv() instead of using the environ array
1380 * from the C library directly. On Windows, the strings in the environ
1381 * array are in system codepage encoding, while in most of the typical
1382 * use cases for environment variables in GLib-using programs you want
1383 * the UTF-8 encoding that this function and g_getenv() provide.
1391 gchar **result, *eq;
1394 len = g_strv_length (environ);
1395 result = g_new0 (gchar *, len + 1);
1398 for (i = 0; i < len; i++)
1400 eq = strchr (environ[i], '=');
1402 result[j++] = g_strndup (environ[i], eq - environ[i]);
1409 gchar **result, *eq;
1413 p = (wchar_t *) GetEnvironmentStringsW ();
1419 q += wcslen (q) + 1;
1423 result = g_new0 (gchar *, len + 1);
1429 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1430 if (result[j] != NULL)
1432 eq = strchr (result[j], '=');
1433 if (eq && eq > result[j])
1441 q += wcslen (q) + 1;
1444 FreeEnvironmentStringsW (p);
1450 G_LOCK_DEFINE_STATIC (g_utils_global);
1452 static gchar *g_tmp_dir = NULL;
1453 static gchar *g_user_name = NULL;
1454 static gchar *g_real_name = NULL;
1455 static gchar *g_home_dir = NULL;
1456 static gchar *g_host_name = NULL;
1459 /* System codepage versions of the above, kept at file level so that they,
1460 * too, are produced only once.
1462 static gchar *g_tmp_dir_cp = NULL;
1463 static gchar *g_user_name_cp = NULL;
1464 static gchar *g_real_name_cp = NULL;
1465 static gchar *g_home_dir_cp = NULL;
1468 static gchar *g_user_data_dir = NULL;
1469 static gchar **g_system_data_dirs = NULL;
1470 static gchar *g_user_cache_dir = NULL;
1471 static gchar *g_user_config_dir = NULL;
1472 static gchar **g_system_config_dirs = NULL;
1474 static gchar **g_user_special_dirs = NULL;
1476 /* fifteen minutes of fame for everybody */
1477 #define G_USER_DIRS_EXPIRE 15 * 60
1482 get_special_folder (int csidl)
1484 wchar_t path[MAX_PATH+1];
1486 LPITEMIDLIST pidl = NULL;
1488 gchar *retval = NULL;
1490 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1493 b = SHGetPathFromIDListW (pidl, path);
1495 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1496 CoTaskMemFree (pidl);
1502 get_windows_directory_root (void)
1504 wchar_t wwindowsdir[MAX_PATH];
1506 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1508 /* Usually X:\Windows, but in terminal server environments
1509 * might be an UNC path, AFAIK.
1511 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1514 if (windowsdir == NULL)
1515 return g_strdup ("C:\\");
1517 p = (char *) g_path_skip_root (windowsdir);
1518 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1524 return g_strdup ("C:\\");
1529 /* HOLDS: g_utils_global_lock */
1531 g_get_any_init_do (void)
1533 gchar hostname[100];
1535 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1536 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1537 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1538 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1539 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1542 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1543 g_tmp_dir = get_windows_directory_root ();
1546 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1549 g_tmp_dir = g_strdup (P_tmpdir);
1550 k = strlen (g_tmp_dir);
1551 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1552 g_tmp_dir[k - 1] = '\0';
1556 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1558 g_tmp_dir = g_strdup ("/tmp");
1560 #endif /* !G_OS_WIN32 */
1563 /* We check $HOME first for Win32, though it is a last resort for Unix
1564 * where we prefer the results of getpwuid().
1566 g_home_dir = g_strdup (g_getenv ("HOME"));
1568 /* Only believe HOME if it is an absolute path and exists */
1571 if (!(g_path_is_absolute (g_home_dir) &&
1572 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1574 g_free (g_home_dir);
1579 /* In case HOME is Unix-style (it happens), convert it to
1585 while ((p = strchr (g_home_dir, '/')) != NULL)
1591 /* USERPROFILE is probably the closest equivalent to $HOME? */
1592 if (g_getenv ("USERPROFILE") != NULL)
1593 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1597 g_home_dir = get_special_folder (CSIDL_PROFILE);
1600 g_home_dir = get_windows_directory_root ();
1601 #endif /* G_OS_WIN32 */
1605 struct passwd *pw = NULL;
1606 gpointer buffer = NULL;
1610 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1612 # ifdef _SC_GETPW_R_SIZE_MAX
1613 /* This reurns the maximum length */
1614 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1618 # else /* _SC_GETPW_R_SIZE_MAX */
1620 # endif /* _SC_GETPW_R_SIZE_MAX */
1622 logname = (gchar *) g_getenv ("LOGNAME");
1627 /* we allocate 6 extra bytes to work around a bug in
1628 * Mac OS < 10.3. See #156446
1630 buffer = g_malloc (bufsize + 6);
1633 # ifdef HAVE_POSIX_GETPWUID_R
1635 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1636 if (!pw || (pw->pw_uid != getuid ())) {
1637 /* LOGNAME is lying, fall back to looking up the uid */
1638 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1641 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1643 error = error < 0 ? errno : error;
1644 # else /* HAVE_NONPOSIX_GETPWUID_R */
1645 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1646 # if defined(_AIX) || defined(__hpux)
1647 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1648 pw = error == 0 ? &pwd : NULL;
1651 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1652 if (!pw || (pw->pw_uid != getuid ())) {
1653 /* LOGNAME is lying, fall back to looking up the uid */
1654 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1657 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1659 error = pw ? 0 : errno;
1661 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1665 /* we bail out prematurely if the user id can't be found
1666 * (should be pretty rare case actually), or if the buffer
1667 * should be sufficiently big and lookups are still not
1670 if (error == 0 || error == ENOENT)
1672 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1673 (gulong) getuid ());
1676 if (bufsize > 32 * 1024)
1678 g_warning ("getpwuid_r(): failed due to: %s.",
1679 g_strerror (error));
1687 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1692 pw = getpwuid (getuid ());
1697 g_user_name = g_strdup (pw->pw_name);
1699 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1701 gchar **gecos_fields;
1704 /* split the gecos field and substitute '&' */
1705 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1706 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1707 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1708 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1709 g_strfreev (gecos_fields);
1710 g_strfreev (name_parts);
1714 g_home_dir = g_strdup (pw->pw_dir);
1719 #else /* !HAVE_PWD_H */
1723 guint len = UNLEN+1;
1724 wchar_t buffer[UNLEN+1];
1726 if (GetUserNameW (buffer, (LPDWORD) &len))
1728 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1729 g_real_name = g_strdup (g_user_name);
1732 #endif /* G_OS_WIN32 */
1734 #endif /* !HAVE_PWD_H */
1738 g_home_dir = g_strdup (g_getenv ("HOME"));
1742 /* change '\\' in %HOME% to '/' */
1743 g_strdelimit (g_home_dir, "\\",'/');
1746 g_user_name = g_strdup ("somebody");
1748 g_real_name = g_strdup ("Unknown");
1752 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1754 DWORD size = sizeof (hostname);
1755 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1757 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1761 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1762 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1763 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1766 g_tmp_dir_cp = g_strdup ("\\");
1767 if (!g_user_name_cp)
1768 g_user_name_cp = g_strdup ("somebody");
1769 if (!g_real_name_cp)
1770 g_real_name_cp = g_strdup ("Unknown");
1772 /* home_dir might be NULL, unlike tmp_dir, user_name and
1776 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1778 g_home_dir_cp = NULL;
1779 #endif /* G_OS_WIN32 */
1783 g_get_any_init (void)
1786 g_get_any_init_do ();
1790 g_get_any_init_locked (void)
1792 G_LOCK (g_utils_global);
1794 G_UNLOCK (g_utils_global);
1801 * Gets the user name of the current user. The encoding of the returned
1802 * string is system-defined. On UNIX, it might be the preferred file name
1803 * encoding, or something else, and there is no guarantee that it is even
1804 * consistent on a machine. On Windows, it is always UTF-8.
1806 * Returns: the user name of the current user.
1808 G_CONST_RETURN gchar*
1809 g_get_user_name (void)
1811 g_get_any_init_locked ();
1818 * Gets the real name of the user. This usually comes from the user's entry
1819 * in the <filename>passwd</filename> file. The encoding of the returned
1820 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1821 * If the real user name cannot be determined, the string "Unknown" is
1824 * Returns: the user's real name.
1826 G_CONST_RETURN gchar*
1827 g_get_real_name (void)
1829 g_get_any_init_locked ();
1836 * Gets the current user's home directory as defined in the
1837 * password database.
1839 * Note that in contrast to traditional UNIX tools, this function
1840 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1841 * environment variable.
1843 * One of the reasons for this decision is that applications in many
1844 * cases need special handling to deal with the case where
1845 * <envar>HOME</envar> is
1847 * <member>Not owned by the user</member>
1848 * <member>Not writeable</member>
1849 * <member>Not even readable</member>
1851 * Since applications are in general <emphasis>not</emphasis> written
1852 * to deal with these situations it was considered better to make
1853 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1854 * return the real home directory for the user. If applications
1855 * want to pay attention to <envar>HOME</envar>, they can do:
1857 * const char *homedir = g_getenv ("HOME");
1859 * homedir = g_get_home_dir (<!-- -->);
1862 * Returns: the current user's home directory
1864 G_CONST_RETURN gchar*
1865 g_get_home_dir (void)
1867 g_get_any_init_locked ();
1874 * Gets the directory to use for temporary files. This is found from
1875 * inspecting the environment variables <envar>TMPDIR</envar>,
1876 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1877 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1878 * The encoding of the returned string is system-defined. On Windows,
1879 * it is always UTF-8. The return value is never %NULL or the empty string.
1881 * Returns: the directory to use for temporary files.
1883 G_CONST_RETURN gchar*
1884 g_get_tmp_dir (void)
1886 g_get_any_init_locked ();
1893 * Return a name for the machine.
1895 * The returned name is not necessarily a fully-qualified domain name,
1896 * or even present in DNS or some other name service at all. It need
1897 * not even be unique on your local network or site, but usually it
1898 * is. Callers should not rely on the return value having any specific
1899 * properties like uniqueness for security purposes. Even if the name
1900 * of the machine is changed while an application is running, the
1901 * return value from this function does not change. The returned
1902 * string is owned by GLib and should not be modified or freed. If no
1903 * name can be determined, a default fixed string "localhost" is
1906 * Returns: the host name of the machine.
1911 g_get_host_name (void)
1913 g_get_any_init_locked ();
1917 G_LOCK_DEFINE_STATIC (g_prgname);
1918 static gchar *g_prgname = NULL;
1923 * Gets the name of the program. This name should <emphasis>not</emphasis>
1924 * be localized, contrast with g_get_application_name().
1925 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1926 * which is called by gtk_init(). The program name is found by taking
1927 * the last component of <literal>argv[0]</literal>.)
1929 * Returns: the name of the program. The returned string belongs
1930 * to GLib and must not be modified or freed.
1933 g_get_prgname (void)
1939 if (g_prgname == NULL)
1941 static gboolean beenhere = FALSE;
1945 gchar *utf8_buf = NULL;
1946 wchar_t buf[MAX_PATH+1];
1949 if (GetModuleFileNameW (GetModuleHandle (NULL),
1950 buf, G_N_ELEMENTS (buf)) > 0)
1951 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1955 g_prgname = g_path_get_basename (utf8_buf);
1962 G_UNLOCK (g_prgname);
1969 * @prgname: the name of the program.
1971 * Sets the name of the program. This name should <emphasis>not</emphasis>
1972 * be localized, contrast with g_set_application_name(). Note that for
1973 * thread-safety reasons this function can only be called once.
1976 g_set_prgname (const gchar *prgname)
1980 g_prgname = g_strdup (prgname);
1981 G_UNLOCK (g_prgname);
1984 G_LOCK_DEFINE_STATIC (g_application_name);
1985 static gchar *g_application_name = NULL;
1988 * g_get_application_name:
1990 * Gets a human-readable name for the application, as set by
1991 * g_set_application_name(). This name should be localized if
1992 * possible, and is intended for display to the user. Contrast with
1993 * g_get_prgname(), which gets a non-localized name. If
1994 * g_set_application_name() has not been called, returns the result of
1995 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1998 * Return value: human-readable application name. may return %NULL
2002 G_CONST_RETURN gchar*
2003 g_get_application_name (void)
2007 G_LOCK (g_application_name);
2008 retval = g_application_name;
2009 G_UNLOCK (g_application_name);
2012 return g_get_prgname ();
2018 * g_set_application_name:
2019 * @application_name: localized name of the application
2021 * Sets a human-readable name for the application. This name should be
2022 * localized if possible, and is intended for display to the user.
2023 * Contrast with g_set_prgname(), which sets a non-localized name.
2024 * g_set_prgname() will be called automatically by gtk_init(),
2025 * but g_set_application_name() will not.
2027 * Note that for thread safety reasons, this function can only
2030 * The application name will be used in contexts such as error messages,
2031 * or when displaying an application's name in the task list.
2036 g_set_application_name (const gchar *application_name)
2038 gboolean already_set = FALSE;
2040 G_LOCK (g_application_name);
2041 if (g_application_name)
2044 g_application_name = g_strdup (application_name);
2045 G_UNLOCK (g_application_name);
2048 g_warning ("g_set_application_name() called multiple times");
2052 * g_get_user_data_dir:
2054 * Returns a base directory in which to access application data such
2055 * as icons that is customized for a particular user.
2057 * On UNIX platforms this is determined using the mechanisms described in
2058 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2059 * XDG Base Directory Specification</ulink>.
2060 * In this case the directory retrieved will be XDG_DATA_HOME.
2062 * On Windows is the virtual folder that represents the My Documents
2063 * desktop item. See documentation for CSIDL_PERSONAL.
2065 * Return value: a string owned by GLib that must not be modified
2069 G_CONST_RETURN gchar*
2070 g_get_user_data_dir (void)
2074 G_LOCK (g_utils_global);
2076 if (!g_user_data_dir)
2079 data_dir = get_special_folder (CSIDL_PERSONAL);
2081 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2083 if (data_dir && data_dir[0])
2084 data_dir = g_strdup (data_dir);
2086 if (!data_dir || !data_dir[0])
2091 data_dir = g_build_filename (g_home_dir, ".local",
2094 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2098 g_user_data_dir = data_dir;
2101 data_dir = g_user_data_dir;
2103 G_UNLOCK (g_utils_global);
2109 g_init_user_config_dir (void)
2113 if (!g_user_config_dir)
2116 config_dir = get_special_folder (CSIDL_APPDATA);
2118 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2120 if (config_dir && config_dir[0])
2121 config_dir = g_strdup (config_dir);
2123 if (!config_dir || !config_dir[0])
2128 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2130 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2133 g_user_config_dir = config_dir;
2138 * g_get_user_config_dir:
2140 * Returns a base directory in which to store user-specific application
2141 * configuration information such as user preferences and settings.
2143 * On UNIX platforms this is determined using the mechanisms described in
2144 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2145 * XDG Base Directory Specification</ulink>.
2146 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2148 * On Windows is the directory that serves as a common repository for
2149 * application-specific data. A typical path is
2150 * C:\Documents and Settings\username\Application. See documentation for
2153 * Return value: a string owned by GLib that must not be modified
2157 G_CONST_RETURN gchar*
2158 g_get_user_config_dir (void)
2160 G_LOCK (g_utils_global);
2162 g_init_user_config_dir ();
2164 G_UNLOCK (g_utils_global);
2166 return g_user_config_dir;
2170 * g_get_user_cache_dir:
2172 * Returns a base directory in which to store non-essential, cached
2173 * data specific to particular user.
2175 * On UNIX platforms this is determined using the mechanisms described in
2176 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2177 * XDG Base Directory Specification</ulink>.
2178 * In this case the directory retrieved will be XDG_CACHE_HOME.
2180 * On Windows is the directory that serves as a common repository for
2181 * temporary Internet files. A typical path is
2182 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2183 * See documentation for CSIDL_INTERNET_CACHE.
2185 * Return value: a string owned by GLib that must not be modified
2189 G_CONST_RETURN gchar*
2190 g_get_user_cache_dir (void)
2194 G_LOCK (g_utils_global);
2196 if (!g_user_cache_dir)
2199 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2201 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2203 if (cache_dir && cache_dir[0])
2204 cache_dir = g_strdup (cache_dir);
2206 if (!cache_dir || !cache_dir[0])
2211 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2213 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2215 g_user_cache_dir = cache_dir;
2218 cache_dir = g_user_cache_dir;
2220 G_UNLOCK (g_utils_global);
2228 find_folder (OSType type)
2230 gchar *filename = NULL;
2233 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2235 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2239 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2243 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2247 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2249 CFStringGetCString (path, filename,
2250 CFStringGetLength (path) * 3 + 1,
2251 kCFStringEncodingUTF8);
2265 load_user_special_dirs (void)
2267 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2268 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2269 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2270 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2271 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2272 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2273 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2274 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2277 #endif /* HAVE_CARBON */
2279 #if defined(G_OS_WIN32)
2281 load_user_special_dirs (void)
2283 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2287 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2289 static const GUID FOLDERID_Downloads =
2290 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2291 static const GUID FOLDERID_Public =
2292 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2296 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2297 "SHGetKnownFolderPath");
2299 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2300 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2302 if (p_SHGetKnownFolderPath == NULL)
2304 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2309 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2310 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2311 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2312 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2313 CoTaskMemFree (wcp);
2316 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2317 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2319 if (p_SHGetKnownFolderPath == NULL)
2322 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2327 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2328 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2329 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2330 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2331 CoTaskMemFree (wcp);
2334 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2335 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2337 #endif /* G_OS_WIN32 */
2339 static void g_init_user_config_dir (void);
2341 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2343 /* adapted from xdg-user-dir-lookup.c
2345 * Copyright (C) 2007 Red Hat Inc.
2347 * Permission is hereby granted, free of charge, to any person
2348 * obtaining a copy of this software and associated documentation files
2349 * (the "Software"), to deal in the Software without restriction,
2350 * including without limitation the rights to use, copy, modify, merge,
2351 * publish, distribute, sublicense, and/or sell copies of the Software,
2352 * and to permit persons to whom the Software is furnished to do so,
2353 * subject to the following conditions:
2355 * The above copyright notice and this permission notice shall be
2356 * included in all copies or substantial portions of the Software.
2358 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2359 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2360 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2361 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2362 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2363 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2364 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2368 load_user_special_dirs (void)
2375 g_init_user_config_dir ();
2376 config_file = g_build_filename (g_user_config_dir,
2380 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2382 g_free (config_file);
2386 lines = g_strsplit (data, "\n", -1);
2387 n_lines = g_strv_length (lines);
2390 for (i = 0; i < n_lines; i++)
2392 gchar *buffer = lines[i];
2395 gboolean is_relative = FALSE;
2396 GUserDirectory directory;
2398 /* Remove newline at end */
2399 len = strlen (buffer);
2400 if (len > 0 && buffer[len - 1] == '\n')
2401 buffer[len - 1] = 0;
2404 while (*p == ' ' || *p == '\t')
2407 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2409 directory = G_USER_DIRECTORY_DESKTOP;
2410 p += strlen ("XDG_DESKTOP_DIR");
2412 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2414 directory = G_USER_DIRECTORY_DOCUMENTS;
2415 p += strlen ("XDG_DOCUMENTS_DIR");
2417 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2419 directory = G_USER_DIRECTORY_DOWNLOAD;
2420 p += strlen ("XDG_DOWNLOAD_DIR");
2422 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2424 directory = G_USER_DIRECTORY_MUSIC;
2425 p += strlen ("XDG_MUSIC_DIR");
2427 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2429 directory = G_USER_DIRECTORY_PICTURES;
2430 p += strlen ("XDG_PICTURES_DIR");
2432 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2434 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2435 p += strlen ("XDG_PUBLICSHARE_DIR");
2437 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2439 directory = G_USER_DIRECTORY_TEMPLATES;
2440 p += strlen ("XDG_TEMPLATES_DIR");
2442 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2444 directory = G_USER_DIRECTORY_VIDEOS;
2445 p += strlen ("XDG_VIDEOS_DIR");
2450 while (*p == ' ' || *p == '\t')
2457 while (*p == ' ' || *p == '\t')
2464 if (strncmp (p, "$HOME", 5) == 0)
2472 d = strrchr (p, '"');
2479 /* remove trailing slashes */
2481 if (d[len - 1] == '/')
2487 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2490 g_user_special_dirs[directory] = g_strdup (d);
2494 g_free (config_file);
2497 #endif /* G_OS_UNIX && !HAVE_CARBON */
2501 * g_reload_user_special_dirs_cache:
2503 * Resets the cache used for g_get_user_special_dir(), so
2504 * that the latest on-disk version is used. Call this only
2505 * if you just changed the data on disk yourself.
2507 * Due to threadsafety issues this may cause leaking of strings
2508 * that were previously returned from g_get_user_special_dir()
2509 * that can't be freed. We ensure to only leak the data for
2510 * the directories that actually changed value though.
2515 g_reload_user_special_dirs_cache (void)
2519 G_LOCK (g_utils_global);
2521 if (g_user_special_dirs != NULL)
2523 /* save a copy of the pointer, to check if some memory can be preserved */
2524 char **old_g_user_special_dirs = g_user_special_dirs;
2527 /* recreate and reload our cache */
2528 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2529 load_user_special_dirs ();
2531 /* only leak changed directories */
2532 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2534 old_val = old_g_user_special_dirs[i];
2535 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2538 g_free (g_user_special_dirs[i]);
2539 g_user_special_dirs[i] = old_val;
2545 /* free the old array */
2546 g_free (old_g_user_special_dirs);
2549 G_UNLOCK (g_utils_global);
2553 * g_get_user_special_dir:
2554 * @directory: the logical id of special directory
2556 * Returns the full path of a special directory using its logical id.
2558 * On Unix this is done using the XDG special user directories.
2559 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2560 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2561 * user directories have not been set up.
2563 * Depending on the platform, the user might be able to change the path
2564 * of the special directory without requiring the session to restart; GLib
2565 * will not reflect any change once the special directories are loaded.
2567 * Return value: the path to the specified special directory, or %NULL
2568 * if the logical id was not found. The returned string is owned by
2569 * GLib and should not be modified or freed.
2573 G_CONST_RETURN gchar *
2574 g_get_user_special_dir (GUserDirectory directory)
2576 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2577 directory < G_USER_N_DIRECTORIES, NULL);
2579 G_LOCK (g_utils_global);
2581 if (G_UNLIKELY (g_user_special_dirs == NULL))
2583 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2585 load_user_special_dirs ();
2587 /* Special-case desktop for historical compatibility */
2588 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2592 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2593 g_build_filename (g_home_dir, "Desktop", NULL);
2597 G_UNLOCK (g_utils_global);
2599 return g_user_special_dirs[directory];
2604 #undef g_get_system_data_dirs
2607 get_module_for_address (gconstpointer address)
2609 /* Holds the g_utils_global lock */
2611 static gboolean beenhere = FALSE;
2612 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2613 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2614 HMODULE hmodule = NULL;
2621 p_GetModuleHandleExA =
2622 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2623 "GetModuleHandleExA");
2627 if (p_GetModuleHandleExA == NULL ||
2628 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2629 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2632 MEMORY_BASIC_INFORMATION mbi;
2633 VirtualQuery (address, &mbi, sizeof (mbi));
2634 hmodule = (HMODULE) mbi.AllocationBase;
2641 get_module_share_dir (gconstpointer address)
2647 hmodule = get_module_for_address (address);
2648 if (hmodule == NULL)
2651 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2652 retval = g_build_filename (filename, "share", NULL);
2658 G_CONST_RETURN gchar * G_CONST_RETURN *
2659 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2663 static GHashTable *per_module_data_dirs = NULL;
2668 if (address_of_function)
2670 G_LOCK (g_utils_global);
2671 hmodule = get_module_for_address (address_of_function);
2672 if (hmodule != NULL)
2674 if (per_module_data_dirs == NULL)
2675 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2678 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2682 G_UNLOCK (g_utils_global);
2683 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2689 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2691 /* Documents and Settings\All Users\Application Data */
2692 p = get_special_folder (CSIDL_COMMON_APPDATA);
2694 g_array_append_val (data_dirs, p);
2696 /* Documents and Settings\All Users\Documents */
2697 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2699 g_array_append_val (data_dirs, p);
2701 /* Using the above subfolders of Documents and Settings perhaps
2702 * makes sense from a Windows perspective.
2704 * But looking at the actual use cases of this function in GTK+
2705 * and GNOME software, what we really want is the "share"
2706 * subdirectory of the installation directory for the package
2707 * our caller is a part of.
2709 * The address_of_function parameter, if non-NULL, points to a
2710 * function in the calling module. Use that to determine that
2711 * module's installation folder, and use its "share" subfolder.
2713 * Additionally, also use the "share" subfolder of the installation
2714 * locations of GLib and the .exe file being run.
2716 * To guard against none of the above being what is really wanted,
2717 * callers of this function should have Win32-specific code to look
2718 * up their installation folder themselves, and handle a subfolder
2719 * "share" of it in the same way as the folders returned from this
2723 p = get_module_share_dir (address_of_function);
2725 g_array_append_val (data_dirs, p);
2727 if (glib_dll != NULL)
2729 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2730 p = g_build_filename (glib_root, "share", NULL);
2732 g_array_append_val (data_dirs, p);
2736 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2737 p = g_build_filename (exe_root, "share", NULL);
2739 g_array_append_val (data_dirs, p);
2742 retval = (gchar **) g_array_free (data_dirs, FALSE);
2744 if (address_of_function)
2746 if (hmodule != NULL)
2747 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2748 G_UNLOCK (g_utils_global);
2751 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2757 * g_get_system_data_dirs:
2759 * Returns an ordered list of base directories in which to access
2760 * system-wide application data.
2762 * On UNIX platforms this is determined using the mechanisms described in
2763 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2764 * XDG Base Directory Specification</ulink>
2765 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2767 * On Windows the first elements in the list are the Application Data
2768 * and Documents folders for All Users. (These can be determined only
2769 * on Windows 2000 or later and are not present in the list on other
2770 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2771 * CSIDL_COMMON_DOCUMENTS.
2773 * Then follows the "share" subfolder in the installation folder for
2774 * the package containing the DLL that calls this function, if it can
2777 * Finally the list contains the "share" subfolder in the installation
2778 * folder for GLib, and in the installation folder for the package the
2779 * application's .exe file belongs to.
2781 * The installation folders above are determined by looking up the
2782 * folder where the module (DLL or EXE) in question is located. If the
2783 * folder's name is "bin", its parent is used, otherwise the folder
2786 * Note that on Windows the returned list can vary depending on where
2787 * this function is called.
2789 * Return value: a %NULL-terminated array of strings owned by GLib that must
2790 * not be modified or freed.
2793 G_CONST_RETURN gchar * G_CONST_RETURN *
2794 g_get_system_data_dirs (void)
2796 gchar **data_dir_vector;
2798 G_LOCK (g_utils_global);
2800 if (!g_system_data_dirs)
2803 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2805 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2807 if (!data_dirs || !data_dirs[0])
2808 data_dirs = "/usr/local/share/:/usr/share/";
2810 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2813 g_system_data_dirs = data_dir_vector;
2816 data_dir_vector = g_system_data_dirs;
2818 G_UNLOCK (g_utils_global);
2820 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2824 * g_get_system_config_dirs:
2826 * Returns an ordered list of base directories in which to access
2827 * system-wide configuration information.
2829 * On UNIX platforms this is determined using the mechanisms described in
2830 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2831 * XDG Base Directory Specification</ulink>.
2832 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2834 * On Windows is the directory that contains application data for all users.
2835 * A typical path is C:\Documents and Settings\All Users\Application Data.
2836 * This folder is used for application data that is not user specific.
2837 * For example, an application can store a spell-check dictionary, a database
2838 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2839 * This information will not roam and is available to anyone using the computer.
2841 * Return value: a %NULL-terminated array of strings owned by GLib that must
2842 * not be modified or freed.
2845 G_CONST_RETURN gchar * G_CONST_RETURN *
2846 g_get_system_config_dirs (void)
2848 gchar *conf_dirs, **conf_dir_vector;
2850 G_LOCK (g_utils_global);
2852 if (!g_system_config_dirs)
2855 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2858 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2863 /* Return empty list */
2864 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2867 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2869 if (!conf_dirs || !conf_dirs[0])
2870 conf_dirs = "/etc/xdg";
2872 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2875 g_system_config_dirs = conf_dir_vector;
2878 conf_dir_vector = g_system_config_dirs;
2879 G_UNLOCK (g_utils_global);
2881 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2886 static GHashTable *alias_table = NULL;
2888 /* read an alias file for the locales */
2890 read_aliases (gchar *file)
2896 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2897 fp = fopen (file,"r");
2900 while (fgets (buf, 256, fp))
2906 /* Line is a comment */
2907 if ((buf[0] == '#') || (buf[0] == '\0'))
2910 /* Reads first column */
2911 for (p = buf, q = NULL; *p; p++) {
2912 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2915 while ((*q == '\t') || (*q == ' ')) {
2921 /* The line only had one column */
2922 if (!q || *q == '\0')
2925 /* Read second column */
2926 for (p = q; *p; p++) {
2927 if ((*p == '\t') || (*p == ' ')) {
2933 /* Add to alias table if necessary */
2934 if (!g_hash_table_lookup (alias_table, buf)) {
2935 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2944 unalias_lang (char *lang)
2951 read_aliases ("/usr/share/locale/locale.alias");
2954 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2959 static gboolean said_before = FALSE;
2961 g_warning ("Too many alias levels for a locale, "
2962 "may indicate a loop");
2971 /* Mask for components of locale spec. The ordering here is from
2972 * least significant to most significant
2976 COMPONENT_CODESET = 1 << 0,
2977 COMPONENT_TERRITORY = 1 << 1,
2978 COMPONENT_MODIFIER = 1 << 2
2981 /* Break an X/Open style locale specification into components
2984 explode_locale (const gchar *locale,
2990 const gchar *uscore_pos;
2991 const gchar *at_pos;
2992 const gchar *dot_pos;
2996 uscore_pos = strchr (locale, '_');
2997 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2998 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3002 mask |= COMPONENT_MODIFIER;
3003 *modifier = g_strdup (at_pos);
3006 at_pos = locale + strlen (locale);
3010 mask |= COMPONENT_CODESET;
3011 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3018 mask |= COMPONENT_TERRITORY;
3019 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3022 uscore_pos = dot_pos;
3024 *language = g_strndup (locale, uscore_pos - locale);
3030 * Compute all interesting variants for a given locale name -
3031 * by stripping off different components of the value.
3033 * For simplicity, we assume that the locale is in
3034 * X/Open format: language[_territory][.codeset][@modifier]
3036 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3037 * as well. We could just copy the code from glibc wholesale
3038 * but it is big, ugly, and complicated, so I'm reluctant
3039 * to do so when this should handle 99% of the time...
3042 _g_compute_locale_variants (const gchar *locale)
3044 GSList *retval = NULL;
3046 gchar *language = NULL;
3047 gchar *territory = NULL;
3048 gchar *codeset = NULL;
3049 gchar *modifier = NULL;
3054 g_return_val_if_fail (locale != NULL, NULL);
3056 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3058 /* Iterate through all possible combinations, from least attractive
3059 * to most attractive.
3061 for (i = 0; i <= mask; i++)
3062 if ((i & ~mask) == 0)
3064 gchar *val = g_strconcat (language,
3065 (i & COMPONENT_TERRITORY) ? territory : "",
3066 (i & COMPONENT_CODESET) ? codeset : "",
3067 (i & COMPONENT_MODIFIER) ? modifier : "",
3069 retval = g_slist_prepend (retval, val);
3073 if (mask & COMPONENT_CODESET)
3075 if (mask & COMPONENT_TERRITORY)
3077 if (mask & COMPONENT_MODIFIER)
3083 /* The following is (partly) taken from the gettext package.
3084 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3086 static const gchar *
3087 guess_category_value (const gchar *category_name)
3089 const gchar *retval;
3091 /* The highest priority value is the `LANGUAGE' environment
3092 variable. This is a GNU extension. */
3093 retval = g_getenv ("LANGUAGE");
3094 if ((retval != NULL) && (retval[0] != '\0'))
3097 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3098 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3099 systems this can be done by the `setlocale' function itself. */
3101 /* Setting of LC_ALL overwrites all other. */
3102 retval = g_getenv ("LC_ALL");
3103 if ((retval != NULL) && (retval[0] != '\0'))
3106 /* Next comes the name of the desired category. */
3107 retval = g_getenv (category_name);
3108 if ((retval != NULL) && (retval[0] != '\0'))
3111 /* Last possibility is the LANG environment variable. */
3112 retval = g_getenv ("LANG");
3113 if ((retval != NULL) && (retval[0] != '\0'))
3116 #ifdef G_PLATFORM_WIN32
3117 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3118 * LANG, which we already did above. Oh well. The main point of
3119 * calling g_win32_getlocale() is to get the thread's locale as used
3120 * by Windows and the Microsoft C runtime (in the "English_United
3121 * States" format) translated into the Unixish format.
3124 char *locale = g_win32_getlocale ();
3125 retval = g_intern_string (locale);
3134 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3136 struct _GLanguageNamesCache {
3138 gchar **language_names;
3142 language_names_cache_free (gpointer data)
3144 GLanguageNamesCache *cache = data;
3145 g_free (cache->languages);
3146 g_strfreev (cache->language_names);
3151 * g_get_language_names:
3153 * Computes a list of applicable locale names, which can be used to
3154 * e.g. construct locale-dependent filenames or search paths. The returned
3155 * list is sorted from most desirable to least desirable and always contains
3156 * the default locale "C".
3158 * For example, if LANGUAGE=de:en_US, then the returned list is
3159 * "de", "en_US", "en", "C".
3161 * This function consults the environment variables <envar>LANGUAGE</envar>,
3162 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3163 * to find the list of locales specified by the user.
3165 * Return value: a %NULL-terminated array of strings owned by GLib
3166 * that must not be modified or freed.
3170 G_CONST_RETURN gchar * G_CONST_RETURN *
3171 g_get_language_names (void)
3173 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3174 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3179 cache = g_new0 (GLanguageNamesCache, 1);
3180 g_static_private_set (&cache_private, cache, language_names_cache_free);
3183 value = guess_category_value ("LC_MESSAGES");
3187 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3194 g_free (cache->languages);
3195 g_strfreev (cache->language_names);
3196 cache->languages = g_strdup (value);
3198 alist = g_strsplit (value, ":", 0);
3200 for (a = alist; *a; a++)
3202 gchar *b = unalias_lang (*a);
3203 list = g_slist_concat (list, _g_compute_locale_variants (b));
3206 list = g_slist_append (list, g_strdup ("C"));
3208 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3209 for (l = list, i = 0; l; l = l->next, i++)
3210 languages[i] = l->data;
3211 languages[i] = NULL;
3213 g_slist_free (list);
3216 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3221 * @v: a #gpointer key
3223 * Converts a gpointer to a hash value.
3224 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3225 * when using pointers as keys in a #GHashTable.
3227 * Returns: a hash value corresponding to the key.
3230 g_direct_hash (gconstpointer v)
3232 return GPOINTER_TO_UINT (v);
3238 * @v2: a key to compare with @v1.
3240 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3241 * It can be passed to g_hash_table_new() as the @key_equal_func
3242 * parameter, when using pointers as keys in a #GHashTable.
3244 * Returns: %TRUE if the two keys match.
3247 g_direct_equal (gconstpointer v1,
3255 * @v1: a pointer to a #gint key.
3256 * @v2: a pointer to a #gint key to compare with @v1.
3258 * Compares the two #gint values being pointed to and returns
3259 * %TRUE if they are equal.
3260 * It can be passed to g_hash_table_new() as the @key_equal_func
3261 * parameter, when using pointers to integers as keys in a #GHashTable.
3263 * Returns: %TRUE if the two keys match.
3266 g_int_equal (gconstpointer v1,
3269 return *((const gint*) v1) == *((const gint*) v2);
3274 * @v: a pointer to a #gint key
3276 * Converts a pointer to a #gint to a hash value.
3277 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3278 * when using pointers to integers values as keys in a #GHashTable.
3280 * Returns: a hash value corresponding to the key.
3283 g_int_hash (gconstpointer v)
3285 return *(const gint*) v;
3290 * @v1: a pointer to a #gint64 key.
3291 * @v2: a pointer to a #gint64 key to compare with @v1.
3293 * Compares the two #gint64 values being pointed to and returns
3294 * %TRUE if they are equal.
3295 * It can be passed to g_hash_table_new() as the @key_equal_func
3296 * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3298 * Returns: %TRUE if the two keys match.
3303 g_int64_equal (gconstpointer v1,
3306 return *((const gint64*) v1) == *((const gint64*) v2);
3311 * @v: a pointer to a #gint64 key
3313 * Converts a pointer to a #gint64 to a hash value.
3314 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3315 * when using pointers to 64-bit integers values as keys in a #GHashTable.
3317 * Returns: a hash value corresponding to the key.
3322 g_int64_hash (gconstpointer v)
3324 return (guint) *(const gint64*) v;
3329 * @v1: a pointer to a #gdouble key.
3330 * @v2: a pointer to a #gdouble key to compare with @v1.
3332 * Compares the two #gdouble values being pointed to and returns
3333 * %TRUE if they are equal.
3334 * It can be passed to g_hash_table_new() as the @key_equal_func
3335 * parameter, when using pointers to doubles as keys in a #GHashTable.
3337 * Returns: %TRUE if the two keys match.
3342 g_double_equal (gconstpointer v1,
3345 return *((const gdouble*) v1) == *((const gdouble*) v2);
3350 * @v: a pointer to a #gdouble key
3352 * Converts a pointer to a #gdouble to a hash value.
3353 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3354 * when using pointers to doubles as keys in a #GHashTable.
3356 * Returns: a hash value corresponding to the key.
3361 g_double_hash (gconstpointer v)
3363 return (guint) *(const gdouble*) v;
3367 * g_nullify_pointer:
3368 * @nullify_location: the memory address of the pointer.
3370 * Set the pointer at the specified location to %NULL.
3373 g_nullify_pointer (gpointer *nullify_location)
3375 g_return_if_fail (nullify_location != NULL);
3377 *nullify_location = NULL;
3383 * Get the codeset for the current locale.
3385 * Return value: a newly allocated string containing the name
3386 * of the codeset. This string must be freed with g_free().
3389 g_get_codeset (void)
3391 const gchar *charset;
3393 g_get_charset (&charset);
3395 return g_strdup (charset);
3398 /* This is called from g_thread_init(). It's used to
3399 * initialize some static data in a threadsafe way.
3402 _g_utils_thread_init (void)
3404 g_get_language_names ();
3410 * _glib_get_locale_dir:
3412 * Return the path to the share\locale or lib\locale subfolder of the
3413 * GLib installation folder. The path is in the system codepage. We
3414 * have to use system codepage as bindtextdomain() doesn't have a
3418 _glib_get_locale_dir (void)
3420 gchar *install_dir = NULL, *locale_dir;
3421 gchar *retval = NULL;
3423 if (glib_dll != NULL)
3424 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3429 * Append "/share/locale" or "/lib/locale" depending on whether
3430 * autoconfigury detected GNU gettext or not.
3432 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3438 locale_dir = g_build_filename (install_dir, p, NULL);
3440 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3442 g_free (install_dir);
3443 g_free (locale_dir);
3449 return g_strdup ("");
3452 #undef GLIB_LOCALE_DIR
3454 #endif /* G_OS_WIN32 */
3458 * @str: The string to be translated
3460 * Returns the translated string from the glib translations.
3461 * This is an internal function and should only be used by
3462 * the internals of glib (such as libgio).
3464 * Returns: the transation of @str to the current locale
3466 G_CONST_RETURN gchar *
3467 glib_gettext (const gchar *str)
3469 static gboolean _glib_gettext_initialized = FALSE;
3471 if (!_glib_gettext_initialized)
3474 gchar *tmp = _glib_get_locale_dir ();
3475 bindtextdomain (GETTEXT_PACKAGE, tmp);
3478 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3480 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3481 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3483 _glib_gettext_initialized = TRUE;
3486 return g_dgettext (GETTEXT_PACKAGE, str);
3489 #if defined (G_OS_WIN32) && !defined (_WIN64)
3491 /* Binary compatibility versions. Not for newly compiled code. */
3493 #undef g_find_program_in_path
3496 g_find_program_in_path (const gchar *program)
3498 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3499 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3502 g_free (utf8_program);
3503 if (utf8_retval == NULL)
3505 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3506 g_free (utf8_retval);
3511 #undef g_get_current_dir
3514 g_get_current_dir (void)
3516 gchar *utf8_dir = g_get_current_dir_utf8 ();
3517 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3524 G_CONST_RETURN gchar*
3525 g_getenv (const gchar *variable)
3527 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3528 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3532 g_free (utf8_variable);
3535 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3536 quark = g_quark_from_string (value);
3539 return g_quark_to_string (quark);
3545 g_setenv (const gchar *variable,
3549 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3550 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3551 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3553 g_free (utf8_variable);
3554 g_free (utf8_value);
3562 g_unsetenv (const gchar *variable)
3564 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3566 g_unsetenv_utf8 (utf8_variable);
3568 g_free (utf8_variable);
3571 #undef g_get_user_name
3573 G_CONST_RETURN gchar*
3574 g_get_user_name (void)
3576 g_get_any_init_locked ();
3577 return g_user_name_cp;
3580 #undef g_get_real_name
3582 G_CONST_RETURN gchar*
3583 g_get_real_name (void)
3585 g_get_any_init_locked ();
3586 return g_real_name_cp;
3589 #undef g_get_home_dir
3591 G_CONST_RETURN gchar*
3592 g_get_home_dir (void)
3594 g_get_any_init_locked ();
3595 return g_home_dir_cp;
3598 #undef g_get_tmp_dir
3600 G_CONST_RETURN gchar*
3601 g_get_tmp_dir (void)
3603 g_get_any_init_locked ();
3604 return g_tmp_dir_cp;