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 #ifdef G_PLATFORM_WIN32
81 #define G_PATH_LENGTH MAXPATHLEN
82 #elif defined (PATH_MAX)
83 #define G_PATH_LENGTH PATH_MAX
84 #elif defined (_PC_PATH_MAX)
85 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
87 #define G_PATH_LENGTH 2048
90 #ifdef G_PLATFORM_WIN32
91 # define STRICT /* Strict typing, please */
94 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
95 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
96 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
98 # include <lmcons.h> /* For UNLEN */
99 #endif /* G_PLATFORM_WIN32 */
104 /* older SDK (e.g. msvc 5.0) does not have these*/
105 # ifndef CSIDL_MYMUSIC
106 # define CSIDL_MYMUSIC 13
108 # ifndef CSIDL_MYVIDEO
109 # define CSIDL_MYVIDEO 14
111 # ifndef CSIDL_INTERNET_CACHE
112 # define CSIDL_INTERNET_CACHE 32
114 # ifndef CSIDL_COMMON_APPDATA
115 # define CSIDL_COMMON_APPDATA 35
117 # ifndef CSIDL_MYPICTURES
118 # define CSIDL_MYPICTURES 0x27
120 # ifndef CSIDL_COMMON_DOCUMENTS
121 # define CSIDL_COMMON_DOCUMENTS 46
123 # ifndef CSIDL_PROFILE
124 # define CSIDL_PROFILE 40
126 # include <process.h>
130 #include <CoreServices/CoreServices.h>
134 #include <langinfo.h>
137 const guint glib_major_version = GLIB_MAJOR_VERSION;
138 const guint glib_minor_version = GLIB_MINOR_VERSION;
139 const guint glib_micro_version = GLIB_MICRO_VERSION;
140 const guint glib_interface_age = GLIB_INTERFACE_AGE;
141 const guint glib_binary_age = GLIB_BINARY_AGE;
143 #ifdef G_PLATFORM_WIN32
145 static HMODULE glib_dll = NULL;
150 DllMain (HINSTANCE hinstDLL,
154 if (fdwReason == DLL_PROCESS_ATTACH)
163 _glib_get_dll_directory (void)
167 wchar_t wc_fn[MAX_PATH];
170 if (glib_dll == NULL)
174 /* This code is different from that in
175 * g_win32_get_package_installation_directory_of_module() in that
176 * here we return the actual folder where the GLib DLL is. We don't
177 * do the check for it being in a "bin" or "lib" subfolder and then
178 * returning the parent of that.
180 * In a statically built GLib, glib_dll will be NULL and we will
181 * thus look up the application's .exe file's location.
183 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
186 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
188 p = strrchr (retval, G_DIR_SEPARATOR);
202 * glib_check_version:
203 * @required_major: the required major version.
204 * @required_minor: the required minor version.
205 * @required_micro: the required micro version.
207 * Checks that the GLib library in use is compatible with the
208 * given version. Generally you would pass in the constants
209 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
210 * as the three arguments to this function; that produces
211 * a check that the library in use is compatible with
212 * the version of GLib the application or module was compiled
215 * Compatibility is defined by two things: first the version
216 * of the running library is newer than the version
217 * @required_major.required_minor.@required_micro. Second
218 * the running library must be binary compatible with the
219 * version @required_major.required_minor.@required_micro
220 * (same major version.)
222 * Return value: %NULL if the GLib library is compatible with the
223 * given version, or a string describing the version mismatch.
224 * The returned string is owned by GLib and must not be modified
230 glib_check_version (guint required_major,
231 guint required_minor,
232 guint required_micro)
234 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
235 gint required_effective_micro = 100 * required_minor + required_micro;
237 if (required_major > GLIB_MAJOR_VERSION)
238 return "GLib version too old (major mismatch)";
239 if (required_major < GLIB_MAJOR_VERSION)
240 return "GLib version too new (major mismatch)";
241 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
242 return "GLib version too new (micro mismatch)";
243 if (required_effective_micro > glib_effective_micro)
244 return "GLib version too old (micro mismatch)";
248 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
251 * @dest: the destination address to copy the bytes to.
252 * @src: the source address to copy the bytes from.
253 * @len: the number of bytes to copy.
255 * Copies a block of memory @len bytes long, from @src to @dest.
256 * The source and destination areas may overlap.
258 * In order to use this function, you must include
259 * <filename>string.h</filename> yourself, because this macro will
260 * typically simply resolve to memmove() and GLib does not include
261 * <filename>string.h</filename> for you.
264 g_memmove (gpointer dest,
268 gchar* destptr = dest;
269 const gchar* srcptr = src;
270 if (src + len < dest || dest + len < src)
272 bcopy (src, dest, len);
275 else if (dest <= src)
278 *(destptr++) = *(srcptr++);
285 *(--destptr) = *(--srcptr);
288 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
296 * @func: the function to call on normal program termination.
298 * Specifies a function to be called at normal program termination.
300 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
301 * macro that maps to a call to the atexit() function in the C
302 * library. This means that in case the code that calls g_atexit(),
303 * i.e. atexit(), is in a DLL, the function will be called when the
304 * DLL is detached from the program. This typically makes more sense
305 * than that the function is called when the GLib DLL is detached,
306 * which happened earlier when g_atexit() was a function in the GLib
309 * The behaviour of atexit() in the context of dynamically loaded
310 * modules is not formally specified and varies wildly.
312 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
313 * loaded module which is unloaded before the program terminates might
314 * well cause a crash at program exit.
316 * Some POSIX systems implement atexit() like Windows, and have each
317 * dynamically loaded module maintain an own atexit chain that is
318 * called when the module is unloaded.
320 * On other POSIX systems, before a dynamically loaded module is
321 * unloaded, the registered atexit functions (if any) residing in that
322 * module are called, regardless where the code that registered them
323 * resided. This is presumably the most robust approach.
325 * As can be seen from the above, for portability it's best to avoid
326 * calling g_atexit() (or atexit()) except in the main executable of a
330 g_atexit (GVoidFunc func)
333 const gchar *error = NULL;
335 /* keep this in sync with glib.h */
337 #ifdef G_NATIVE_ATEXIT
338 result = ATEXIT (func);
340 error = g_strerror (errno);
341 #elif defined (HAVE_ATEXIT)
342 # ifdef NeXT /* @#%@! NeXTStep */
343 result = !atexit ((void (*)(void)) func);
345 error = g_strerror (errno);
347 result = atexit ((void (*)(void)) func);
349 error = g_strerror (errno);
351 #elif defined (HAVE_ON_EXIT)
352 result = on_exit ((void (*)(int, void *)) func, NULL);
354 error = g_strerror (errno);
357 error = "no implementation";
358 #endif /* G_NATIVE_ATEXIT */
361 g_error ("Could not register atexit() function: %s", error);
364 /* Based on execvp() from GNU Libc.
365 * Some of this code is cut-and-pasted into gspawn.c
369 my_strchrnul (const gchar *str,
372 gchar *p = (gchar*)str;
373 while (*p && (*p != c))
381 static gchar *inner_find_program_in_path (const gchar *program);
384 g_find_program_in_path (const gchar *program)
386 const gchar *last_dot = strrchr (program, '.');
388 if (last_dot == NULL ||
389 strchr (last_dot, '\\') != NULL ||
390 strchr (last_dot, '/') != NULL)
392 const gint program_length = strlen (program);
393 gchar *pathext = g_build_path (";",
394 ".exe;.cmd;.bat;.com",
395 g_getenv ("PATHEXT"),
398 gchar *decorated_program;
404 gchar *q = my_strchrnul (p, ';');
406 decorated_program = g_malloc (program_length + (q-p) + 1);
407 memcpy (decorated_program, program, program_length);
408 memcpy (decorated_program+program_length, p, q-p);
409 decorated_program [program_length + (q-p)] = '\0';
411 retval = inner_find_program_in_path (decorated_program);
412 g_free (decorated_program);
420 } while (*p++ != '\0');
425 return inner_find_program_in_path (program);
431 * g_find_program_in_path:
432 * @program: a program name in the GLib file name encoding
434 * Locates the first executable named @program in the user's path, in the
435 * same way that execvp() would locate it. Returns an allocated string
436 * with the absolute path name, or %NULL if the program is not found in
437 * the path. If @program is already an absolute path, returns a copy of
438 * @program if @program exists and is executable, and %NULL otherwise.
440 * On Windows, if @program does not have a file type suffix, tries
441 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
442 * the <envar>PATHEXT</envar> environment variable.
444 * On Windows, it looks for the file in the same way as CreateProcess()
445 * would. This means first in the directory where the executing
446 * program was loaded from, then in the current directory, then in the
447 * Windows 32-bit system directory, then in the Windows directory, and
448 * finally in the directories in the <envar>PATH</envar> environment
449 * variable. If the program is found, the return value contains the
450 * full name including the type suffix.
452 * Return value: absolute path, or %NULL
456 inner_find_program_in_path (const gchar *program)
459 g_find_program_in_path (const gchar *program)
462 const gchar *path, *p;
463 gchar *name, *freeme;
465 const gchar *path_copy;
466 gchar *filename = NULL, *appdir = NULL;
467 gchar *sysdir = NULL, *windir = NULL;
469 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
475 g_return_val_if_fail (program != NULL, NULL);
477 /* If it is an absolute path, or a relative path including subdirectories,
478 * don't look in PATH.
480 if (g_path_is_absolute (program)
481 || strchr (program, G_DIR_SEPARATOR) != NULL
483 || strchr (program, '/') != NULL
487 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
488 !g_file_test (program, G_FILE_TEST_IS_DIR))
489 return g_strdup (program);
494 path = g_getenv ("PATH");
495 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
498 /* There is no `PATH' in the environment. The default
499 * search path in GNU libc is the current directory followed by
500 * the path `confstr' returns for `_CS_PATH'.
503 /* In GLib we put . last, for security, and don't use the
504 * unportable confstr(); UNIX98 does not actually specify
505 * what to search if PATH is unset. POSIX may, dunno.
508 path = "/bin:/usr/bin:.";
511 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
512 if (n > 0 && n < MAXPATHLEN)
513 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
515 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
516 if (n > 0 && n < MAXPATHLEN)
517 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
519 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
520 if (n > 0 && n < MAXPATHLEN)
521 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
525 appdir = g_path_get_dirname (filename);
529 path = g_strdup (path);
533 const gchar *tem = path;
534 path = g_strconcat (windir, ";", path, NULL);
535 g_free ((gchar *) tem);
541 const gchar *tem = path;
542 path = g_strconcat (sysdir, ";", path, NULL);
543 g_free ((gchar *) tem);
548 const gchar *tem = path;
549 path = g_strconcat (".;", path, NULL);
550 g_free ((gchar *) tem);
555 const gchar *tem = path;
556 path = g_strconcat (appdir, ";", path, NULL);
557 g_free ((gchar *) tem);
564 len = strlen (program) + 1;
565 pathlen = strlen (path);
566 freeme = name = g_malloc (pathlen + len + 1);
568 /* Copy the file name at the top, including '\0' */
569 memcpy (name + pathlen + 1, program, len);
570 name = name + pathlen;
571 /* And add the slash before the filename */
572 *name = G_DIR_SEPARATOR;
580 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
583 /* Two adjacent colons, or a colon at the beginning or the end
584 * of `PATH' means to search the current directory.
588 startp = memcpy (name - (p - path), path, p - path);
590 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
591 !g_file_test (startp, G_FILE_TEST_IS_DIR))
594 ret = g_strdup (startp);
597 g_free ((gchar *) path_copy);
602 while (*p++ != '\0');
606 g_free ((gchar *) path_copy);
613 debug_key_matches (const gchar *key,
617 for (; length; length--, key++, token++)
619 char k = (*key == '_') ? '-' : tolower (*key );
620 char t = (*token == '_') ? '-' : tolower (*token);
630 * g_parse_debug_string:
631 * @string: a list of debug options separated by colons, spaces, or
633 * @keys: pointer to an array of #GDebugKey which associate
634 * strings with bit flags.
635 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
637 * Parses a string containing debugging options
638 * into a %guint containing bit flags. This is used
639 * within GDK and GTK+ to parse the debug options passed on the
640 * command line or through environment variables.
642 * If @string is equal to "all", all flags are set. If @string
643 * is equal to "help", all the available keys in @keys are printed
644 * out to standard error.
646 * Returns: the combined set of bit flags.
649 g_parse_debug_string (const gchar *string,
650 const GDebugKey *keys,
659 /* this function is used by gmem.c/gslice.c initialization code,
660 * so introducing malloc dependencies here would require adaptions
661 * of those code portions.
664 if (!g_ascii_strcasecmp (string, "all"))
666 for (i=0; i<nkeys; i++)
667 result |= keys[i].value;
669 else if (!g_ascii_strcasecmp (string, "help"))
671 /* using stdio directly for the reason stated above */
672 fprintf (stderr, "Supported debug values: ");
673 for (i=0; i<nkeys; i++)
674 fprintf (stderr, " %s", keys[i].key);
675 fprintf (stderr, "\n");
679 const gchar *p = string;
684 q = strpbrk (p, ":;, \t");
688 for (i = 0; i < nkeys; i++)
689 if (debug_key_matches (keys[i].key, p, q - p))
690 result |= keys[i].value;
703 * @file_name: the name of the file.
705 * Gets the name of the file without any leading directory components.
706 * It returns a pointer into the given file name string.
708 * Return value: the name of the file without any leading directory components.
710 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
711 * g_path_get_basename() allocates new memory for the returned string, unlike
712 * this function which returns a pointer into the argument.
714 G_CONST_RETURN gchar*
715 g_basename (const gchar *file_name)
717 register gchar *base;
719 g_return_val_if_fail (file_name != NULL, NULL);
721 base = strrchr (file_name, G_DIR_SEPARATOR);
725 gchar *q = strrchr (file_name, '/');
726 if (base == NULL || (q != NULL && q > base))
735 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
736 return (gchar*) file_name + 2;
737 #endif /* G_OS_WIN32 */
739 return (gchar*) file_name;
743 * g_path_get_basename:
744 * @file_name: the name of the file.
746 * Gets the last component of the filename. If @file_name ends with a
747 * directory separator it gets the component before the last slash. If
748 * @file_name consists only of directory separators (and on Windows,
749 * possibly a drive letter), a single separator is returned. If
750 * @file_name is empty, it gets ".".
752 * Return value: a newly allocated string containing the last component of
756 g_path_get_basename (const gchar *file_name)
758 register gssize base;
759 register gssize last_nonslash;
763 g_return_val_if_fail (file_name != NULL, NULL);
765 if (file_name[0] == '\0')
767 return g_strdup (".");
769 last_nonslash = strlen (file_name) - 1;
771 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
774 if (last_nonslash == -1)
775 /* string only containing slashes */
776 return g_strdup (G_DIR_SEPARATOR_S);
779 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
780 /* string only containing slashes and a drive */
781 return g_strdup (G_DIR_SEPARATOR_S);
782 #endif /* G_OS_WIN32 */
784 base = last_nonslash;
786 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
790 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
792 #endif /* G_OS_WIN32 */
794 len = last_nonslash - base;
795 retval = g_malloc (len + 1);
796 memcpy (retval, file_name + base + 1, len);
802 * g_path_is_absolute:
803 * @file_name: a file name.
805 * Returns %TRUE if the given @file_name is an absolute file name.
806 * Note that this is a somewhat vague concept on Windows.
808 * On POSIX systems, an absolute file name is well-defined. It always
809 * starts from the single root directory. For example "/usr/local".
811 * On Windows, the concepts of current drive and drive-specific
812 * current directory introduce vagueness. This function interprets as
813 * an absolute file name one that either begins with a directory
814 * separator such as "\Users\tml" or begins with the root on a drive,
815 * for example "C:\Windows". The first case also includes UNC paths
816 * such as "\\myserver\docs\foo". In all cases, either slashes or
817 * backslashes are accepted.
819 * Note that a file name relative to the current drive root does not
820 * truly specify a file uniquely over time and across processes, as
821 * the current drive is a per-process value and can be changed.
823 * File names relative the current directory on some specific drive,
824 * such as "D:foo/bar", are not interpreted as absolute by this
825 * function, but they obviously are not relative to the normal current
826 * directory as returned by getcwd() or g_get_current_dir()
827 * either. Such paths should be avoided, or need to be handled using
828 * Windows-specific code.
830 * Returns: %TRUE if @file_name is absolute.
833 g_path_is_absolute (const gchar *file_name)
835 g_return_val_if_fail (file_name != NULL, FALSE);
837 if (G_IS_DIR_SEPARATOR (file_name[0]))
841 /* Recognize drive letter on native Windows */
842 if (g_ascii_isalpha (file_name[0]) &&
843 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
845 #endif /* G_OS_WIN32 */
852 * @file_name: a file name.
854 * Returns a pointer into @file_name after the root component, i.e. after
855 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
856 * path it returns %NULL.
858 * Returns: a pointer into @file_name after the root component.
860 G_CONST_RETURN gchar*
861 g_path_skip_root (const gchar *file_name)
863 g_return_val_if_fail (file_name != NULL, NULL);
865 #ifdef G_PLATFORM_WIN32
866 /* Skip \\server\share or //server/share */
867 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
868 G_IS_DIR_SEPARATOR (file_name[1]) &&
870 !G_IS_DIR_SEPARATOR (file_name[2]))
874 p = strchr (file_name + 2, G_DIR_SEPARATOR);
877 gchar *q = strchr (file_name + 2, '/');
878 if (p == NULL || (q != NULL && q < p))
888 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
891 /* Possibly skip a backslash after the share name */
892 if (G_IS_DIR_SEPARATOR (file_name[0]))
895 return (gchar *)file_name;
900 /* Skip initial slashes */
901 if (G_IS_DIR_SEPARATOR (file_name[0]))
903 while (G_IS_DIR_SEPARATOR (file_name[0]))
905 return (gchar *)file_name;
910 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
911 return (gchar *)file_name + 3;
918 * g_path_get_dirname:
919 * @file_name: the name of the file.
921 * Gets the directory components of a file name. If the file name has no
922 * directory components "." is returned. The returned string should be
923 * freed when no longer needed.
925 * Returns: the directory components of the file.
928 g_path_get_dirname (const gchar *file_name)
930 register gchar *base;
933 g_return_val_if_fail (file_name != NULL, NULL);
935 base = strrchr (file_name, G_DIR_SEPARATOR);
938 gchar *q = strrchr (file_name, '/');
939 if (base == NULL || (q != NULL && q > base))
946 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
948 gchar drive_colon_dot[4];
950 drive_colon_dot[0] = file_name[0];
951 drive_colon_dot[1] = ':';
952 drive_colon_dot[2] = '.';
953 drive_colon_dot[3] = '\0';
955 return g_strdup (drive_colon_dot);
958 return g_strdup (".");
961 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
965 /* base points to the char before the last slash.
967 * In case file_name is the root of a drive (X:\) or a child of the
968 * root of a drive (X:\foo), include the slash.
970 * In case file_name is the root share of an UNC path
971 * (\\server\share), add a slash, returning \\server\share\ .
973 * In case file_name is a direct child of a share in an UNC path
974 * (\\server\share\foo), include the slash after the share name,
975 * returning \\server\share\ .
977 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
979 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
980 G_IS_DIR_SEPARATOR (file_name[1]) &&
982 !G_IS_DIR_SEPARATOR (file_name[2]) &&
983 base >= file_name + 2)
985 const gchar *p = file_name + 2;
986 while (*p && !G_IS_DIR_SEPARATOR (*p))
990 len = (guint) strlen (file_name) + 1;
991 base = g_new (gchar, len + 1);
992 strcpy (base, file_name);
993 base[len-1] = G_DIR_SEPARATOR;
997 if (G_IS_DIR_SEPARATOR (*p))
1000 while (*p && !G_IS_DIR_SEPARATOR (*p))
1008 len = (guint) 1 + base - file_name;
1010 base = g_new (gchar, len + 1);
1011 g_memmove (base, file_name, len);
1018 * g_get_current_dir:
1020 * Gets the current directory.
1021 * The returned string should be freed when no longer needed. The encoding
1022 * of the returned string is system defined. On Windows, it is always UTF-8.
1024 * Returns: the current directory.
1027 g_get_current_dir (void)
1032 wchar_t dummy[2], *wdir;
1035 len = GetCurrentDirectoryW (2, dummy);
1036 wdir = g_new (wchar_t, len);
1038 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1039 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1044 dir = g_strdup ("\\");
1050 gchar *buffer = NULL;
1052 static gulong max_len = 0;
1055 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1057 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1058 * and, if that wasn't bad enough, hangs in doing so.
1060 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1061 buffer = g_new (gchar, max_len + 1);
1063 dir = getwd (buffer);
1064 #else /* !sun || !HAVE_GETCWD */
1065 while (max_len < G_MAXULONG / 2)
1068 buffer = g_new (gchar, max_len + 1);
1070 dir = getcwd (buffer, max_len);
1072 if (dir || errno != ERANGE)
1077 #endif /* !sun || !HAVE_GETCWD */
1079 if (!dir || !*buffer)
1081 /* hm, should we g_error() out here?
1082 * this can happen if e.g. "./" has mode \0000
1084 buffer[0] = G_DIR_SEPARATOR;
1088 dir = g_strdup (buffer);
1097 * @variable: the environment variable to get, in the GLib file name encoding.
1099 * Returns the value of an environment variable. The name and value
1100 * are in the GLib file name encoding. On UNIX, this means the actual
1101 * bytes which might or might not be in some consistent character set
1102 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1103 * environment variable's value contains references to other
1104 * environment variables, they are expanded.
1106 * Return value: the value of the environment variable, or %NULL if
1107 * the environment variable is not found. The returned string may be
1108 * overwritten by the next call to g_getenv(), g_setenv() or
1111 G_CONST_RETURN gchar*
1112 g_getenv (const gchar *variable)
1116 g_return_val_if_fail (variable != NULL, NULL);
1118 return getenv (variable);
1120 #else /* G_OS_WIN32 */
1124 wchar_t dummy[2], *wname, *wvalue;
1127 g_return_val_if_fail (variable != NULL, NULL);
1128 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1130 /* On Windows NT, it is relatively typical that environment
1131 * variables contain references to other environment variables. If
1132 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1133 * environment variables would be stored in the Registry as
1134 * REG_EXPAND_SZ type values, and would then get automatically
1135 * expanded before a program sees them. But there is broken software
1136 * that stores environment variables as REG_SZ values even if they
1137 * contain references to other environment variables.)
1140 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1142 len = GetEnvironmentVariableW (wname, dummy, 2);
1152 wvalue = g_new (wchar_t, len);
1154 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1161 if (wcschr (wvalue, L'%') != NULL)
1163 wchar_t *tem = wvalue;
1165 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1169 wvalue = g_new (wchar_t, len);
1171 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1181 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1186 quark = g_quark_from_string (value);
1189 return g_quark_to_string (quark);
1191 #endif /* G_OS_WIN32 */
1194 /* _g_getenv_nomalloc
1195 * this function does a getenv() without doing any kind of allocation
1196 * through glib. it's suitable for chars <= 127 only (both, for the
1197 * variable name and the contents) and for contents < 1024 chars in
1198 * length. also, it aliases "" to a NULL return value.
1201 _g_getenv_nomalloc (const gchar *variable,
1204 const gchar *retval = getenv (variable);
1205 if (retval && retval[0])
1207 gint l = strlen (retval);
1210 strncpy (buffer, retval, l);
1220 * @variable: the environment variable to set, must not contain '='.
1221 * @value: the value for to set the variable to.
1222 * @overwrite: whether to change the variable if it already exists.
1224 * Sets an environment variable. Both the variable's name and value
1225 * should be in the GLib file name encoding. On UNIX, this means that
1226 * they can be any sequence of bytes. On Windows, they should be in
1229 * Note that on some systems, when variables are overwritten, the memory
1230 * used for the previous variables and its value isn't reclaimed.
1232 * Returns: %FALSE if the environment variable couldn't be set.
1237 g_setenv (const gchar *variable,
1248 g_return_val_if_fail (variable != NULL, FALSE);
1249 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1252 result = setenv (variable, value, overwrite);
1254 if (!overwrite && getenv (variable) != NULL)
1257 /* This results in a leak when you overwrite existing
1258 * settings. It would be fairly easy to fix this by keeping
1259 * our own parallel array or hash table.
1261 string = g_strconcat (variable, "=", value, NULL);
1262 result = putenv (string);
1266 #else /* G_OS_WIN32 */
1269 wchar_t *wname, *wvalue, *wassignment;
1272 g_return_val_if_fail (variable != NULL, FALSE);
1273 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1274 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1275 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1277 if (!overwrite && g_getenv (variable) != NULL)
1280 /* We want to (if possible) set both the environment variable copy
1281 * kept by the C runtime and the one kept by the system.
1283 * We can't use only the C runtime's putenv or _wputenv() as that
1284 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1285 * (with main() and not wmain()). In a "main()" app the C runtime
1286 * initializes the C runtime's environment table by converting the
1287 * real (wide char) environment variables to system codepage, thus
1288 * breaking those that aren't representable in the system codepage.
1290 * As the C runtime's putenv() will also set the system copy, we do
1291 * the putenv() first, then call SetEnvironmentValueW ourselves.
1294 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1295 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1296 tem = g_strconcat (variable, "=", value, NULL);
1297 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1300 _wputenv (wassignment);
1301 g_free (wassignment);
1303 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1310 #endif /* G_OS_WIN32 */
1313 #ifdef HAVE__NSGETENVIRON
1314 #define environ (*_NSGetEnviron())
1315 #elif !defined(G_OS_WIN32)
1317 /* According to the Single Unix Specification, environ is not in
1318 * any system header, although unistd.h often declares it.
1320 extern char **environ;
1325 * @variable: the environment variable to remove, must not contain '='.
1327 * Removes an environment variable from the environment.
1329 * Note that on some systems, when variables are overwritten, the memory
1330 * used for the previous variables and its value isn't reclaimed.
1331 * Furthermore, this function can't be guaranteed to operate in a
1337 g_unsetenv (const gchar *variable)
1341 #ifdef HAVE_UNSETENV
1342 g_return_if_fail (variable != NULL);
1343 g_return_if_fail (strchr (variable, '=') == NULL);
1345 unsetenv (variable);
1346 #else /* !HAVE_UNSETENV */
1350 g_return_if_fail (variable != NULL);
1351 g_return_if_fail (strchr (variable, '=') == NULL);
1353 len = strlen (variable);
1355 /* Mess directly with the environ array.
1356 * This seems to be the only portable way to do this.
1358 * Note that we remove *all* environment entries for
1359 * the variable name, not just the first.
1364 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1372 #endif /* !HAVE_UNSETENV */
1374 #else /* G_OS_WIN32 */
1376 wchar_t *wname, *wassignment;
1379 g_return_if_fail (variable != NULL);
1380 g_return_if_fail (strchr (variable, '=') == NULL);
1381 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1383 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1384 tem = g_strconcat (variable, "=", NULL);
1385 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1388 _wputenv (wassignment);
1389 g_free (wassignment);
1391 SetEnvironmentVariableW (wname, NULL);
1395 #endif /* G_OS_WIN32 */
1401 * Gets the names of all variables set in the environment.
1403 * Returns: a %NULL-terminated list of strings which must be freed
1404 * with g_strfreev().
1406 * Programs that want to be portable to Windows should typically use
1407 * this function and g_getenv() instead of using the environ array
1408 * from the C library directly. On Windows, the strings in the environ
1409 * array are in system codepage encoding, while in most of the typical
1410 * use cases for environment variables in GLib-using programs you want
1411 * the UTF-8 encoding that this function and g_getenv() provide.
1419 gchar **result, *eq;
1422 len = g_strv_length (environ);
1423 result = g_new0 (gchar *, len + 1);
1426 for (i = 0; i < len; i++)
1428 eq = strchr (environ[i], '=');
1430 result[j++] = g_strndup (environ[i], eq - environ[i]);
1437 gchar **result, *eq;
1441 p = (wchar_t *) GetEnvironmentStringsW ();
1447 q += wcslen (q) + 1;
1451 result = g_new0 (gchar *, len + 1);
1457 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1458 if (result[j] != NULL)
1460 eq = strchr (result[j], '=');
1461 if (eq && eq > result[j])
1469 q += wcslen (q) + 1;
1472 FreeEnvironmentStringsW (p);
1481 * Gets the list of environment variables for the current process. The
1482 * list is %NULL terminated and each item in the list is of the form
1485 * This is equivalent to direct access to the 'environ' global variable,
1488 * The return value is freshly allocated and it should be freed with
1489 * g_strfreev() when it is no longer needed.
1491 * Returns: the list of environment variables
1496 g_get_environ (void)
1499 return g_strdupv (environ);
1505 strings = GetEnvironmentStringsW ();
1506 for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1507 result = g_new (char *, n + 1);
1508 for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1509 result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1510 FreeEnvironmentStringsW (strings);
1517 G_LOCK_DEFINE_STATIC (g_utils_global);
1519 static gchar *g_tmp_dir = NULL;
1520 static gchar *g_user_name = NULL;
1521 static gchar *g_real_name = NULL;
1522 static gchar *g_home_dir = NULL;
1523 static gchar *g_host_name = NULL;
1526 /* System codepage versions of the above, kept at file level so that they,
1527 * too, are produced only once.
1529 static gchar *g_tmp_dir_cp = NULL;
1530 static gchar *g_user_name_cp = NULL;
1531 static gchar *g_real_name_cp = NULL;
1532 static gchar *g_home_dir_cp = NULL;
1535 static gchar *g_user_data_dir = NULL;
1536 static gchar **g_system_data_dirs = NULL;
1537 static gchar *g_user_cache_dir = NULL;
1538 static gchar *g_user_config_dir = NULL;
1539 static gchar **g_system_config_dirs = NULL;
1541 static gchar **g_user_special_dirs = NULL;
1543 /* fifteen minutes of fame for everybody */
1544 #define G_USER_DIRS_EXPIRE 15 * 60
1549 get_special_folder (int csidl)
1551 wchar_t path[MAX_PATH+1];
1553 LPITEMIDLIST pidl = NULL;
1555 gchar *retval = NULL;
1557 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1560 b = SHGetPathFromIDListW (pidl, path);
1562 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1563 CoTaskMemFree (pidl);
1569 get_windows_directory_root (void)
1571 wchar_t wwindowsdir[MAX_PATH];
1573 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1575 /* Usually X:\Windows, but in terminal server environments
1576 * might be an UNC path, AFAIK.
1578 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1581 if (windowsdir == NULL)
1582 return g_strdup ("C:\\");
1584 p = (char *) g_path_skip_root (windowsdir);
1585 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1591 return g_strdup ("C:\\");
1596 /* HOLDS: g_utils_global_lock */
1598 g_get_any_init_do (void)
1600 gchar hostname[100];
1602 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1603 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1604 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1605 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1606 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1609 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1610 g_tmp_dir = get_windows_directory_root ();
1613 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1616 g_tmp_dir = g_strdup (P_tmpdir);
1617 k = strlen (g_tmp_dir);
1618 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1619 g_tmp_dir[k - 1] = '\0';
1623 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1625 g_tmp_dir = g_strdup ("/tmp");
1627 #endif /* !G_OS_WIN32 */
1630 /* We check $HOME first for Win32, though it is a last resort for Unix
1631 * where we prefer the results of getpwuid().
1633 g_home_dir = g_strdup (g_getenv ("HOME"));
1635 /* Only believe HOME if it is an absolute path and exists */
1638 if (!(g_path_is_absolute (g_home_dir) &&
1639 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1641 g_free (g_home_dir);
1646 /* In case HOME is Unix-style (it happens), convert it to
1652 while ((p = strchr (g_home_dir, '/')) != NULL)
1658 /* USERPROFILE is probably the closest equivalent to $HOME? */
1659 if (g_getenv ("USERPROFILE") != NULL)
1660 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1664 g_home_dir = get_special_folder (CSIDL_PROFILE);
1667 g_home_dir = get_windows_directory_root ();
1668 #endif /* G_OS_WIN32 */
1672 struct passwd *pw = NULL;
1673 gpointer buffer = NULL;
1677 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1679 # ifdef _SC_GETPW_R_SIZE_MAX
1680 /* This reurns the maximum length */
1681 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1685 # else /* _SC_GETPW_R_SIZE_MAX */
1687 # endif /* _SC_GETPW_R_SIZE_MAX */
1689 logname = (gchar *) g_getenv ("LOGNAME");
1694 /* we allocate 6 extra bytes to work around a bug in
1695 * Mac OS < 10.3. See #156446
1697 buffer = g_malloc (bufsize + 6);
1700 # ifdef HAVE_POSIX_GETPWUID_R
1702 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1703 if (!pw || (pw->pw_uid != getuid ())) {
1704 /* LOGNAME is lying, fall back to looking up the uid */
1705 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1708 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1710 error = error < 0 ? errno : error;
1711 # else /* HAVE_NONPOSIX_GETPWUID_R */
1712 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1713 # if defined(_AIX) || defined(__hpux)
1714 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1715 pw = error == 0 ? &pwd : NULL;
1718 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1719 if (!pw || (pw->pw_uid != getuid ())) {
1720 /* LOGNAME is lying, fall back to looking up the uid */
1721 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1724 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1726 error = pw ? 0 : errno;
1728 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1732 /* we bail out prematurely if the user id can't be found
1733 * (should be pretty rare case actually), or if the buffer
1734 * should be sufficiently big and lookups are still not
1737 if (error == 0 || error == ENOENT)
1739 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1740 (gulong) getuid ());
1743 if (bufsize > 32 * 1024)
1745 g_warning ("getpwuid_r(): failed due to: %s.",
1746 g_strerror (error));
1754 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1759 pw = getpwuid (getuid ());
1764 g_user_name = g_strdup (pw->pw_name);
1766 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1768 gchar **gecos_fields;
1771 /* split the gecos field and substitute '&' */
1772 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1773 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1774 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1775 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1776 g_strfreev (gecos_fields);
1777 g_strfreev (name_parts);
1781 g_home_dir = g_strdup (pw->pw_dir);
1786 #else /* !HAVE_PWD_H */
1790 guint len = UNLEN+1;
1791 wchar_t buffer[UNLEN+1];
1793 if (GetUserNameW (buffer, (LPDWORD) &len))
1795 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1796 g_real_name = g_strdup (g_user_name);
1799 #endif /* G_OS_WIN32 */
1801 #endif /* !HAVE_PWD_H */
1805 g_home_dir = g_strdup (g_getenv ("HOME"));
1809 /* change '\\' in %HOME% to '/' */
1810 g_strdelimit (g_home_dir, "\\",'/');
1813 g_user_name = g_strdup ("somebody");
1815 g_real_name = g_strdup ("Unknown");
1819 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1821 DWORD size = sizeof (hostname);
1822 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1824 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1828 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1829 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1830 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1833 g_tmp_dir_cp = g_strdup ("\\");
1834 if (!g_user_name_cp)
1835 g_user_name_cp = g_strdup ("somebody");
1836 if (!g_real_name_cp)
1837 g_real_name_cp = g_strdup ("Unknown");
1839 /* home_dir might be NULL, unlike tmp_dir, user_name and
1843 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1845 g_home_dir_cp = NULL;
1846 #endif /* G_OS_WIN32 */
1850 g_get_any_init (void)
1853 g_get_any_init_do ();
1857 g_get_any_init_locked (void)
1859 G_LOCK (g_utils_global);
1861 G_UNLOCK (g_utils_global);
1868 * Gets the user name of the current user. The encoding of the returned
1869 * string is system-defined. On UNIX, it might be the preferred file name
1870 * encoding, or something else, and there is no guarantee that it is even
1871 * consistent on a machine. On Windows, it is always UTF-8.
1873 * Returns: the user name of the current user.
1875 G_CONST_RETURN gchar*
1876 g_get_user_name (void)
1878 g_get_any_init_locked ();
1885 * Gets the real name of the user. This usually comes from the user's entry
1886 * in the <filename>passwd</filename> file. The encoding of the returned
1887 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1888 * If the real user name cannot be determined, the string "Unknown" is
1891 * Returns: the user's real name.
1893 G_CONST_RETURN gchar*
1894 g_get_real_name (void)
1896 g_get_any_init_locked ();
1903 * Gets the current user's home directory as defined in the
1904 * password database.
1906 * Note that in contrast to traditional UNIX tools, this function
1907 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1908 * environment variable.
1910 * One of the reasons for this decision is that applications in many
1911 * cases need special handling to deal with the case where
1912 * <envar>HOME</envar> is
1914 * <member>Not owned by the user</member>
1915 * <member>Not writeable</member>
1916 * <member>Not even readable</member>
1918 * Since applications are in general <emphasis>not</emphasis> written
1919 * to deal with these situations it was considered better to make
1920 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1921 * return the real home directory for the user. If applications
1922 * want to pay attention to <envar>HOME</envar>, they can do:
1924 * const char *homedir = g_getenv ("HOME");
1926 * homedir = g_get_home_dir (<!-- -->);
1929 * Returns: the current user's home directory
1931 G_CONST_RETURN gchar*
1932 g_get_home_dir (void)
1934 g_get_any_init_locked ();
1941 * Gets the directory to use for temporary files. This is found from
1942 * inspecting the environment variables <envar>TMPDIR</envar>,
1943 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1944 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1945 * The encoding of the returned string is system-defined. On Windows,
1946 * it is always UTF-8. The return value is never %NULL or the empty string.
1948 * Returns: the directory to use for temporary files.
1950 G_CONST_RETURN gchar*
1951 g_get_tmp_dir (void)
1953 g_get_any_init_locked ();
1960 * Return a name for the machine.
1962 * The returned name is not necessarily a fully-qualified domain name,
1963 * or even present in DNS or some other name service at all. It need
1964 * not even be unique on your local network or site, but usually it
1965 * is. Callers should not rely on the return value having any specific
1966 * properties like uniqueness for security purposes. Even if the name
1967 * of the machine is changed while an application is running, the
1968 * return value from this function does not change. The returned
1969 * string is owned by GLib and should not be modified or freed. If no
1970 * name can be determined, a default fixed string "localhost" is
1973 * Returns: the host name of the machine.
1978 g_get_host_name (void)
1980 g_get_any_init_locked ();
1984 G_LOCK_DEFINE_STATIC (g_prgname);
1985 static gchar *g_prgname = NULL;
1990 * Gets the name of the program. This name should <emphasis>not</emphasis>
1991 * be localized, contrast with g_get_application_name().
1992 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1993 * which is called by gtk_init(). The program name is found by taking
1994 * the last component of <literal>argv[0]</literal>.)
1996 * Returns: the name of the program. The returned string belongs
1997 * to GLib and must not be modified or freed.
2000 g_get_prgname (void)
2006 if (g_prgname == NULL)
2008 static gboolean beenhere = FALSE;
2012 gchar *utf8_buf = NULL;
2013 wchar_t buf[MAX_PATH+1];
2016 if (GetModuleFileNameW (GetModuleHandle (NULL),
2017 buf, G_N_ELEMENTS (buf)) > 0)
2018 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2022 g_prgname = g_path_get_basename (utf8_buf);
2029 G_UNLOCK (g_prgname);
2036 * @prgname: the name of the program.
2038 * Sets the name of the program. This name should <emphasis>not</emphasis>
2039 * be localized, contrast with g_set_application_name(). Note that for
2040 * thread-safety reasons this function can only be called once.
2043 g_set_prgname (const gchar *prgname)
2047 g_prgname = g_strdup (prgname);
2048 G_UNLOCK (g_prgname);
2051 G_LOCK_DEFINE_STATIC (g_application_name);
2052 static gchar *g_application_name = NULL;
2055 * g_get_application_name:
2057 * Gets a human-readable name for the application, as set by
2058 * g_set_application_name(). This name should be localized if
2059 * possible, and is intended for display to the user. Contrast with
2060 * g_get_prgname(), which gets a non-localized name. If
2061 * g_set_application_name() has not been called, returns the result of
2062 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2065 * Return value: human-readable application name. may return %NULL
2069 G_CONST_RETURN gchar*
2070 g_get_application_name (void)
2074 G_LOCK (g_application_name);
2075 retval = g_application_name;
2076 G_UNLOCK (g_application_name);
2079 return g_get_prgname ();
2085 * g_set_application_name:
2086 * @application_name: localized name of the application
2088 * Sets a human-readable name for the application. This name should be
2089 * localized if possible, and is intended for display to the user.
2090 * Contrast with g_set_prgname(), which sets a non-localized name.
2091 * g_set_prgname() will be called automatically by gtk_init(),
2092 * but g_set_application_name() will not.
2094 * Note that for thread safety reasons, this function can only
2097 * The application name will be used in contexts such as error messages,
2098 * or when displaying an application's name in the task list.
2103 g_set_application_name (const gchar *application_name)
2105 gboolean already_set = FALSE;
2107 G_LOCK (g_application_name);
2108 if (g_application_name)
2111 g_application_name = g_strdup (application_name);
2112 G_UNLOCK (g_application_name);
2115 g_warning ("g_set_application_name() called multiple times");
2119 * g_get_user_data_dir:
2121 * Returns a base directory in which to access application data such
2122 * as icons that is customized for a particular user.
2124 * On UNIX platforms this is determined using the mechanisms described in
2125 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2126 * XDG Base Directory Specification</ulink>.
2127 * In this case the directory retrieved will be XDG_DATA_HOME.
2129 * On Windows this is the folder to use for local (as opposed to
2130 * roaming) application data. See documentation for
2131 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2132 * what g_get_user_config_dir() returns.
2134 * Return value: a string owned by GLib that must not be modified
2138 G_CONST_RETURN gchar*
2139 g_get_user_data_dir (void)
2143 G_LOCK (g_utils_global);
2145 if (!g_user_data_dir)
2148 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2150 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2152 if (data_dir && data_dir[0])
2153 data_dir = g_strdup (data_dir);
2155 if (!data_dir || !data_dir[0])
2160 data_dir = g_build_filename (g_home_dir, ".local",
2163 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2167 g_user_data_dir = data_dir;
2170 data_dir = g_user_data_dir;
2172 G_UNLOCK (g_utils_global);
2178 g_init_user_config_dir (void)
2182 if (!g_user_config_dir)
2185 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2187 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2189 if (config_dir && config_dir[0])
2190 config_dir = g_strdup (config_dir);
2192 if (!config_dir || !config_dir[0])
2197 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2199 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2202 g_user_config_dir = config_dir;
2207 * g_get_user_config_dir:
2209 * Returns a base directory in which to store user-specific application
2210 * configuration information such as user preferences and settings.
2212 * On UNIX platforms this is determined using the mechanisms described in
2213 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2214 * XDG Base Directory Specification</ulink>.
2215 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2217 * On Windows this is the folder to use for local (as opposed to
2218 * roaming) application data. See documentation for
2219 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2220 * what g_get_user_data_dir() returns.
2222 * Return value: a string owned by GLib that must not be modified
2226 G_CONST_RETURN gchar*
2227 g_get_user_config_dir (void)
2229 G_LOCK (g_utils_global);
2231 g_init_user_config_dir ();
2233 G_UNLOCK (g_utils_global);
2235 return g_user_config_dir;
2239 * g_get_user_cache_dir:
2241 * Returns a base directory in which to store non-essential, cached
2242 * data specific to particular user.
2244 * On UNIX platforms this is determined using the mechanisms described in
2245 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2246 * XDG Base Directory Specification</ulink>.
2247 * In this case the directory retrieved will be XDG_CACHE_HOME.
2249 * On Windows is the directory that serves as a common repository for
2250 * temporary Internet files. A typical path is
2251 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2252 * See documentation for CSIDL_INTERNET_CACHE.
2254 * Return value: a string owned by GLib that must not be modified
2258 G_CONST_RETURN gchar*
2259 g_get_user_cache_dir (void)
2263 G_LOCK (g_utils_global);
2265 if (!g_user_cache_dir)
2268 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2270 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2272 if (cache_dir && cache_dir[0])
2273 cache_dir = g_strdup (cache_dir);
2275 if (!cache_dir || !cache_dir[0])
2280 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2282 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2284 g_user_cache_dir = cache_dir;
2287 cache_dir = g_user_cache_dir;
2289 G_UNLOCK (g_utils_global);
2295 * g_get_user_runtime_dir:
2297 * Returns a directory that is unique to the current user on the local
2300 * On UNIX platforms this is determined using the mechanisms described in
2301 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2302 * XDG Base Directory Specification</ulink>. This is the directory
2303 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2304 * In the case that this variable is not set, GLib will issue a warning
2305 * message to stderr and return the value of g_get_user_cache_dir().
2307 * On Windows this is the folder to use for local (as opposed to
2308 * roaming) application data. See documentation for
2309 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2310 * what g_get_user_config_dir() returns.
2312 * Returns: a string owned by GLib that must not be modified or freed.
2317 g_get_user_runtime_dir (void)
2320 static const gchar *runtime_dir;
2321 static gsize initialised;
2323 if (g_once_init_enter (&initialised))
2325 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2327 if (runtime_dir == NULL)
2328 g_warning ("XDG_RUNTIME_DIR variable not set. "
2329 "Falling back to XDG cache dir.");
2331 g_once_init_leave (&initialised, 1);
2337 /* Both fallback for UNIX and the default
2338 * in Windows: use the user cache directory.
2342 return g_get_user_cache_dir ();
2348 find_folder (OSType type)
2350 gchar *filename = NULL;
2353 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2355 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2359 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2363 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2367 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2369 CFStringGetCString (path, filename,
2370 CFStringGetLength (path) * 3 + 1,
2371 kCFStringEncodingUTF8);
2385 load_user_special_dirs (void)
2387 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2388 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2389 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2390 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2391 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2392 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2393 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2394 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2397 #endif /* HAVE_CARBON */
2399 #if defined(G_OS_WIN32)
2401 load_user_special_dirs (void)
2403 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2407 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2409 static const GUID FOLDERID_Downloads =
2410 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2411 static const GUID FOLDERID_Public =
2412 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2416 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2417 "SHGetKnownFolderPath");
2419 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2420 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2422 if (p_SHGetKnownFolderPath == NULL)
2424 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2429 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2432 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2433 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2434 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2435 CoTaskMemFree (wcp);
2438 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2441 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2442 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2444 if (p_SHGetKnownFolderPath == NULL)
2447 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2452 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2455 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2456 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2457 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2458 CoTaskMemFree (wcp);
2461 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2464 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2465 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2467 #endif /* G_OS_WIN32 */
2469 static void g_init_user_config_dir (void);
2471 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2473 /* adapted from xdg-user-dir-lookup.c
2475 * Copyright (C) 2007 Red Hat Inc.
2477 * Permission is hereby granted, free of charge, to any person
2478 * obtaining a copy of this software and associated documentation files
2479 * (the "Software"), to deal in the Software without restriction,
2480 * including without limitation the rights to use, copy, modify, merge,
2481 * publish, distribute, sublicense, and/or sell copies of the Software,
2482 * and to permit persons to whom the Software is furnished to do so,
2483 * subject to the following conditions:
2485 * The above copyright notice and this permission notice shall be
2486 * included in all copies or substantial portions of the Software.
2488 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2489 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2490 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2491 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2492 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2493 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2494 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2498 load_user_special_dirs (void)
2505 g_init_user_config_dir ();
2506 config_file = g_build_filename (g_user_config_dir,
2510 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2512 g_free (config_file);
2516 lines = g_strsplit (data, "\n", -1);
2517 n_lines = g_strv_length (lines);
2520 for (i = 0; i < n_lines; i++)
2522 gchar *buffer = lines[i];
2525 gboolean is_relative = FALSE;
2526 GUserDirectory directory;
2528 /* Remove newline at end */
2529 len = strlen (buffer);
2530 if (len > 0 && buffer[len - 1] == '\n')
2531 buffer[len - 1] = 0;
2534 while (*p == ' ' || *p == '\t')
2537 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2539 directory = G_USER_DIRECTORY_DESKTOP;
2540 p += strlen ("XDG_DESKTOP_DIR");
2542 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2544 directory = G_USER_DIRECTORY_DOCUMENTS;
2545 p += strlen ("XDG_DOCUMENTS_DIR");
2547 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2549 directory = G_USER_DIRECTORY_DOWNLOAD;
2550 p += strlen ("XDG_DOWNLOAD_DIR");
2552 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2554 directory = G_USER_DIRECTORY_MUSIC;
2555 p += strlen ("XDG_MUSIC_DIR");
2557 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2559 directory = G_USER_DIRECTORY_PICTURES;
2560 p += strlen ("XDG_PICTURES_DIR");
2562 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2564 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2565 p += strlen ("XDG_PUBLICSHARE_DIR");
2567 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2569 directory = G_USER_DIRECTORY_TEMPLATES;
2570 p += strlen ("XDG_TEMPLATES_DIR");
2572 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2574 directory = G_USER_DIRECTORY_VIDEOS;
2575 p += strlen ("XDG_VIDEOS_DIR");
2580 while (*p == ' ' || *p == '\t')
2587 while (*p == ' ' || *p == '\t')
2594 if (strncmp (p, "$HOME", 5) == 0)
2602 d = strrchr (p, '"');
2609 /* remove trailing slashes */
2611 if (d[len - 1] == '/')
2617 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2620 g_user_special_dirs[directory] = g_strdup (d);
2624 g_free (config_file);
2627 #endif /* G_OS_UNIX && !HAVE_CARBON */
2631 * g_reload_user_special_dirs_cache:
2633 * Resets the cache used for g_get_user_special_dir(), so
2634 * that the latest on-disk version is used. Call this only
2635 * if you just changed the data on disk yourself.
2637 * Due to threadsafety issues this may cause leaking of strings
2638 * that were previously returned from g_get_user_special_dir()
2639 * that can't be freed. We ensure to only leak the data for
2640 * the directories that actually changed value though.
2645 g_reload_user_special_dirs_cache (void)
2649 G_LOCK (g_utils_global);
2651 if (g_user_special_dirs != NULL)
2653 /* save a copy of the pointer, to check if some memory can be preserved */
2654 char **old_g_user_special_dirs = g_user_special_dirs;
2657 /* recreate and reload our cache */
2658 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2659 load_user_special_dirs ();
2661 /* only leak changed directories */
2662 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2664 old_val = old_g_user_special_dirs[i];
2665 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2668 g_free (g_user_special_dirs[i]);
2669 g_user_special_dirs[i] = old_val;
2675 /* free the old array */
2676 g_free (old_g_user_special_dirs);
2679 G_UNLOCK (g_utils_global);
2683 * g_get_user_special_dir:
2684 * @directory: the logical id of special directory
2686 * Returns the full path of a special directory using its logical id.
2688 * On Unix this is done using the XDG special user directories.
2689 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2690 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2691 * user directories have not been set up.
2693 * Depending on the platform, the user might be able to change the path
2694 * of the special directory without requiring the session to restart; GLib
2695 * will not reflect any change once the special directories are loaded.
2697 * Return value: the path to the specified special directory, or %NULL
2698 * if the logical id was not found. The returned string is owned by
2699 * GLib and should not be modified or freed.
2703 G_CONST_RETURN gchar *
2704 g_get_user_special_dir (GUserDirectory directory)
2706 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2707 directory < G_USER_N_DIRECTORIES, NULL);
2709 G_LOCK (g_utils_global);
2711 if (G_UNLIKELY (g_user_special_dirs == NULL))
2713 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2715 load_user_special_dirs ();
2717 /* Special-case desktop for historical compatibility */
2718 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2722 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2723 g_build_filename (g_home_dir, "Desktop", NULL);
2727 G_UNLOCK (g_utils_global);
2729 return g_user_special_dirs[directory];
2734 #undef g_get_system_data_dirs
2737 get_module_for_address (gconstpointer address)
2739 /* Holds the g_utils_global lock */
2741 static gboolean beenhere = FALSE;
2742 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2743 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2744 HMODULE hmodule = NULL;
2751 p_GetModuleHandleExA =
2752 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2753 "GetModuleHandleExA");
2757 if (p_GetModuleHandleExA == NULL ||
2758 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2759 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2762 MEMORY_BASIC_INFORMATION mbi;
2763 VirtualQuery (address, &mbi, sizeof (mbi));
2764 hmodule = (HMODULE) mbi.AllocationBase;
2771 get_module_share_dir (gconstpointer address)
2777 hmodule = get_module_for_address (address);
2778 if (hmodule == NULL)
2781 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2782 retval = g_build_filename (filename, "share", NULL);
2788 G_CONST_RETURN gchar * G_CONST_RETURN *
2789 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2793 static GHashTable *per_module_data_dirs = NULL;
2798 if (address_of_function)
2800 G_LOCK (g_utils_global);
2801 hmodule = get_module_for_address (address_of_function);
2802 if (hmodule != NULL)
2804 if (per_module_data_dirs == NULL)
2805 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2808 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2812 G_UNLOCK (g_utils_global);
2813 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2819 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2821 /* Documents and Settings\All Users\Application Data */
2822 p = get_special_folder (CSIDL_COMMON_APPDATA);
2824 g_array_append_val (data_dirs, p);
2826 /* Documents and Settings\All Users\Documents */
2827 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2829 g_array_append_val (data_dirs, p);
2831 /* Using the above subfolders of Documents and Settings perhaps
2832 * makes sense from a Windows perspective.
2834 * But looking at the actual use cases of this function in GTK+
2835 * and GNOME software, what we really want is the "share"
2836 * subdirectory of the installation directory for the package
2837 * our caller is a part of.
2839 * The address_of_function parameter, if non-NULL, points to a
2840 * function in the calling module. Use that to determine that
2841 * module's installation folder, and use its "share" subfolder.
2843 * Additionally, also use the "share" subfolder of the installation
2844 * locations of GLib and the .exe file being run.
2846 * To guard against none of the above being what is really wanted,
2847 * callers of this function should have Win32-specific code to look
2848 * up their installation folder themselves, and handle a subfolder
2849 * "share" of it in the same way as the folders returned from this
2853 p = get_module_share_dir (address_of_function);
2855 g_array_append_val (data_dirs, p);
2857 if (glib_dll != NULL)
2859 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2860 p = g_build_filename (glib_root, "share", NULL);
2862 g_array_append_val (data_dirs, p);
2866 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2867 p = g_build_filename (exe_root, "share", NULL);
2869 g_array_append_val (data_dirs, p);
2872 retval = (gchar **) g_array_free (data_dirs, FALSE);
2874 if (address_of_function)
2876 if (hmodule != NULL)
2877 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2878 G_UNLOCK (g_utils_global);
2881 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2887 * g_get_system_data_dirs:
2889 * Returns an ordered list of base directories in which to access
2890 * system-wide application data.
2892 * On UNIX platforms this is determined using the mechanisms described in
2893 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2894 * XDG Base Directory Specification</ulink>
2895 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2897 * On Windows the first elements in the list are the Application Data
2898 * and Documents folders for All Users. (These can be determined only
2899 * on Windows 2000 or later and are not present in the list on other
2900 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2901 * CSIDL_COMMON_DOCUMENTS.
2903 * Then follows the "share" subfolder in the installation folder for
2904 * the package containing the DLL that calls this function, if it can
2907 * Finally the list contains the "share" subfolder in the installation
2908 * folder for GLib, and in the installation folder for the package the
2909 * application's .exe file belongs to.
2911 * The installation folders above are determined by looking up the
2912 * folder where the module (DLL or EXE) in question is located. If the
2913 * folder's name is "bin", its parent is used, otherwise the folder
2916 * Note that on Windows the returned list can vary depending on where
2917 * this function is called.
2919 * Return value: a %NULL-terminated array of strings owned by GLib that must
2920 * not be modified or freed.
2923 G_CONST_RETURN gchar * G_CONST_RETURN *
2924 g_get_system_data_dirs (void)
2926 gchar **data_dir_vector;
2928 G_LOCK (g_utils_global);
2930 if (!g_system_data_dirs)
2933 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2935 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2937 if (!data_dirs || !data_dirs[0])
2938 data_dirs = "/usr/local/share/:/usr/share/";
2940 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2943 g_system_data_dirs = data_dir_vector;
2946 data_dir_vector = g_system_data_dirs;
2948 G_UNLOCK (g_utils_global);
2950 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2954 * g_get_system_config_dirs:
2956 * Returns an ordered list of base directories in which to access
2957 * system-wide configuration information.
2959 * On UNIX platforms this is determined using the mechanisms described in
2960 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2961 * XDG Base Directory Specification</ulink>.
2962 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2964 * On Windows is the directory that contains application data for all users.
2965 * A typical path is C:\Documents and Settings\All Users\Application Data.
2966 * This folder is used for application data that is not user specific.
2967 * For example, an application can store a spell-check dictionary, a database
2968 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2969 * This information will not roam and is available to anyone using the computer.
2971 * Return value: a %NULL-terminated array of strings owned by GLib that must
2972 * not be modified or freed.
2975 G_CONST_RETURN gchar * G_CONST_RETURN *
2976 g_get_system_config_dirs (void)
2978 gchar *conf_dirs, **conf_dir_vector;
2980 G_LOCK (g_utils_global);
2982 if (!g_system_config_dirs)
2985 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2988 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2993 /* Return empty list */
2994 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2997 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2999 if (!conf_dirs || !conf_dirs[0])
3000 conf_dirs = "/etc/xdg";
3002 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3005 g_system_config_dirs = conf_dir_vector;
3008 conf_dir_vector = g_system_config_dirs;
3009 G_UNLOCK (g_utils_global);
3011 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
3016 static GHashTable *alias_table = NULL;
3018 /* read an alias file for the locales */
3020 read_aliases (gchar *file)
3026 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3027 fp = fopen (file,"r");
3030 while (fgets (buf, 256, fp))
3036 /* Line is a comment */
3037 if ((buf[0] == '#') || (buf[0] == '\0'))
3040 /* Reads first column */
3041 for (p = buf, q = NULL; *p; p++) {
3042 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3045 while ((*q == '\t') || (*q == ' ')) {
3051 /* The line only had one column */
3052 if (!q || *q == '\0')
3055 /* Read second column */
3056 for (p = q; *p; p++) {
3057 if ((*p == '\t') || (*p == ' ')) {
3063 /* Add to alias table if necessary */
3064 if (!g_hash_table_lookup (alias_table, buf)) {
3065 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3074 unalias_lang (char *lang)
3081 read_aliases ("/usr/share/locale/locale.alias");
3084 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3089 static gboolean said_before = FALSE;
3091 g_warning ("Too many alias levels for a locale, "
3092 "may indicate a loop");
3101 /* Mask for components of locale spec. The ordering here is from
3102 * least significant to most significant
3106 COMPONENT_CODESET = 1 << 0,
3107 COMPONENT_TERRITORY = 1 << 1,
3108 COMPONENT_MODIFIER = 1 << 2
3111 /* Break an X/Open style locale specification into components
3114 explode_locale (const gchar *locale,
3120 const gchar *uscore_pos;
3121 const gchar *at_pos;
3122 const gchar *dot_pos;
3126 uscore_pos = strchr (locale, '_');
3127 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3128 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3132 mask |= COMPONENT_MODIFIER;
3133 *modifier = g_strdup (at_pos);
3136 at_pos = locale + strlen (locale);
3140 mask |= COMPONENT_CODESET;
3141 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3148 mask |= COMPONENT_TERRITORY;
3149 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3152 uscore_pos = dot_pos;
3154 *language = g_strndup (locale, uscore_pos - locale);
3160 * Compute all interesting variants for a given locale name -
3161 * by stripping off different components of the value.
3163 * For simplicity, we assume that the locale is in
3164 * X/Open format: language[_territory][.codeset][@modifier]
3166 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3167 * as well. We could just copy the code from glibc wholesale
3168 * but it is big, ugly, and complicated, so I'm reluctant
3169 * to do so when this should handle 99% of the time...
3172 append_locale_variants (GPtrArray *array,
3173 const gchar *locale)
3175 gchar *language = NULL;
3176 gchar *territory = NULL;
3177 gchar *codeset = NULL;
3178 gchar *modifier = NULL;
3183 g_return_if_fail (locale != NULL);
3185 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3187 /* Iterate through all possible combinations, from least attractive
3188 * to most attractive.
3190 for (j = 0; j <= mask; ++j)
3194 if ((i & ~mask) == 0)
3196 gchar *val = g_strconcat (language,
3197 (i & COMPONENT_TERRITORY) ? territory : "",
3198 (i & COMPONENT_CODESET) ? codeset : "",
3199 (i & COMPONENT_MODIFIER) ? modifier : "",
3201 g_ptr_array_add (array, val);
3206 if (mask & COMPONENT_CODESET)
3208 if (mask & COMPONENT_TERRITORY)
3210 if (mask & COMPONENT_MODIFIER)
3215 * g_get_locale_variants:
3216 * @locale: a locale identifier
3218 * Returns a list of derived variants of @locale, which can be used to
3219 * e.g. construct locale-dependent filenames or search paths. The returned
3220 * list is sorted from most desirable to least desirable.
3221 * This function handles territory, charset and extra locale modifiers.
3223 * For example, if @locale is "fr_BE", then the returned list
3226 * If you need the list of variants for the <emphasis>current locale</emphasis>,
3227 * use g_get_language_names().
3229 * Returns: (transfer full) (array zero-terminated="1") (element-type utf8): a newly
3230 * allocated array of newly allocated strings with the locale variants. Free with
3236 g_get_locale_variants (const gchar *locale)
3240 g_return_val_if_fail (locale != NULL, NULL);
3242 array = g_ptr_array_sized_new (8);
3243 append_locale_variants (array, locale);
3244 g_ptr_array_add (array, NULL);
3246 return (gchar **) g_ptr_array_free (array, FALSE);
3249 /* The following is (partly) taken from the gettext package.
3250 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3252 static const gchar *
3253 guess_category_value (const gchar *category_name)
3255 const gchar *retval;
3257 /* The highest priority value is the `LANGUAGE' environment
3258 variable. This is a GNU extension. */
3259 retval = g_getenv ("LANGUAGE");
3260 if ((retval != NULL) && (retval[0] != '\0'))
3263 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3264 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3265 systems this can be done by the `setlocale' function itself. */
3267 /* Setting of LC_ALL overwrites all other. */
3268 retval = g_getenv ("LC_ALL");
3269 if ((retval != NULL) && (retval[0] != '\0'))
3272 /* Next comes the name of the desired category. */
3273 retval = g_getenv (category_name);
3274 if ((retval != NULL) && (retval[0] != '\0'))
3277 /* Last possibility is the LANG environment variable. */
3278 retval = g_getenv ("LANG");
3279 if ((retval != NULL) && (retval[0] != '\0'))
3282 #ifdef G_PLATFORM_WIN32
3283 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3284 * LANG, which we already did above. Oh well. The main point of
3285 * calling g_win32_getlocale() is to get the thread's locale as used
3286 * by Windows and the Microsoft C runtime (in the "English_United
3287 * States" format) translated into the Unixish format.
3290 char *locale = g_win32_getlocale ();
3291 retval = g_intern_string (locale);
3300 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3302 struct _GLanguageNamesCache {
3304 gchar **language_names;
3308 language_names_cache_free (gpointer data)
3310 GLanguageNamesCache *cache = data;
3311 g_free (cache->languages);
3312 g_strfreev (cache->language_names);
3317 * g_get_language_names:
3319 * Computes a list of applicable locale names, which can be used to
3320 * e.g. construct locale-dependent filenames or search paths. The returned
3321 * list is sorted from most desirable to least desirable and always contains
3322 * the default locale "C".
3324 * For example, if LANGUAGE=de:en_US, then the returned list is
3325 * "de", "en_US", "en", "C".
3327 * This function consults the environment variables <envar>LANGUAGE</envar>,
3328 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3329 * to find the list of locales specified by the user.
3331 * Return value: a %NULL-terminated array of strings owned by GLib
3332 * that must not be modified or freed.
3336 G_CONST_RETURN gchar * G_CONST_RETURN *
3337 g_get_language_names (void)
3339 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3340 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3345 cache = g_new0 (GLanguageNamesCache, 1);
3346 g_static_private_set (&cache_private, cache, language_names_cache_free);
3349 value = guess_category_value ("LC_MESSAGES");
3353 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3358 g_free (cache->languages);
3359 g_strfreev (cache->language_names);
3360 cache->languages = g_strdup (value);
3362 array = g_ptr_array_sized_new (8);
3364 alist = g_strsplit (value, ":", 0);
3365 for (a = alist; *a; a++)
3366 append_locale_variants (array, unalias_lang (*a));
3368 g_ptr_array_add (array, g_strdup ("C"));
3369 g_ptr_array_add (array, NULL);
3371 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3374 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3379 * @v: a #gpointer key
3381 * Converts a gpointer to a hash value.
3382 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3383 * when using pointers as keys in a #GHashTable.
3385 * Returns: a hash value corresponding to the key.
3388 g_direct_hash (gconstpointer v)
3390 return GPOINTER_TO_UINT (v);
3396 * @v2: a key to compare with @v1.
3398 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3399 * It can be passed to g_hash_table_new() as the @key_equal_func
3400 * parameter, when using pointers as keys in a #GHashTable.
3402 * Returns: %TRUE if the two keys match.
3405 g_direct_equal (gconstpointer v1,
3413 * @v1: a pointer to a #gint key.
3414 * @v2: a pointer to a #gint key to compare with @v1.
3416 * Compares the two #gint values being pointed to and returns
3417 * %TRUE if they are equal.
3418 * It can be passed to g_hash_table_new() as the @key_equal_func
3419 * parameter, when using pointers to integers as keys in a #GHashTable.
3421 * Returns: %TRUE if the two keys match.
3424 g_int_equal (gconstpointer v1,
3427 return *((const gint*) v1) == *((const gint*) v2);
3432 * @v: a pointer to a #gint key
3434 * Converts a pointer to a #gint to a hash value.
3435 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3436 * when using pointers to integers values as keys in a #GHashTable.
3438 * Returns: a hash value corresponding to the key.
3441 g_int_hash (gconstpointer v)
3443 return *(const gint*) v;
3448 * @v1: a pointer to a #gint64 key.
3449 * @v2: a pointer to a #gint64 key to compare with @v1.
3451 * Compares the two #gint64 values being pointed to and returns
3452 * %TRUE if they are equal.
3453 * It can be passed to g_hash_table_new() as the @key_equal_func
3454 * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3456 * Returns: %TRUE if the two keys match.
3461 g_int64_equal (gconstpointer v1,
3464 return *((const gint64*) v1) == *((const gint64*) v2);
3469 * @v: a pointer to a #gint64 key
3471 * Converts a pointer to a #gint64 to a hash value.
3472 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3473 * when using pointers to 64-bit integers values as keys in a #GHashTable.
3475 * Returns: a hash value corresponding to the key.
3480 g_int64_hash (gconstpointer v)
3482 return (guint) *(const gint64*) v;
3487 * @v1: a pointer to a #gdouble key.
3488 * @v2: a pointer to a #gdouble key to compare with @v1.
3490 * Compares the two #gdouble values being pointed to and returns
3491 * %TRUE if they are equal.
3492 * It can be passed to g_hash_table_new() as the @key_equal_func
3493 * parameter, when using pointers to doubles as keys in a #GHashTable.
3495 * Returns: %TRUE if the two keys match.
3500 g_double_equal (gconstpointer v1,
3503 return *((const gdouble*) v1) == *((const gdouble*) v2);
3508 * @v: a pointer to a #gdouble key
3510 * Converts a pointer to a #gdouble to a hash value.
3511 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3512 * when using pointers to doubles as keys in a #GHashTable.
3514 * Returns: a hash value corresponding to the key.
3519 g_double_hash (gconstpointer v)
3521 return (guint) *(const gdouble*) v;
3525 * g_nullify_pointer:
3526 * @nullify_location: the memory address of the pointer.
3528 * Set the pointer at the specified location to %NULL.
3531 g_nullify_pointer (gpointer *nullify_location)
3533 g_return_if_fail (nullify_location != NULL);
3535 *nullify_location = NULL;
3541 * Get the codeset for the current locale.
3543 * Return value: a newly allocated string containing the name
3544 * of the codeset. This string must be freed with g_free().
3547 g_get_codeset (void)
3549 const gchar *charset;
3551 g_get_charset (&charset);
3553 return g_strdup (charset);
3556 /* This is called from g_thread_init(). It's used to
3557 * initialize some static data in a threadsafe way.
3560 _g_utils_thread_init (void)
3562 g_get_language_names ();
3568 * _glib_get_locale_dir:
3570 * Return the path to the share\locale or lib\locale subfolder of the
3571 * GLib installation folder. The path is in the system codepage. We
3572 * have to use system codepage as bindtextdomain() doesn't have a
3576 _glib_get_locale_dir (void)
3578 gchar *install_dir = NULL, *locale_dir;
3579 gchar *retval = NULL;
3581 if (glib_dll != NULL)
3582 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3587 * Append "/share/locale" or "/lib/locale" depending on whether
3588 * autoconfigury detected GNU gettext or not.
3590 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3596 locale_dir = g_build_filename (install_dir, p, NULL);
3598 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3600 g_free (install_dir);
3601 g_free (locale_dir);
3607 return g_strdup ("");
3610 #undef GLIB_LOCALE_DIR
3612 #endif /* G_OS_WIN32 */
3615 ensure_gettext_initialized(void)
3617 static gboolean _glib_gettext_initialized = FALSE;
3619 if (!_glib_gettext_initialized)
3622 gchar *tmp = _glib_get_locale_dir ();
3623 bindtextdomain (GETTEXT_PACKAGE, tmp);
3626 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3628 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3629 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3631 _glib_gettext_initialized = TRUE;
3637 * @str: The string to be translated
3639 * Returns the translated string from the glib translations.
3640 * This is an internal function and should only be used by
3641 * the internals of glib (such as libgio).
3643 * Returns: the transation of @str to the current locale
3645 G_CONST_RETURN gchar *
3646 glib_gettext (const gchar *str)
3648 ensure_gettext_initialized();
3650 return g_dgettext (GETTEXT_PACKAGE, str);
3655 * @msgctxtid: a combined message context and message id, separated
3656 * by a \004 character
3657 * @msgidoffset: the offset of the message id in @msgctxid
3659 * This function is a variant of glib_gettext() which supports
3660 * a disambiguating message context. See g_dpgettext() for full
3663 * This is an internal function and should only be used by
3664 * the internals of glib (such as libgio).
3666 * Returns: the transation of @str to the current locale
3668 G_CONST_RETURN gchar *
3669 glib_pgettext(const gchar *msgctxtid,
3672 ensure_gettext_initialized();
3674 return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3677 #if defined (G_OS_WIN32) && !defined (_WIN64)
3679 /* Binary compatibility versions. Not for newly compiled code. */
3681 #undef g_find_program_in_path
3684 g_find_program_in_path (const gchar *program)
3686 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3687 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3690 g_free (utf8_program);
3691 if (utf8_retval == NULL)
3693 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3694 g_free (utf8_retval);
3699 #undef g_get_current_dir
3702 g_get_current_dir (void)
3704 gchar *utf8_dir = g_get_current_dir_utf8 ();
3705 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3712 G_CONST_RETURN gchar*
3713 g_getenv (const gchar *variable)
3715 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3716 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3720 g_free (utf8_variable);
3723 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3724 quark = g_quark_from_string (value);
3727 return g_quark_to_string (quark);
3733 g_setenv (const gchar *variable,
3737 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3738 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3739 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3741 g_free (utf8_variable);
3742 g_free (utf8_value);
3750 g_unsetenv (const gchar *variable)
3752 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3754 g_unsetenv_utf8 (utf8_variable);
3756 g_free (utf8_variable);
3759 #undef g_get_user_name
3761 G_CONST_RETURN gchar*
3762 g_get_user_name (void)
3764 g_get_any_init_locked ();
3765 return g_user_name_cp;
3768 #undef g_get_real_name
3770 G_CONST_RETURN gchar*
3771 g_get_real_name (void)
3773 g_get_any_init_locked ();
3774 return g_real_name_cp;
3777 #undef g_get_home_dir
3779 G_CONST_RETURN gchar*
3780 g_get_home_dir (void)
3782 g_get_any_init_locked ();
3783 return g_home_dir_cp;
3786 #undef g_get_tmp_dir
3788 G_CONST_RETURN gchar*
3789 g_get_tmp_dir (void)
3791 g_get_any_init_locked ();
3792 return g_tmp_dir_cp;