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
61 #include "gprintfint.h"
62 #include "gthreadprivate.h"
66 #define G_PATH_LENGTH MAXPATHLEN
67 #elif defined (PATH_MAX)
68 #define G_PATH_LENGTH PATH_MAX
69 #elif defined (_PC_PATH_MAX)
70 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
72 #define G_PATH_LENGTH 2048
75 #ifdef G_PLATFORM_WIN32
76 # define STRICT /* Strict typing, please */
79 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
80 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
81 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
83 # include <lmcons.h> /* For UNLEN */
84 #endif /* G_PLATFORM_WIN32 */
89 /* older SDK (e.g. msvc 5.0) does not have these*/
90 # ifndef CSIDL_MYMUSIC
91 # define CSIDL_MYMUSIC 13
93 # ifndef CSIDL_MYVIDEO
94 # define CSIDL_MYVIDEO 14
96 # ifndef CSIDL_INTERNET_CACHE
97 # define CSIDL_INTERNET_CACHE 32
99 # ifndef CSIDL_COMMON_APPDATA
100 # define CSIDL_COMMON_APPDATA 35
102 # ifndef CSIDL_MYPICTURES
103 # define CSIDL_MYPICTURES 0x27
105 # ifndef CSIDL_COMMON_DOCUMENTS
106 # define CSIDL_COMMON_DOCUMENTS 46
108 # ifndef CSIDL_PROFILE
109 # define CSIDL_PROFILE 40
111 # include <process.h>
115 #include <CoreServices/CoreServices.h>
119 #include <langinfo.h>
122 const guint glib_major_version = GLIB_MAJOR_VERSION;
123 const guint glib_minor_version = GLIB_MINOR_VERSION;
124 const guint glib_micro_version = GLIB_MICRO_VERSION;
125 const guint glib_interface_age = GLIB_INTERFACE_AGE;
126 const guint glib_binary_age = GLIB_BINARY_AGE;
128 #ifdef G_PLATFORM_WIN32
130 static HMODULE glib_dll = NULL;
135 DllMain (HINSTANCE hinstDLL,
139 if (fdwReason == DLL_PROCESS_ATTACH)
148 _glib_get_dll_directory (void)
152 wchar_t wc_fn[MAX_PATH];
155 if (glib_dll == NULL)
159 /* This code is different from that in
160 * g_win32_get_package_installation_directory_of_module() in that
161 * here we return the actual folder where the GLib DLL is. We don't
162 * do the check for it being in a "bin" or "lib" subfolder and then
163 * returning the parent of that.
165 * In a statically built GLib, glib_dll will be NULL and we will
166 * thus look up the application's .exe file's location.
168 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
171 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
173 p = strrchr (retval, G_DIR_SEPARATOR);
187 * glib_check_version:
188 * @required_major: the required major version.
189 * @required_minor: the required minor version.
190 * @required_micro: the required micro version.
192 * Checks that the GLib library in use is compatible with the
193 * given version. Generally you would pass in the constants
194 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
195 * as the three arguments to this function; that produces
196 * a check that the library in use is compatible with
197 * the version of GLib the application or module was compiled
200 * Compatibility is defined by two things: first the version
201 * of the running library is newer than the version
202 * @required_major.required_minor.@required_micro. Second
203 * the running library must be binary compatible with the
204 * version @required_major.required_minor.@required_micro
205 * (same major version.)
207 * Return value: %NULL if the GLib library is compatible with the
208 * given version, or a string describing the version mismatch.
209 * The returned string is owned by GLib and must not be modified
215 glib_check_version (guint required_major,
216 guint required_minor,
217 guint required_micro)
219 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
220 gint required_effective_micro = 100 * required_minor + required_micro;
222 if (required_major > GLIB_MAJOR_VERSION)
223 return "GLib version too old (major mismatch)";
224 if (required_major < GLIB_MAJOR_VERSION)
225 return "GLib version too new (major mismatch)";
226 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
227 return "GLib version too new (micro mismatch)";
228 if (required_effective_micro > glib_effective_micro)
229 return "GLib version too old (micro mismatch)";
233 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
236 * @dest: the destination address to copy the bytes to.
237 * @src: the source address to copy the bytes from.
238 * @len: the number of bytes to copy.
240 * Copies a block of memory @len bytes long, from @src to @dest.
241 * The source and destination areas may overlap.
243 * In order to use this function, you must include
244 * <filename>string.h</filename> yourself, because this macro will
245 * typically simply resolve to memmove() and GLib does not include
246 * <filename>string.h</filename> for you.
249 g_memmove (gpointer dest,
253 gchar* destptr = dest;
254 const gchar* srcptr = src;
255 if (src + len < dest || dest + len < src)
257 bcopy (src, dest, len);
260 else if (dest <= src)
263 *(destptr++) = *(srcptr++);
270 *(--destptr) = *(--srcptr);
273 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
281 * @func: the function to call on normal program termination.
283 * Specifies a function to be called at normal program termination.
285 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
286 * macro that maps to a call to the atexit() function in the C
287 * library. This means that in case the code that calls g_atexit(),
288 * i.e. atexit(), is in a DLL, the function will be called when the
289 * DLL is detached from the program. This typically makes more sense
290 * than that the function is called when the GLib DLL is detached,
291 * which happened earlier when g_atexit() was a function in the GLib
294 * The behaviour of atexit() in the context of dynamically loaded
295 * modules is not formally specified and varies wildly.
297 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
298 * loaded module which is unloaded before the program terminates might
299 * well cause a crash at program exit.
301 * Some POSIX systems implement atexit() like Windows, and have each
302 * dynamically loaded module maintain an own atexit chain that is
303 * called when the module is unloaded.
305 * On other POSIX systems, before a dynamically loaded module is
306 * unloaded, the registered atexit functions (if any) residing in that
307 * module are called, regardless where the code that registered them
308 * resided. This is presumably the most robust approach.
310 * As can be seen from the above, for portability it's best to avoid
311 * calling g_atexit() (or atexit()) except in the main executable of a
315 g_atexit (GVoidFunc func)
318 const gchar *error = NULL;
320 /* keep this in sync with glib.h */
322 #ifdef G_NATIVE_ATEXIT
323 result = ATEXIT (func);
325 error = g_strerror (errno);
326 #elif defined (HAVE_ATEXIT)
327 # ifdef NeXT /* @#%@! NeXTStep */
328 result = !atexit ((void (*)(void)) func);
330 error = g_strerror (errno);
332 result = atexit ((void (*)(void)) func);
334 error = g_strerror (errno);
336 #elif defined (HAVE_ON_EXIT)
337 result = on_exit ((void (*)(int, void *)) func, NULL);
339 error = g_strerror (errno);
342 error = "no implementation";
343 #endif /* G_NATIVE_ATEXIT */
346 g_error ("Could not register atexit() function: %s", error);
349 /* Based on execvp() from GNU Libc.
350 * Some of this code is cut-and-pasted into gspawn.c
354 my_strchrnul (const gchar *str,
357 gchar *p = (gchar*)str;
358 while (*p && (*p != c))
366 static gchar *inner_find_program_in_path (const gchar *program);
369 g_find_program_in_path (const gchar *program)
371 const gchar *last_dot = strrchr (program, '.');
373 if (last_dot == NULL ||
374 strchr (last_dot, '\\') != NULL ||
375 strchr (last_dot, '/') != NULL)
377 const gint program_length = strlen (program);
378 gchar *pathext = g_build_path (";",
379 ".exe;.cmd;.bat;.com",
380 g_getenv ("PATHEXT"),
383 gchar *decorated_program;
389 gchar *q = my_strchrnul (p, ';');
391 decorated_program = g_malloc (program_length + (q-p) + 1);
392 memcpy (decorated_program, program, program_length);
393 memcpy (decorated_program+program_length, p, q-p);
394 decorated_program [program_length + (q-p)] = '\0';
396 retval = inner_find_program_in_path (decorated_program);
397 g_free (decorated_program);
405 } while (*p++ != '\0');
410 return inner_find_program_in_path (program);
416 * g_find_program_in_path:
417 * @program: a program name in the GLib file name encoding
419 * Locates the first executable named @program in the user's path, in the
420 * same way that execvp() would locate it. Returns an allocated string
421 * with the absolute path name, or %NULL if the program is not found in
422 * the path. If @program is already an absolute path, returns a copy of
423 * @program if @program exists and is executable, and %NULL otherwise.
425 * On Windows, if @program does not have a file type suffix, tries
426 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
427 * the <envar>PATHEXT</envar> environment variable.
429 * On Windows, it looks for the file in the same way as CreateProcess()
430 * would. This means first in the directory where the executing
431 * program was loaded from, then in the current directory, then in the
432 * Windows 32-bit system directory, then in the Windows directory, and
433 * finally in the directories in the <envar>PATH</envar> environment
434 * variable. If the program is found, the return value contains the
435 * full name including the type suffix.
437 * Return value: absolute path, or %NULL
441 inner_find_program_in_path (const gchar *program)
444 g_find_program_in_path (const gchar *program)
447 const gchar *path, *p;
448 gchar *name, *freeme;
450 const gchar *path_copy;
451 gchar *filename = NULL, *appdir = NULL;
452 gchar *sysdir = NULL, *windir = NULL;
454 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
460 g_return_val_if_fail (program != NULL, NULL);
462 /* If it is an absolute path, or a relative path including subdirectories,
463 * don't look in PATH.
465 if (g_path_is_absolute (program)
466 || strchr (program, G_DIR_SEPARATOR) != NULL
468 || strchr (program, '/') != NULL
472 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
473 !g_file_test (program, G_FILE_TEST_IS_DIR))
474 return g_strdup (program);
479 path = g_getenv ("PATH");
480 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
483 /* There is no `PATH' in the environment. The default
484 * search path in GNU libc is the current directory followed by
485 * the path `confstr' returns for `_CS_PATH'.
488 /* In GLib we put . last, for security, and don't use the
489 * unportable confstr(); UNIX98 does not actually specify
490 * what to search if PATH is unset. POSIX may, dunno.
493 path = "/bin:/usr/bin:.";
496 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
497 if (n > 0 && n < MAXPATHLEN)
498 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
500 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
501 if (n > 0 && n < MAXPATHLEN)
502 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
504 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
505 if (n > 0 && n < MAXPATHLEN)
506 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
510 appdir = g_path_get_dirname (filename);
514 path = g_strdup (path);
518 const gchar *tem = path;
519 path = g_strconcat (windir, ";", path, NULL);
520 g_free ((gchar *) tem);
526 const gchar *tem = path;
527 path = g_strconcat (sysdir, ";", path, NULL);
528 g_free ((gchar *) tem);
533 const gchar *tem = path;
534 path = g_strconcat (".;", path, NULL);
535 g_free ((gchar *) tem);
540 const gchar *tem = path;
541 path = g_strconcat (appdir, ";", path, NULL);
542 g_free ((gchar *) tem);
549 len = strlen (program) + 1;
550 pathlen = strlen (path);
551 freeme = name = g_malloc (pathlen + len + 1);
553 /* Copy the file name at the top, including '\0' */
554 memcpy (name + pathlen + 1, program, len);
555 name = name + pathlen;
556 /* And add the slash before the filename */
557 *name = G_DIR_SEPARATOR;
565 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
568 /* Two adjacent colons, or a colon at the beginning or the end
569 * of `PATH' means to search the current directory.
573 startp = memcpy (name - (p - path), path, p - path);
575 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
576 !g_file_test (startp, G_FILE_TEST_IS_DIR))
579 ret = g_strdup (startp);
582 g_free ((gchar *) path_copy);
587 while (*p++ != '\0');
591 g_free ((gchar *) path_copy);
598 debug_key_matches (const gchar *key,
602 for (; length; length--, key++, token++)
604 char k = (*key == '_') ? '-' : tolower (*key );
605 char t = (*token == '_') ? '-' : tolower (*token);
615 * g_parse_debug_string:
616 * @string: a list of debug options separated by colons, spaces, or
618 * @keys: pointer to an array of #GDebugKey which associate
619 * strings with bit flags.
620 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
622 * Parses a string containing debugging options
623 * into a %guint containing bit flags. This is used
624 * within GDK and GTK+ to parse the debug options passed on the
625 * command line or through environment variables.
627 * If @string is equal to "all", all flags are set. If @string
628 * is equal to "help", all the available keys in @keys are printed
629 * out to standard error.
631 * Returns: the combined set of bit flags.
634 g_parse_debug_string (const gchar *string,
635 const GDebugKey *keys,
644 /* this function is used by gmem.c/gslice.c initialization code,
645 * so introducing malloc dependencies here would require adaptions
646 * of those code portions.
649 if (!g_ascii_strcasecmp (string, "all"))
651 for (i=0; i<nkeys; i++)
652 result |= keys[i].value;
654 else if (!g_ascii_strcasecmp (string, "help"))
656 /* using stdio directly for the reason stated above */
657 fprintf (stderr, "Supported debug values: ");
658 for (i=0; i<nkeys; i++)
659 fprintf (stderr, " %s", keys[i].key);
660 fprintf (stderr, "\n");
664 const gchar *p = string;
669 q = strpbrk (p, ":;, \t");
673 for (i = 0; i < nkeys; i++)
674 if (debug_key_matches (keys[i].key, p, q - p))
675 result |= keys[i].value;
688 * @file_name: the name of the file.
690 * Gets the name of the file without any leading directory components.
691 * It returns a pointer into the given file name string.
693 * Return value: the name of the file without any leading directory components.
695 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
696 * g_path_get_basename() allocates new memory for the returned string, unlike
697 * this function which returns a pointer into the argument.
699 G_CONST_RETURN gchar*
700 g_basename (const gchar *file_name)
702 register gchar *base;
704 g_return_val_if_fail (file_name != NULL, NULL);
706 base = strrchr (file_name, G_DIR_SEPARATOR);
710 gchar *q = strrchr (file_name, '/');
711 if (base == NULL || (q != NULL && q > base))
720 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
721 return (gchar*) file_name + 2;
722 #endif /* G_OS_WIN32 */
724 return (gchar*) file_name;
728 * g_path_get_basename:
729 * @file_name: the name of the file.
731 * Gets the last component of the filename. If @file_name ends with a
732 * directory separator it gets the component before the last slash. If
733 * @file_name consists only of directory separators (and on Windows,
734 * possibly a drive letter), a single separator is returned. If
735 * @file_name is empty, it gets ".".
737 * Return value: a newly allocated string containing the last component of
741 g_path_get_basename (const gchar *file_name)
743 register gssize base;
744 register gssize last_nonslash;
748 g_return_val_if_fail (file_name != NULL, NULL);
750 if (file_name[0] == '\0')
752 return g_strdup (".");
754 last_nonslash = strlen (file_name) - 1;
756 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
759 if (last_nonslash == -1)
760 /* string only containing slashes */
761 return g_strdup (G_DIR_SEPARATOR_S);
764 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
765 /* string only containing slashes and a drive */
766 return g_strdup (G_DIR_SEPARATOR_S);
767 #endif /* G_OS_WIN32 */
769 base = last_nonslash;
771 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
775 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
777 #endif /* G_OS_WIN32 */
779 len = last_nonslash - base;
780 retval = g_malloc (len + 1);
781 memcpy (retval, file_name + base + 1, len);
787 * g_path_is_absolute:
788 * @file_name: a file name.
790 * Returns %TRUE if the given @file_name is an absolute file name,
791 * i.e. it contains a full path from the root directory such as "/usr/local"
792 * on UNIX or "C:\windows" on Windows systems.
794 * Returns: %TRUE if @file_name is an absolute path.
797 g_path_is_absolute (const gchar *file_name)
799 g_return_val_if_fail (file_name != NULL, FALSE);
801 if (G_IS_DIR_SEPARATOR (file_name[0]))
805 /* Recognize drive letter on native Windows */
806 if (g_ascii_isalpha (file_name[0]) &&
807 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
809 #endif /* G_OS_WIN32 */
816 * @file_name: a file name.
818 * Returns a pointer into @file_name after the root component, i.e. after
819 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
820 * path it returns %NULL.
822 * Returns: a pointer into @file_name after the root component.
824 G_CONST_RETURN gchar*
825 g_path_skip_root (const gchar *file_name)
827 g_return_val_if_fail (file_name != NULL, NULL);
829 #ifdef G_PLATFORM_WIN32
830 /* Skip \\server\share or //server/share */
831 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
832 G_IS_DIR_SEPARATOR (file_name[1]) &&
834 !G_IS_DIR_SEPARATOR (file_name[2]))
838 p = strchr (file_name + 2, G_DIR_SEPARATOR);
841 gchar *q = strchr (file_name + 2, '/');
842 if (p == NULL || (q != NULL && q < p))
852 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
855 /* Possibly skip a backslash after the share name */
856 if (G_IS_DIR_SEPARATOR (file_name[0]))
859 return (gchar *)file_name;
864 /* Skip initial slashes */
865 if (G_IS_DIR_SEPARATOR (file_name[0]))
867 while (G_IS_DIR_SEPARATOR (file_name[0]))
869 return (gchar *)file_name;
874 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
875 return (gchar *)file_name + 3;
882 * g_path_get_dirname:
883 * @file_name: the name of the file.
885 * Gets the directory components of a file name. If the file name has no
886 * directory components "." is returned. The returned string should be
887 * freed when no longer needed.
889 * Returns: the directory components of the file.
892 g_path_get_dirname (const gchar *file_name)
894 register gchar *base;
897 g_return_val_if_fail (file_name != NULL, NULL);
899 base = strrchr (file_name, G_DIR_SEPARATOR);
902 gchar *q = strrchr (file_name, '/');
903 if (base == NULL || (q != NULL && q > base))
910 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
912 gchar drive_colon_dot[4];
914 drive_colon_dot[0] = file_name[0];
915 drive_colon_dot[1] = ':';
916 drive_colon_dot[2] = '.';
917 drive_colon_dot[3] = '\0';
919 return g_strdup (drive_colon_dot);
922 return g_strdup (".");
925 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
929 /* base points to the char before the last slash.
931 * In case file_name is the root of a drive (X:\) or a child of the
932 * root of a drive (X:\foo), include the slash.
934 * In case file_name is the root share of an UNC path
935 * (\\server\share), add a slash, returning \\server\share\ .
937 * In case file_name is a direct child of a share in an UNC path
938 * (\\server\share\foo), include the slash after the share name,
939 * returning \\server\share\ .
941 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
943 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
944 G_IS_DIR_SEPARATOR (file_name[1]) &&
946 !G_IS_DIR_SEPARATOR (file_name[2]) &&
947 base >= file_name + 2)
949 const gchar *p = file_name + 2;
950 while (*p && !G_IS_DIR_SEPARATOR (*p))
954 len = (guint) strlen (file_name) + 1;
955 base = g_new (gchar, len + 1);
956 strcpy (base, file_name);
957 base[len-1] = G_DIR_SEPARATOR;
961 if (G_IS_DIR_SEPARATOR (*p))
964 while (*p && !G_IS_DIR_SEPARATOR (*p))
972 len = (guint) 1 + base - file_name;
974 base = g_new (gchar, len + 1);
975 g_memmove (base, file_name, len);
984 * Gets the current directory.
985 * The returned string should be freed when no longer needed. The encoding
986 * of the returned string is system defined. On Windows, it is always UTF-8.
988 * Returns: the current directory.
991 g_get_current_dir (void)
996 wchar_t dummy[2], *wdir;
999 len = GetCurrentDirectoryW (2, dummy);
1000 wdir = g_new (wchar_t, len);
1002 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1003 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1008 dir = g_strdup ("\\");
1014 gchar *buffer = NULL;
1016 static gulong max_len = 0;
1019 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1021 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1022 * and, if that wasn't bad enough, hangs in doing so.
1024 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1025 buffer = g_new (gchar, max_len + 1);
1027 dir = getwd (buffer);
1028 #else /* !sun || !HAVE_GETCWD */
1029 while (max_len < G_MAXULONG / 2)
1032 buffer = g_new (gchar, max_len + 1);
1034 dir = getcwd (buffer, max_len);
1036 if (dir || errno != ERANGE)
1041 #endif /* !sun || !HAVE_GETCWD */
1043 if (!dir || !*buffer)
1045 /* hm, should we g_error() out here?
1046 * this can happen if e.g. "./" has mode \0000
1048 buffer[0] = G_DIR_SEPARATOR;
1052 dir = g_strdup (buffer);
1061 * @variable: the environment variable to get, in the GLib file name encoding.
1063 * Returns the value of an environment variable. The name and value
1064 * are in the GLib file name encoding. On UNIX, this means the actual
1065 * bytes which might or might not be in some consistent character set
1066 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1067 * environment variable's value contains references to other
1068 * environment variables, they are expanded.
1070 * Return value: the value of the environment variable, or %NULL if
1071 * the environment variable is not found. The returned string may be
1072 * overwritten by the next call to g_getenv(), g_setenv() or
1075 G_CONST_RETURN gchar*
1076 g_getenv (const gchar *variable)
1080 g_return_val_if_fail (variable != NULL, NULL);
1082 return getenv (variable);
1084 #else /* G_OS_WIN32 */
1088 wchar_t dummy[2], *wname, *wvalue;
1091 g_return_val_if_fail (variable != NULL, NULL);
1092 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1094 /* On Windows NT, it is relatively typical that environment
1095 * variables contain references to other environment variables. If
1096 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1097 * environment variables would be stored in the Registry as
1098 * REG_EXPAND_SZ type values, and would then get automatically
1099 * expanded before a program sees them. But there is broken software
1100 * that stores environment variables as REG_SZ values even if they
1101 * contain references to other environment variables.)
1104 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1106 len = GetEnvironmentVariableW (wname, dummy, 2);
1116 wvalue = g_new (wchar_t, len);
1118 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1125 if (wcschr (wvalue, L'%') != NULL)
1127 wchar_t *tem = wvalue;
1129 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1133 wvalue = g_new (wchar_t, len);
1135 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1145 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1150 quark = g_quark_from_string (value);
1153 return g_quark_to_string (quark);
1155 #endif /* G_OS_WIN32 */
1158 /* _g_getenv_nomalloc
1159 * this function does a getenv() without doing any kind of allocation
1160 * through glib. it's suitable for chars <= 127 only (both, for the
1161 * variable name and the contents) and for contents < 1024 chars in
1162 * length. also, it aliases "" to a NULL return value.
1165 _g_getenv_nomalloc (const gchar *variable,
1168 const gchar *retval = getenv (variable);
1169 if (retval && retval[0])
1171 gint l = strlen (retval);
1174 strncpy (buffer, retval, l);
1184 * @variable: the environment variable to set, must not contain '='.
1185 * @value: the value for to set the variable to.
1186 * @overwrite: whether to change the variable if it already exists.
1188 * Sets an environment variable. Both the variable's name and value
1189 * should be in the GLib file name encoding. On UNIX, this means that
1190 * they can be any sequence of bytes. On Windows, they should be in
1193 * Note that on some systems, when variables are overwritten, the memory
1194 * used for the previous variables and its value isn't reclaimed.
1196 * Returns: %FALSE if the environment variable couldn't be set.
1201 g_setenv (const gchar *variable,
1212 g_return_val_if_fail (variable != NULL, FALSE);
1213 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1216 result = setenv (variable, value, overwrite);
1218 if (!overwrite && getenv (variable) != NULL)
1221 /* This results in a leak when you overwrite existing
1222 * settings. It would be fairly easy to fix this by keeping
1223 * our own parallel array or hash table.
1225 string = g_strconcat (variable, "=", value, NULL);
1226 result = putenv (string);
1230 #else /* G_OS_WIN32 */
1233 wchar_t *wname, *wvalue, *wassignment;
1236 g_return_val_if_fail (variable != NULL, FALSE);
1237 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1238 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1239 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1241 if (!overwrite && g_getenv (variable) != NULL)
1244 /* We want to (if possible) set both the environment variable copy
1245 * kept by the C runtime and the one kept by the system.
1247 * We can't use only the C runtime's putenv or _wputenv() as that
1248 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1249 * (with main() and not wmain()). In a "main()" app the C runtime
1250 * initializes the C runtime's environment table by converting the
1251 * real (wide char) environment variables to system codepage, thus
1252 * breaking those that aren't representable in the system codepage.
1254 * As the C runtime's putenv() will also set the system copy, we do
1255 * the putenv() first, then call SetEnvironmentValueW ourselves.
1258 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1259 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1260 tem = g_strconcat (variable, "=", value, NULL);
1261 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1264 _wputenv (wassignment);
1265 g_free (wassignment);
1267 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1274 #endif /* G_OS_WIN32 */
1277 #ifdef HAVE__NSGETENVIRON
1278 #define environ (*_NSGetEnviron())
1279 #elif !defined(G_OS_WIN32)
1281 /* According to the Single Unix Specification, environ is not in
1282 * any system header, although unistd.h often declares it.
1284 extern char **environ;
1289 * @variable: the environment variable to remove, must not contain '='.
1291 * Removes an environment variable from the environment.
1293 * Note that on some systems, when variables are overwritten, the memory
1294 * used for the previous variables and its value isn't reclaimed.
1295 * Furthermore, this function can't be guaranteed to operate in a
1301 g_unsetenv (const gchar *variable)
1305 #ifdef HAVE_UNSETENV
1306 g_return_if_fail (variable != NULL);
1307 g_return_if_fail (strchr (variable, '=') == NULL);
1309 unsetenv (variable);
1310 #else /* !HAVE_UNSETENV */
1314 g_return_if_fail (variable != NULL);
1315 g_return_if_fail (strchr (variable, '=') == NULL);
1317 len = strlen (variable);
1319 /* Mess directly with the environ array.
1320 * This seems to be the only portable way to do this.
1322 * Note that we remove *all* environment entries for
1323 * the variable name, not just the first.
1328 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1336 #endif /* !HAVE_UNSETENV */
1338 #else /* G_OS_WIN32 */
1340 wchar_t *wname, *wassignment;
1343 g_return_if_fail (variable != NULL);
1344 g_return_if_fail (strchr (variable, '=') == NULL);
1345 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1347 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1348 tem = g_strconcat (variable, "=", NULL);
1349 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1352 _wputenv (wassignment);
1353 g_free (wassignment);
1355 SetEnvironmentVariableW (wname, NULL);
1359 #endif /* G_OS_WIN32 */
1365 * Gets the names of all variables set in the environment.
1367 * Returns: a %NULL-terminated list of strings which must be freed
1368 * with g_strfreev().
1370 * Programs that want to be portable to Windows should typically use
1371 * this function and g_getenv() instead of using the environ array
1372 * from the C library directly. On Windows, the strings in the environ
1373 * array are in system codepage encoding, while in most of the typical
1374 * use cases for environment variables in GLib-using programs you want
1375 * the UTF-8 encoding that this function and g_getenv() provide.
1383 gchar **result, *eq;
1386 len = g_strv_length (environ);
1387 result = g_new0 (gchar *, len + 1);
1390 for (i = 0; i < len; i++)
1392 eq = strchr (environ[i], '=');
1394 result[j++] = g_strndup (environ[i], eq - environ[i]);
1401 gchar **result, *eq;
1405 p = (wchar_t *) GetEnvironmentStringsW ();
1411 q += wcslen (q) + 1;
1415 result = g_new0 (gchar *, len + 1);
1421 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1422 if (result[j] != NULL)
1424 eq = strchr (result[j], '=');
1425 if (eq && eq > result[j])
1433 q += wcslen (q) + 1;
1436 FreeEnvironmentStringsW (p);
1442 G_LOCK_DEFINE_STATIC (g_utils_global);
1444 static gchar *g_tmp_dir = NULL;
1445 static gchar *g_user_name = NULL;
1446 static gchar *g_real_name = NULL;
1447 static gchar *g_home_dir = NULL;
1448 static gchar *g_host_name = NULL;
1451 /* System codepage versions of the above, kept at file level so that they,
1452 * too, are produced only once.
1454 static gchar *g_tmp_dir_cp = NULL;
1455 static gchar *g_user_name_cp = NULL;
1456 static gchar *g_real_name_cp = NULL;
1457 static gchar *g_home_dir_cp = NULL;
1460 static gchar *g_user_data_dir = NULL;
1461 static gchar **g_system_data_dirs = NULL;
1462 static gchar *g_user_cache_dir = NULL;
1463 static gchar *g_user_config_dir = NULL;
1464 static gchar **g_system_config_dirs = NULL;
1466 static gchar **g_user_special_dirs = NULL;
1468 /* fifteen minutes of fame for everybody */
1469 #define G_USER_DIRS_EXPIRE 15 * 60
1474 get_special_folder (int csidl)
1476 wchar_t path[MAX_PATH+1];
1478 LPITEMIDLIST pidl = NULL;
1480 gchar *retval = NULL;
1482 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1485 b = SHGetPathFromIDListW (pidl, path);
1487 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1488 CoTaskMemFree (pidl);
1494 get_windows_directory_root (void)
1496 wchar_t wwindowsdir[MAX_PATH];
1498 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1500 /* Usually X:\Windows, but in terminal server environments
1501 * might be an UNC path, AFAIK.
1503 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1506 if (windowsdir == NULL)
1507 return g_strdup ("C:\\");
1509 p = (char *) g_path_skip_root (windowsdir);
1510 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1516 return g_strdup ("C:\\");
1521 /* HOLDS: g_utils_global_lock */
1523 g_get_any_init_do (void)
1525 gchar hostname[100];
1527 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1528 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1529 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1530 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1531 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1534 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1535 g_tmp_dir = get_windows_directory_root ();
1538 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1541 g_tmp_dir = g_strdup (P_tmpdir);
1542 k = strlen (g_tmp_dir);
1543 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1544 g_tmp_dir[k - 1] = '\0';
1548 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1550 g_tmp_dir = g_strdup ("/tmp");
1552 #endif /* !G_OS_WIN32 */
1555 /* We check $HOME first for Win32, though it is a last resort for Unix
1556 * where we prefer the results of getpwuid().
1558 g_home_dir = g_strdup (g_getenv ("HOME"));
1560 /* Only believe HOME if it is an absolute path and exists */
1563 if (!(g_path_is_absolute (g_home_dir) &&
1564 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1566 g_free (g_home_dir);
1571 /* In case HOME is Unix-style (it happens), convert it to
1577 while ((p = strchr (g_home_dir, '/')) != NULL)
1583 /* USERPROFILE is probably the closest equivalent to $HOME? */
1584 if (g_getenv ("USERPROFILE") != NULL)
1585 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1589 g_home_dir = get_special_folder (CSIDL_PROFILE);
1592 g_home_dir = get_windows_directory_root ();
1593 #endif /* G_OS_WIN32 */
1597 struct passwd *pw = NULL;
1598 gpointer buffer = NULL;
1602 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1604 # ifdef _SC_GETPW_R_SIZE_MAX
1605 /* This reurns the maximum length */
1606 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1610 # else /* _SC_GETPW_R_SIZE_MAX */
1612 # endif /* _SC_GETPW_R_SIZE_MAX */
1614 logname = (gchar *) g_getenv ("LOGNAME");
1619 /* we allocate 6 extra bytes to work around a bug in
1620 * Mac OS < 10.3. See #156446
1622 buffer = g_malloc (bufsize + 6);
1625 # ifdef HAVE_POSIX_GETPWUID_R
1627 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1628 if (!pw || (pw->pw_uid != getuid ())) {
1629 /* LOGNAME is lying, fall back to looking up the uid */
1630 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1633 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1635 error = error < 0 ? errno : error;
1636 # else /* HAVE_NONPOSIX_GETPWUID_R */
1637 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1638 # if defined(_AIX) || defined(__hpux)
1639 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1640 pw = error == 0 ? &pwd : NULL;
1643 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1644 if (!pw || (pw->pw_uid != getuid ())) {
1645 /* LOGNAME is lying, fall back to looking up the uid */
1646 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1649 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1651 error = pw ? 0 : errno;
1653 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1657 /* we bail out prematurely if the user id can't be found
1658 * (should be pretty rare case actually), or if the buffer
1659 * should be sufficiently big and lookups are still not
1662 if (error == 0 || error == ENOENT)
1664 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1665 (gulong) getuid ());
1668 if (bufsize > 32 * 1024)
1670 g_warning ("getpwuid_r(): failed due to: %s.",
1671 g_strerror (error));
1679 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1684 pw = getpwuid (getuid ());
1689 g_user_name = g_strdup (pw->pw_name);
1691 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1693 gchar **gecos_fields;
1696 /* split the gecos field and substitute '&' */
1697 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1698 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1699 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1700 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1701 g_strfreev (gecos_fields);
1702 g_strfreev (name_parts);
1706 g_home_dir = g_strdup (pw->pw_dir);
1711 #else /* !HAVE_PWD_H */
1715 guint len = UNLEN+1;
1716 wchar_t buffer[UNLEN+1];
1718 if (GetUserNameW (buffer, (LPDWORD) &len))
1720 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1721 g_real_name = g_strdup (g_user_name);
1724 #endif /* G_OS_WIN32 */
1726 #endif /* !HAVE_PWD_H */
1730 g_home_dir = g_strdup (g_getenv ("HOME"));
1734 /* change '\\' in %HOME% to '/' */
1735 g_strdelimit (g_home_dir, "\\",'/');
1738 g_user_name = g_strdup ("somebody");
1740 g_real_name = g_strdup ("Unknown");
1744 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1746 DWORD size = sizeof (hostname);
1747 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1749 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1753 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1754 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1755 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1758 g_tmp_dir_cp = g_strdup ("\\");
1759 if (!g_user_name_cp)
1760 g_user_name_cp = g_strdup ("somebody");
1761 if (!g_real_name_cp)
1762 g_real_name_cp = g_strdup ("Unknown");
1764 /* home_dir might be NULL, unlike tmp_dir, user_name and
1768 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1770 g_home_dir_cp = NULL;
1771 #endif /* G_OS_WIN32 */
1775 g_get_any_init (void)
1778 g_get_any_init_do ();
1782 g_get_any_init_locked (void)
1784 G_LOCK (g_utils_global);
1786 G_UNLOCK (g_utils_global);
1793 * Gets the user name of the current user. The encoding of the returned
1794 * string is system-defined. On UNIX, it might be the preferred file name
1795 * encoding, or something else, and there is no guarantee that it is even
1796 * consistent on a machine. On Windows, it is always UTF-8.
1798 * Returns: the user name of the current user.
1800 G_CONST_RETURN gchar*
1801 g_get_user_name (void)
1803 g_get_any_init_locked ();
1810 * Gets the real name of the user. This usually comes from the user's entry
1811 * in the <filename>passwd</filename> file. The encoding of the returned
1812 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1813 * If the real user name cannot be determined, the string "Unknown" is
1816 * Returns: the user's real name.
1818 G_CONST_RETURN gchar*
1819 g_get_real_name (void)
1821 g_get_any_init_locked ();
1828 * Gets the current user's home directory as defined in the
1829 * password database.
1831 * Note that in contrast to traditional UNIX tools, this function
1832 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1833 * environment variable.
1835 * One of the reasons for this decision is that applications in many
1836 * cases need special handling to deal with the case where
1837 * <envar>HOME</envar> is
1839 * <member>Not owned by the user</member>
1840 * <member>Not writeable</member>
1841 * <member>Not even readable</member>
1843 * Since applications are in general <emphasis>not</emphasis> written
1844 * to deal with these situations it was considered better to make
1845 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1846 * return the real home directory for the user. If applications
1847 * want to pay attention to <envar>HOME</envar>, they can do:
1849 * const char *homedir = g_getenv ("HOME");
1851 * homedir = g_get_home_dir (<!-- -->);
1854 * Returns: the current user's home directory
1856 G_CONST_RETURN gchar*
1857 g_get_home_dir (void)
1859 g_get_any_init_locked ();
1866 * Gets the directory to use for temporary files. This is found from
1867 * inspecting the environment variables <envar>TMPDIR</envar>,
1868 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1869 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1870 * The encoding of the returned string is system-defined. On Windows,
1871 * it is always UTF-8. The return value is never %NULL or the empty string.
1873 * Returns: the directory to use for temporary files.
1875 G_CONST_RETURN gchar*
1876 g_get_tmp_dir (void)
1878 g_get_any_init_locked ();
1885 * Return a name for the machine.
1887 * The returned name is not necessarily a fully-qualified domain name,
1888 * or even present in DNS or some other name service at all. It need
1889 * not even be unique on your local network or site, but usually it
1890 * is. Callers should not rely on the return value having any specific
1891 * properties like uniqueness for security purposes. Even if the name
1892 * of the machine is changed while an application is running, the
1893 * return value from this function does not change. The returned
1894 * string is owned by GLib and should not be modified or freed. If no
1895 * name can be determined, a default fixed string "localhost" is
1898 * Returns: the host name of the machine.
1903 g_get_host_name (void)
1905 g_get_any_init_locked ();
1909 G_LOCK_DEFINE_STATIC (g_prgname);
1910 static gchar *g_prgname = NULL;
1915 * Gets the name of the program. This name should <emphasis>not</emphasis>
1916 * be localized, contrast with g_get_application_name().
1917 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1918 * which is called by gtk_init(). The program name is found by taking
1919 * the last component of <literal>argv[0]</literal>.)
1921 * Returns: the name of the program. The returned string belongs
1922 * to GLib and must not be modified or freed.
1925 g_get_prgname (void)
1931 if (g_prgname == NULL)
1933 static gboolean beenhere = FALSE;
1937 gchar *utf8_buf = NULL;
1938 wchar_t buf[MAX_PATH+1];
1941 if (GetModuleFileNameW (GetModuleHandle (NULL),
1942 buf, G_N_ELEMENTS (buf)) > 0)
1943 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1947 g_prgname = g_path_get_basename (utf8_buf);
1954 G_UNLOCK (g_prgname);
1961 * @prgname: the name of the program.
1963 * Sets the name of the program. This name should <emphasis>not</emphasis>
1964 * be localized, contrast with g_set_application_name(). Note that for
1965 * thread-safety reasons this function can only be called once.
1968 g_set_prgname (const gchar *prgname)
1972 g_prgname = g_strdup (prgname);
1973 G_UNLOCK (g_prgname);
1976 G_LOCK_DEFINE_STATIC (g_application_name);
1977 static gchar *g_application_name = NULL;
1980 * g_get_application_name:
1982 * Gets a human-readable name for the application, as set by
1983 * g_set_application_name(). This name should be localized if
1984 * possible, and is intended for display to the user. Contrast with
1985 * g_get_prgname(), which gets a non-localized name. If
1986 * g_set_application_name() has not been called, returns the result of
1987 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1990 * Return value: human-readable application name. may return %NULL
1994 G_CONST_RETURN gchar*
1995 g_get_application_name (void)
1999 G_LOCK (g_application_name);
2000 retval = g_application_name;
2001 G_UNLOCK (g_application_name);
2004 return g_get_prgname ();
2010 * g_set_application_name:
2011 * @application_name: localized name of the application
2013 * Sets a human-readable name for the application. This name should be
2014 * localized if possible, and is intended for display to the user.
2015 * Contrast with g_set_prgname(), which sets a non-localized name.
2016 * g_set_prgname() will be called automatically by gtk_init(),
2017 * but g_set_application_name() will not.
2019 * Note that for thread safety reasons, this function can only
2022 * The application name will be used in contexts such as error messages,
2023 * or when displaying an application's name in the task list.
2028 g_set_application_name (const gchar *application_name)
2030 gboolean already_set = FALSE;
2032 G_LOCK (g_application_name);
2033 if (g_application_name)
2036 g_application_name = g_strdup (application_name);
2037 G_UNLOCK (g_application_name);
2040 g_warning ("g_set_application_name() called multiple times");
2044 * g_get_user_data_dir:
2046 * Returns a base directory in which to access application data such
2047 * as icons that is customized for a particular user.
2049 * On UNIX platforms this is determined using the mechanisms described in
2050 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2051 * XDG Base Directory Specification</ulink>.
2052 * In this case the directory retrieved will be XDG_DATA_HOME.
2054 * On Windows is the virtual folder that represents the My Documents
2055 * desktop item. See documentation for CSIDL_PERSONAL.
2057 * Return value: a string owned by GLib that must not be modified
2061 G_CONST_RETURN gchar*
2062 g_get_user_data_dir (void)
2066 G_LOCK (g_utils_global);
2068 if (!g_user_data_dir)
2071 data_dir = get_special_folder (CSIDL_PERSONAL);
2073 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2075 if (data_dir && data_dir[0])
2076 data_dir = g_strdup (data_dir);
2078 if (!data_dir || !data_dir[0])
2083 data_dir = g_build_filename (g_home_dir, ".local",
2086 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2090 g_user_data_dir = data_dir;
2093 data_dir = g_user_data_dir;
2095 G_UNLOCK (g_utils_global);
2101 g_init_user_config_dir (void)
2105 if (!g_user_config_dir)
2108 config_dir = get_special_folder (CSIDL_APPDATA);
2110 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2112 if (config_dir && config_dir[0])
2113 config_dir = g_strdup (config_dir);
2115 if (!config_dir || !config_dir[0])
2120 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2122 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2125 g_user_config_dir = config_dir;
2130 * g_get_user_config_dir:
2132 * Returns a base directory in which to store user-specific application
2133 * configuration information such as user preferences and settings.
2135 * On UNIX platforms this is determined using the mechanisms described in
2136 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2137 * XDG Base Directory Specification</ulink>.
2138 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2140 * On Windows is the directory that serves as a common repository for
2141 * application-specific data. A typical path is
2142 * C:\Documents and Settings\username\Application. See documentation for
2145 * Return value: a string owned by GLib that must not be modified
2149 G_CONST_RETURN gchar*
2150 g_get_user_config_dir (void)
2152 G_LOCK (g_utils_global);
2154 g_init_user_config_dir ();
2156 G_UNLOCK (g_utils_global);
2158 return g_user_config_dir;
2162 * g_get_user_cache_dir:
2164 * Returns a base directory in which to store non-essential, cached
2165 * data specific to particular user.
2167 * On UNIX platforms this is determined using the mechanisms described in
2168 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2169 * XDG Base Directory Specification</ulink>.
2170 * In this case the directory retrieved will be XDG_CACHE_HOME.
2172 * On Windows is the directory that serves as a common repository for
2173 * temporary Internet files. A typical path is
2174 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2175 * See documentation for CSIDL_INTERNET_CACHE.
2177 * Return value: a string owned by GLib that must not be modified
2181 G_CONST_RETURN gchar*
2182 g_get_user_cache_dir (void)
2186 G_LOCK (g_utils_global);
2188 if (!g_user_cache_dir)
2191 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2193 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2195 if (cache_dir && cache_dir[0])
2196 cache_dir = g_strdup (cache_dir);
2198 if (!cache_dir || !cache_dir[0])
2203 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2205 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2207 g_user_cache_dir = cache_dir;
2210 cache_dir = g_user_cache_dir;
2212 G_UNLOCK (g_utils_global);
2220 find_folder (OSType type)
2222 gchar *filename = NULL;
2225 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2227 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2231 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2235 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2239 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2241 CFStringGetCString (path, filename,
2242 CFStringGetLength (path) * 3 + 1,
2243 kCFStringEncodingUTF8);
2257 load_user_special_dirs (void)
2259 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2260 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2261 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2262 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2263 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2264 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2265 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2266 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2269 #endif /* HAVE_CARBON */
2271 #if defined(G_OS_WIN32)
2273 load_user_special_dirs (void)
2275 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2279 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2280 static const GUID FOLDERID_Downloads =
2281 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2282 static const GUID FOLDERID_Public =
2283 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2286 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (LoadLibrary ("shell32.dll"),
2287 "SHGetKnownFolderPath");
2289 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2290 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2292 if (p_SHGetKnownFolderPath == NULL)
2294 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2299 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2300 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2301 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2302 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2303 CoTaskMemFree (wcp);
2306 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2307 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2309 if (p_SHGetKnownFolderPath == NULL)
2312 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2317 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2318 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2319 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2320 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2321 CoTaskMemFree (wcp);
2324 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2325 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2327 #endif /* G_OS_WIN32 */
2329 static void g_init_user_config_dir (void);
2331 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2333 /* adapted from xdg-user-dir-lookup.c
2335 * Copyright (C) 2007 Red Hat Inc.
2337 * Permission is hereby granted, free of charge, to any person
2338 * obtaining a copy of this software and associated documentation files
2339 * (the "Software"), to deal in the Software without restriction,
2340 * including without limitation the rights to use, copy, modify, merge,
2341 * publish, distribute, sublicense, and/or sell copies of the Software,
2342 * and to permit persons to whom the Software is furnished to do so,
2343 * subject to the following conditions:
2345 * The above copyright notice and this permission notice shall be
2346 * included in all copies or substantial portions of the Software.
2348 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2349 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2350 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2351 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2352 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2353 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2354 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2358 load_user_special_dirs (void)
2365 g_init_user_config_dir ();
2366 config_file = g_build_filename (g_user_config_dir,
2370 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2372 g_free (config_file);
2376 lines = g_strsplit (data, "\n", -1);
2377 n_lines = g_strv_length (lines);
2380 for (i = 0; i < n_lines; i++)
2382 gchar *buffer = lines[i];
2385 gboolean is_relative = FALSE;
2386 GUserDirectory directory;
2388 /* Remove newline at end */
2389 len = strlen (buffer);
2390 if (len > 0 && buffer[len - 1] == '\n')
2391 buffer[len - 1] = 0;
2394 while (*p == ' ' || *p == '\t')
2397 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2399 directory = G_USER_DIRECTORY_DESKTOP;
2400 p += strlen ("XDG_DESKTOP_DIR");
2402 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2404 directory = G_USER_DIRECTORY_DOCUMENTS;
2405 p += strlen ("XDG_DOCUMENTS_DIR");
2407 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2409 directory = G_USER_DIRECTORY_DOWNLOAD;
2410 p += strlen ("XDG_DOWNLOAD_DIR");
2412 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2414 directory = G_USER_DIRECTORY_MUSIC;
2415 p += strlen ("XDG_MUSIC_DIR");
2417 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2419 directory = G_USER_DIRECTORY_PICTURES;
2420 p += strlen ("XDG_PICTURES_DIR");
2422 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2424 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2425 p += strlen ("XDG_PUBLICSHARE_DIR");
2427 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2429 directory = G_USER_DIRECTORY_TEMPLATES;
2430 p += strlen ("XDG_TEMPLATES_DIR");
2432 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2434 directory = G_USER_DIRECTORY_VIDEOS;
2435 p += strlen ("XDG_VIDEOS_DIR");
2440 while (*p == ' ' || *p == '\t')
2447 while (*p == ' ' || *p == '\t')
2454 if (strncmp (p, "$HOME", 5) == 0)
2462 d = strrchr (p, '"');
2469 /* remove trailing slashes */
2471 if (d[len - 1] == '/')
2477 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2480 g_user_special_dirs[directory] = g_strdup (d);
2484 g_free (config_file);
2487 #endif /* G_OS_UNIX && !HAVE_CARBON */
2491 * g_reload_user_special_dirs_cache:
2493 * Resets the cache used for g_get_user_special_dir(), so
2494 * that the latest on-disk version is used. Call this only
2495 * if you just changed the data on disk yourself.
2497 * Due to threadsafety issues this may cause leaking of strings
2498 * that were previously returned from g_get_user_special_dir()
2499 * that can't be freed. We ensure to only leak the data for
2500 * the directories that actually changed value though.
2505 g_reload_user_special_dirs_cache (void)
2509 G_LOCK (g_utils_global);
2511 if (g_user_special_dirs != NULL)
2513 /* save a copy of the pointer, to check if some memory can be preserved */
2514 char **old_g_user_special_dirs = g_user_special_dirs;
2517 /* recreate and reload our cache */
2518 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2519 load_user_special_dirs ();
2521 /* only leak changed directories */
2522 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2524 old_val = old_g_user_special_dirs[i];
2525 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2528 g_free (g_user_special_dirs[i]);
2529 g_user_special_dirs[i] = old_val;
2535 /* free the old array */
2536 g_free (old_g_user_special_dirs);
2539 G_UNLOCK (g_utils_global);
2543 * g_get_user_special_dir:
2544 * @directory: the logical id of special directory
2546 * Returns the full path of a special directory using its logical id.
2548 * On Unix this is done using the XDG special user directories.
2549 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2550 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2551 * user directories have not been set up.
2553 * Depending on the platform, the user might be able to change the path
2554 * of the special directory without requiring the session to restart; GLib
2555 * will not reflect any change once the special directories are loaded.
2557 * Return value: the path to the specified special directory, or %NULL
2558 * if the logical id was not found. The returned string is owned by
2559 * GLib and should not be modified or freed.
2563 G_CONST_RETURN gchar *
2564 g_get_user_special_dir (GUserDirectory directory)
2566 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2567 directory < G_USER_N_DIRECTORIES, NULL);
2569 G_LOCK (g_utils_global);
2571 if (G_UNLIKELY (g_user_special_dirs == NULL))
2573 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2575 load_user_special_dirs ();
2577 /* Special-case desktop for historical compatibility */
2578 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2582 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2583 g_build_filename (g_home_dir, "Desktop", NULL);
2587 G_UNLOCK (g_utils_global);
2589 return g_user_special_dirs[directory];
2594 #undef g_get_system_data_dirs
2597 get_module_for_address (gconstpointer address)
2599 /* Holds the g_utils_global lock */
2601 static gboolean beenhere = FALSE;
2602 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2603 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2604 HMODULE hmodule = NULL;
2611 p_GetModuleHandleExA =
2612 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2613 "GetModuleHandleExA");
2617 if (p_GetModuleHandleExA == NULL ||
2618 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2619 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2622 MEMORY_BASIC_INFORMATION mbi;
2623 VirtualQuery (address, &mbi, sizeof (mbi));
2624 hmodule = (HMODULE) mbi.AllocationBase;
2631 get_module_share_dir (gconstpointer address)
2637 hmodule = get_module_for_address (address);
2638 if (hmodule == NULL)
2641 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2642 retval = g_build_filename (filename, "share", NULL);
2648 G_CONST_RETURN gchar * G_CONST_RETURN *
2649 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2653 static GHashTable *per_module_data_dirs = NULL;
2658 if (address_of_function)
2660 G_LOCK (g_utils_global);
2661 hmodule = get_module_for_address (address_of_function);
2662 if (hmodule != NULL)
2664 if (per_module_data_dirs == NULL)
2665 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2668 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2672 G_UNLOCK (g_utils_global);
2673 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2679 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2681 /* Documents and Settings\All Users\Application Data */
2682 p = get_special_folder (CSIDL_COMMON_APPDATA);
2684 g_array_append_val (data_dirs, p);
2686 /* Documents and Settings\All Users\Documents */
2687 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2689 g_array_append_val (data_dirs, p);
2691 /* Using the above subfolders of Documents and Settings perhaps
2692 * makes sense from a Windows perspective.
2694 * But looking at the actual use cases of this function in GTK+
2695 * and GNOME software, what we really want is the "share"
2696 * subdirectory of the installation directory for the package
2697 * our caller is a part of.
2699 * The address_of_function parameter, if non-NULL, points to a
2700 * function in the calling module. Use that to determine that
2701 * module's installation folder, and use its "share" subfolder.
2703 * Additionally, also use the "share" subfolder of the installation
2704 * locations of GLib and the .exe file being run.
2706 * To guard against none of the above being what is really wanted,
2707 * callers of this function should have Win32-specific code to look
2708 * up their installation folder themselves, and handle a subfolder
2709 * "share" of it in the same way as the folders returned from this
2713 p = get_module_share_dir (address_of_function);
2715 g_array_append_val (data_dirs, p);
2717 if (glib_dll != NULL)
2719 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2720 p = g_build_filename (glib_root, "share", NULL);
2722 g_array_append_val (data_dirs, p);
2726 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2727 p = g_build_filename (exe_root, "share", NULL);
2729 g_array_append_val (data_dirs, p);
2732 retval = (gchar **) g_array_free (data_dirs, FALSE);
2734 if (address_of_function)
2736 if (hmodule != NULL)
2737 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2738 G_UNLOCK (g_utils_global);
2741 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2747 * g_get_system_data_dirs:
2749 * Returns an ordered list of base directories in which to access
2750 * system-wide application data.
2752 * On UNIX platforms this is determined using the mechanisms described in
2753 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2754 * XDG Base Directory Specification</ulink>
2755 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2757 * On Windows the first elements in the list are the Application Data
2758 * and Documents folders for All Users. (These can be determined only
2759 * on Windows 2000 or later and are not present in the list on other
2760 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2761 * CSIDL_COMMON_DOCUMENTS.
2763 * Then follows the "share" subfolder in the installation folder for
2764 * the package containing the DLL that calls this function, if it can
2767 * Finally the list contains the "share" subfolder in the installation
2768 * folder for GLib, and in the installation folder for the package the
2769 * application's .exe file belongs to.
2771 * The installation folders above are determined by looking up the
2772 * folder where the module (DLL or EXE) in question is located. If the
2773 * folder's name is "bin", its parent is used, otherwise the folder
2776 * Note that on Windows the returned list can vary depending on where
2777 * this function is called.
2779 * Return value: a %NULL-terminated array of strings owned by GLib that must
2780 * not be modified or freed.
2783 G_CONST_RETURN gchar * G_CONST_RETURN *
2784 g_get_system_data_dirs (void)
2786 gchar **data_dir_vector;
2788 G_LOCK (g_utils_global);
2790 if (!g_system_data_dirs)
2793 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2795 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2797 if (!data_dirs || !data_dirs[0])
2798 data_dirs = "/usr/local/share/:/usr/share/";
2800 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2803 g_system_data_dirs = data_dir_vector;
2806 data_dir_vector = g_system_data_dirs;
2808 G_UNLOCK (g_utils_global);
2810 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2814 * g_get_system_config_dirs:
2816 * Returns an ordered list of base directories in which to access
2817 * system-wide configuration information.
2819 * On UNIX platforms this is determined using the mechanisms described in
2820 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2821 * XDG Base Directory Specification</ulink>.
2822 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2824 * On Windows is the directory that contains application data for all users.
2825 * A typical path is C:\Documents and Settings\All Users\Application Data.
2826 * This folder is used for application data that is not user specific.
2827 * For example, an application can store a spell-check dictionary, a database
2828 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2829 * This information will not roam and is available to anyone using the computer.
2831 * Return value: a %NULL-terminated array of strings owned by GLib that must
2832 * not be modified or freed.
2835 G_CONST_RETURN gchar * G_CONST_RETURN *
2836 g_get_system_config_dirs (void)
2838 gchar *conf_dirs, **conf_dir_vector;
2840 G_LOCK (g_utils_global);
2842 if (!g_system_config_dirs)
2845 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2848 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2853 /* Return empty list */
2854 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2857 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2859 if (!conf_dirs || !conf_dirs[0])
2860 conf_dirs = "/etc/xdg";
2862 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2865 g_system_config_dirs = conf_dir_vector;
2868 conf_dir_vector = g_system_config_dirs;
2869 G_UNLOCK (g_utils_global);
2871 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2876 static GHashTable *alias_table = NULL;
2878 /* read an alias file for the locales */
2880 read_aliases (gchar *file)
2886 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2887 fp = fopen (file,"r");
2890 while (fgets (buf, 256, fp))
2896 /* Line is a comment */
2897 if ((buf[0] == '#') || (buf[0] == '\0'))
2900 /* Reads first column */
2901 for (p = buf, q = NULL; *p; p++) {
2902 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2905 while ((*q == '\t') || (*q == ' ')) {
2911 /* The line only had one column */
2912 if (!q || *q == '\0')
2915 /* Read second column */
2916 for (p = q; *p; p++) {
2917 if ((*p == '\t') || (*p == ' ')) {
2923 /* Add to alias table if necessary */
2924 if (!g_hash_table_lookup (alias_table, buf)) {
2925 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2934 unalias_lang (char *lang)
2941 read_aliases ("/usr/share/locale/locale.alias");
2944 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2949 static gboolean said_before = FALSE;
2951 g_warning ("Too many alias levels for a locale, "
2952 "may indicate a loop");
2961 /* Mask for components of locale spec. The ordering here is from
2962 * least significant to most significant
2966 COMPONENT_CODESET = 1 << 0,
2967 COMPONENT_TERRITORY = 1 << 1,
2968 COMPONENT_MODIFIER = 1 << 2
2971 /* Break an X/Open style locale specification into components
2974 explode_locale (const gchar *locale,
2980 const gchar *uscore_pos;
2981 const gchar *at_pos;
2982 const gchar *dot_pos;
2986 uscore_pos = strchr (locale, '_');
2987 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2988 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2992 mask |= COMPONENT_MODIFIER;
2993 *modifier = g_strdup (at_pos);
2996 at_pos = locale + strlen (locale);
3000 mask |= COMPONENT_CODESET;
3001 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3008 mask |= COMPONENT_TERRITORY;
3009 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3012 uscore_pos = dot_pos;
3014 *language = g_strndup (locale, uscore_pos - locale);
3020 * Compute all interesting variants for a given locale name -
3021 * by stripping off different components of the value.
3023 * For simplicity, we assume that the locale is in
3024 * X/Open format: language[_territory][.codeset][@modifier]
3026 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3027 * as well. We could just copy the code from glibc wholesale
3028 * but it is big, ugly, and complicated, so I'm reluctant
3029 * to do so when this should handle 99% of the time...
3032 _g_compute_locale_variants (const gchar *locale)
3034 GSList *retval = NULL;
3036 gchar *language = NULL;
3037 gchar *territory = NULL;
3038 gchar *codeset = NULL;
3039 gchar *modifier = NULL;
3044 g_return_val_if_fail (locale != NULL, NULL);
3046 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3048 /* Iterate through all possible combinations, from least attractive
3049 * to most attractive.
3051 for (i = 0; i <= mask; i++)
3052 if ((i & ~mask) == 0)
3054 gchar *val = g_strconcat (language,
3055 (i & COMPONENT_TERRITORY) ? territory : "",
3056 (i & COMPONENT_CODESET) ? codeset : "",
3057 (i & COMPONENT_MODIFIER) ? modifier : "",
3059 retval = g_slist_prepend (retval, val);
3063 if (mask & COMPONENT_CODESET)
3065 if (mask & COMPONENT_TERRITORY)
3067 if (mask & COMPONENT_MODIFIER)
3073 /* The following is (partly) taken from the gettext package.
3074 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3076 static const gchar *
3077 guess_category_value (const gchar *category_name)
3079 const gchar *retval;
3081 /* The highest priority value is the `LANGUAGE' environment
3082 variable. This is a GNU extension. */
3083 retval = g_getenv ("LANGUAGE");
3084 if ((retval != NULL) && (retval[0] != '\0'))
3087 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3088 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3089 systems this can be done by the `setlocale' function itself. */
3091 /* Setting of LC_ALL overwrites all other. */
3092 retval = g_getenv ("LC_ALL");
3093 if ((retval != NULL) && (retval[0] != '\0'))
3096 /* Next comes the name of the desired category. */
3097 retval = g_getenv (category_name);
3098 if ((retval != NULL) && (retval[0] != '\0'))
3101 /* Last possibility is the LANG environment variable. */
3102 retval = g_getenv ("LANG");
3103 if ((retval != NULL) && (retval[0] != '\0'))
3106 #ifdef G_PLATFORM_WIN32
3107 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3108 * LANG, which we already did above. Oh well. The main point of
3109 * calling g_win32_getlocale() is to get the thread's locale as used
3110 * by Windows and the Microsoft C runtime (in the "English_United
3111 * States" format) translated into the Unixish format.
3114 char *locale = g_win32_getlocale ();
3115 retval = g_intern_string (locale);
3124 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3126 struct _GLanguageNamesCache {
3128 gchar **language_names;
3132 language_names_cache_free (gpointer data)
3134 GLanguageNamesCache *cache = data;
3135 g_free (cache->languages);
3136 g_strfreev (cache->language_names);
3141 * g_get_language_names:
3143 * Computes a list of applicable locale names, which can be used to
3144 * e.g. construct locale-dependent filenames or search paths. The returned
3145 * list is sorted from most desirable to least desirable and always contains
3146 * the default locale "C".
3148 * For example, if LANGUAGE=de:en_US, then the returned list is
3149 * "de", "en_US", "en", "C".
3151 * This function consults the environment variables <envar>LANGUAGE</envar>,
3152 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3153 * to find the list of locales specified by the user.
3155 * Return value: a %NULL-terminated array of strings owned by GLib
3156 * that must not be modified or freed.
3160 G_CONST_RETURN gchar * G_CONST_RETURN *
3161 g_get_language_names (void)
3163 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3164 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3169 cache = g_new0 (GLanguageNamesCache, 1);
3170 g_static_private_set (&cache_private, cache, language_names_cache_free);
3173 value = guess_category_value ("LC_MESSAGES");
3177 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3184 g_free (cache->languages);
3185 g_strfreev (cache->language_names);
3186 cache->languages = g_strdup (value);
3188 alist = g_strsplit (value, ":", 0);
3190 for (a = alist; *a; a++)
3192 gchar *b = unalias_lang (*a);
3193 list = g_slist_concat (list, _g_compute_locale_variants (b));
3196 list = g_slist_append (list, g_strdup ("C"));
3198 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3199 for (l = list, i = 0; l; l = l->next, i++)
3200 languages[i] = l->data;
3201 languages[i] = NULL;
3203 g_slist_free (list);
3206 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3211 * @v: a #gpointer key
3213 * Converts a gpointer to a hash value.
3214 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3215 * when using pointers as keys in a #GHashTable.
3217 * Returns: a hash value corresponding to the key.
3220 g_direct_hash (gconstpointer v)
3222 return GPOINTER_TO_UINT (v);
3228 * @v2: a key to compare with @v1.
3230 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3231 * It can be passed to g_hash_table_new() as the @key_equal_func
3232 * parameter, when using pointers as keys in a #GHashTable.
3234 * Returns: %TRUE if the two keys match.
3237 g_direct_equal (gconstpointer v1,
3245 * @v1: a pointer to a #gint key.
3246 * @v2: a pointer to a #gint key to compare with @v1.
3248 * Compares the two #gint values being pointed to and returns
3249 * %TRUE if they are equal.
3250 * It can be passed to g_hash_table_new() as the @key_equal_func
3251 * parameter, when using pointers to integers as keys in a #GHashTable.
3253 * Returns: %TRUE if the two keys match.
3256 g_int_equal (gconstpointer v1,
3259 return *((const gint*) v1) == *((const gint*) v2);
3264 * @v: a pointer to a #gint key
3266 * Converts a pointer to a #gint to a hash value.
3267 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3268 * when using pointers to integers values as keys in a #GHashTable.
3270 * Returns: a hash value corresponding to the key.
3273 g_int_hash (gconstpointer v)
3275 return *(const gint*) v;
3280 * @v1: a pointer to a #gint64 key.
3281 * @v2: a pointer to a #gint64 key to compare with @v1.
3283 * Compares the two #gint64 values being pointed to and returns
3284 * %TRUE if they are equal.
3285 * It can be passed to g_hash_table_new() as the @key_equal_func
3286 * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3288 * Returns: %TRUE if the two keys match.
3293 g_int64_equal (gconstpointer v1,
3296 return *((const gint64*) v1) == *((const gint64*) v2);
3301 * @v: a pointer to a #gint64 key
3303 * Converts a pointer to a #gint64 to a hash value.
3304 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3305 * when using pointers to 64-bit integers values as keys in a #GHashTable.
3307 * Returns: a hash value corresponding to the key.
3312 g_int64_hash (gconstpointer v)
3314 return (guint) *(const gint64*) v;
3319 * @v1: a pointer to a #gdouble key.
3320 * @v2: a pointer to a #gdouble key to compare with @v1.
3322 * Compares the two #gdouble values being pointed to and returns
3323 * %TRUE if they are equal.
3324 * It can be passed to g_hash_table_new() as the @key_equal_func
3325 * parameter, when using pointers to doubles as keys in a #GHashTable.
3327 * Returns: %TRUE if the two keys match.
3332 g_double_equal (gconstpointer v1,
3335 return *((const gdouble*) v1) == *((const gdouble*) v2);
3340 * @v: a pointer to a #gdouble key
3342 * Converts a pointer to a #gdouble to a hash value.
3343 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3344 * when using pointers to doubles as keys in a #GHashTable.
3346 * Returns: a hash value corresponding to the key.
3351 g_double_hash (gconstpointer v)
3353 return (guint) *(const gdouble*) v;
3357 * g_nullify_pointer:
3358 * @nullify_location: the memory address of the pointer.
3360 * Set the pointer at the specified location to %NULL.
3363 g_nullify_pointer (gpointer *nullify_location)
3365 g_return_if_fail (nullify_location != NULL);
3367 *nullify_location = NULL;
3373 * Get the codeset for the current locale.
3375 * Return value: a newly allocated string containing the name
3376 * of the codeset. This string must be freed with g_free().
3379 g_get_codeset (void)
3381 const gchar *charset;
3383 g_get_charset (&charset);
3385 return g_strdup (charset);
3388 /* This is called from g_thread_init(). It's used to
3389 * initialize some static data in a threadsafe way.
3392 _g_utils_thread_init (void)
3394 g_get_language_names ();
3400 * _glib_get_locale_dir:
3402 * Return the path to the share\locale or lib\locale subfolder of the
3403 * GLib installation folder. The path is in the system codepage. We
3404 * have to use system codepage as bindtextdomain() doesn't have a
3408 _glib_get_locale_dir (void)
3410 gchar *install_dir = NULL, *locale_dir;
3411 gchar *retval = NULL;
3413 if (glib_dll != NULL)
3414 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3419 * Append "/share/locale" or "/lib/locale" depending on whether
3420 * autoconfigury detected GNU gettext or not.
3422 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3428 locale_dir = g_build_filename (install_dir, p, NULL);
3430 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3432 g_free (install_dir);
3433 g_free (locale_dir);
3439 return g_strdup ("");
3442 #undef GLIB_LOCALE_DIR
3444 #endif /* G_OS_WIN32 */
3448 * @str: The string to be translated
3450 * Returns the translated string from the glib translations.
3451 * This is an internal function and should only be used by
3452 * the internals of glib (such as libgio).
3454 * Returns: the transation of @str to the current locale
3456 G_CONST_RETURN gchar *
3457 glib_gettext (const gchar *str)
3459 static gboolean _glib_gettext_initialized = FALSE;
3461 if (!_glib_gettext_initialized)
3464 gchar *tmp = _glib_get_locale_dir ();
3465 bindtextdomain (GETTEXT_PACKAGE, tmp);
3468 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3470 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3471 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3473 _glib_gettext_initialized = TRUE;
3476 return g_dgettext (GETTEXT_PACKAGE, str);
3479 #if defined (G_OS_WIN32) && !defined (_WIN64)
3481 /* Binary compatibility versions. Not for newly compiled code. */
3483 #undef g_find_program_in_path
3486 g_find_program_in_path (const gchar *program)
3488 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3489 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3492 g_free (utf8_program);
3493 if (utf8_retval == NULL)
3495 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3496 g_free (utf8_retval);
3501 #undef g_get_current_dir
3504 g_get_current_dir (void)
3506 gchar *utf8_dir = g_get_current_dir_utf8 ();
3507 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3514 G_CONST_RETURN gchar*
3515 g_getenv (const gchar *variable)
3517 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3518 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3522 g_free (utf8_variable);
3525 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3526 quark = g_quark_from_string (value);
3529 return g_quark_to_string (quark);
3535 g_setenv (const gchar *variable,
3539 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3540 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3541 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3543 g_free (utf8_variable);
3544 g_free (utf8_value);
3552 g_unsetenv (const gchar *variable)
3554 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3556 g_unsetenv_utf8 (utf8_variable);
3558 g_free (utf8_variable);
3561 #undef g_get_user_name
3563 G_CONST_RETURN gchar*
3564 g_get_user_name (void)
3566 g_get_any_init_locked ();
3567 return g_user_name_cp;
3570 #undef g_get_real_name
3572 G_CONST_RETURN gchar*
3573 g_get_real_name (void)
3575 g_get_any_init_locked ();
3576 return g_real_name_cp;
3579 #undef g_get_home_dir
3581 G_CONST_RETURN gchar*
3582 g_get_home_dir (void)
3584 g_get_any_init_locked ();
3585 return g_home_dir_cp;
3588 #undef g_get_tmp_dir
3590 G_CONST_RETURN gchar*
3591 g_get_tmp_dir (void)
3593 g_get_any_init_locked ();
3594 return g_tmp_dir_cp;