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.
33 * @Title: Version Information
34 * @Short_description: Variables and functions to check the GLib version
36 * GLib provides version information, primarily useful in configure
37 * checks for builds that have a configure script. Applications will
38 * not typically use the features described here.
44 * The major version number of the GLib library.
46 * Like #glib_major_version, but from the headers used at
47 * application compile time, rather than from the library
48 * linked against at application run time.
54 * The minor version number of the GLib library.
56 * Like #gtk_minor_version, but from the headers used at
57 * application compile time, rather than from the library
58 * linked against at application run time.
64 * The micro version number of the GLib library.
66 * Like #gtk_micro_version, but from the headers used at
67 * application compile time, rather than from the library
68 * linked against at application run time.
81 #include <ctype.h> /* For tolower() */
83 #include <sys/types.h>
88 #include <sys/types.h>
89 #ifdef HAVE_SYS_PARAM_H
90 #include <sys/param.h>
92 #ifdef HAVE_CRT_EXTERNS_H
93 #include <crt_externs.h> /* for _NSGetEnviron */
96 /* implement gutils's inline functions
98 #define G_IMPLEMENT_INLINES 1
102 #include "gfileutils.h"
105 #include "gprintfint.h"
107 #include "gthreadprivate.h"
108 #include "gtestutils.h"
109 #include "gunicode.h"
110 #include "gstrfuncs.h"
112 #include "glibintl.h"
114 #ifdef G_PLATFORM_WIN32
116 #include "gconvert.h"
123 * @title: Miscellaneous Utility Functions
124 * @short_description: a selection of portable utility functions
126 * These are portable utility functions.
130 #define G_PATH_LENGTH MAXPATHLEN
131 #elif defined (PATH_MAX)
132 #define G_PATH_LENGTH PATH_MAX
133 #elif defined (_PC_PATH_MAX)
134 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
136 #define G_PATH_LENGTH 2048
139 #ifdef G_PLATFORM_WIN32
140 # define STRICT /* Strict typing, please */
141 # include <windows.h>
143 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
144 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
145 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
147 # include <lmcons.h> /* For UNLEN */
148 #endif /* G_PLATFORM_WIN32 */
153 /* older SDK (e.g. msvc 5.0) does not have these*/
154 # ifndef CSIDL_MYMUSIC
155 # define CSIDL_MYMUSIC 13
157 # ifndef CSIDL_MYVIDEO
158 # define CSIDL_MYVIDEO 14
160 # ifndef CSIDL_INTERNET_CACHE
161 # define CSIDL_INTERNET_CACHE 32
163 # ifndef CSIDL_COMMON_APPDATA
164 # define CSIDL_COMMON_APPDATA 35
166 # ifndef CSIDL_MYPICTURES
167 # define CSIDL_MYPICTURES 0x27
169 # ifndef CSIDL_COMMON_DOCUMENTS
170 # define CSIDL_COMMON_DOCUMENTS 46
172 # ifndef CSIDL_PROFILE
173 # define CSIDL_PROFILE 40
175 # include <process.h>
179 #include <CoreServices/CoreServices.h>
183 #include <langinfo.h>
186 const guint glib_major_version = GLIB_MAJOR_VERSION;
187 const guint glib_minor_version = GLIB_MINOR_VERSION;
188 const guint glib_micro_version = GLIB_MICRO_VERSION;
189 const guint glib_interface_age = GLIB_INTERFACE_AGE;
190 const guint glib_binary_age = GLIB_BINARY_AGE;
192 #ifdef G_PLATFORM_WIN32
194 static HMODULE glib_dll = NULL;
199 DllMain (HINSTANCE hinstDLL,
203 if (fdwReason == DLL_PROCESS_ATTACH)
215 _glib_get_dll_directory (void)
219 wchar_t wc_fn[MAX_PATH];
222 if (glib_dll == NULL)
226 /* This code is different from that in
227 * g_win32_get_package_installation_directory_of_module() in that
228 * here we return the actual folder where the GLib DLL is. We don't
229 * do the check for it being in a "bin" or "lib" subfolder and then
230 * returning the parent of that.
232 * In a statically built GLib, glib_dll will be NULL and we will
233 * thus look up the application's .exe file's location.
235 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
238 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
240 p = strrchr (retval, G_DIR_SEPARATOR);
254 * glib_check_version:
255 * @required_major: the required major version.
256 * @required_minor: the required minor version.
257 * @required_micro: the required micro version.
259 * Checks that the GLib library in use is compatible with the
260 * given version. Generally you would pass in the constants
261 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
262 * as the three arguments to this function; that produces
263 * a check that the library in use is compatible with
264 * the version of GLib the application or module was compiled
267 * Compatibility is defined by two things: first the version
268 * of the running library is newer than the version
269 * @required_major.required_minor.@required_micro. Second
270 * the running library must be binary compatible with the
271 * version @required_major.required_minor.@required_micro
272 * (same major version.)
274 * Return value: %NULL if the GLib library is compatible with the
275 * given version, or a string describing the version mismatch.
276 * The returned string is owned by GLib and must not be modified
282 glib_check_version (guint required_major,
283 guint required_minor,
284 guint required_micro)
286 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
287 gint required_effective_micro = 100 * required_minor + required_micro;
289 if (required_major > GLIB_MAJOR_VERSION)
290 return "GLib version too old (major mismatch)";
291 if (required_major < GLIB_MAJOR_VERSION)
292 return "GLib version too new (major mismatch)";
293 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
294 return "GLib version too new (micro mismatch)";
295 if (required_effective_micro > glib_effective_micro)
296 return "GLib version too old (micro mismatch)";
300 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
303 * @dest: the destination address to copy the bytes to.
304 * @src: the source address to copy the bytes from.
305 * @len: the number of bytes to copy.
307 * Copies a block of memory @len bytes long, from @src to @dest.
308 * The source and destination areas may overlap.
310 * In order to use this function, you must include
311 * <filename>string.h</filename> yourself, because this macro will
312 * typically simply resolve to memmove() and GLib does not include
313 * <filename>string.h</filename> for you.
316 g_memmove (gpointer dest,
320 gchar* destptr = dest;
321 const gchar* srcptr = src;
322 if (src + len < dest || dest + len < src)
324 bcopy (src, dest, len);
327 else if (dest <= src)
330 *(destptr++) = *(srcptr++);
337 *(--destptr) = *(--srcptr);
340 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
348 * @func: (scope async): the function to call on normal program termination.
350 * Specifies a function to be called at normal program termination.
352 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
353 * macro that maps to a call to the atexit() function in the C
354 * library. This means that in case the code that calls g_atexit(),
355 * i.e. atexit(), is in a DLL, the function will be called when the
356 * DLL is detached from the program. This typically makes more sense
357 * than that the function is called when the GLib DLL is detached,
358 * which happened earlier when g_atexit() was a function in the GLib
361 * The behaviour of atexit() in the context of dynamically loaded
362 * modules is not formally specified and varies wildly.
364 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
365 * loaded module which is unloaded before the program terminates might
366 * well cause a crash at program exit.
368 * Some POSIX systems implement atexit() like Windows, and have each
369 * dynamically loaded module maintain an own atexit chain that is
370 * called when the module is unloaded.
372 * On other POSIX systems, before a dynamically loaded module is
373 * unloaded, the registered atexit functions (if any) residing in that
374 * module are called, regardless where the code that registered them
375 * resided. This is presumably the most robust approach.
377 * As can be seen from the above, for portability it's best to avoid
378 * calling g_atexit() (or atexit()) except in the main executable of a
382 g_atexit (GVoidFunc func)
385 const gchar *error = NULL;
387 /* keep this in sync with glib.h */
389 #ifdef G_NATIVE_ATEXIT
390 result = ATEXIT (func);
392 error = g_strerror (errno);
393 #elif defined (HAVE_ATEXIT)
394 # ifdef NeXT /* @#%@! NeXTStep */
395 result = !atexit ((void (*)(void)) func);
397 error = g_strerror (errno);
399 result = atexit ((void (*)(void)) func);
401 error = g_strerror (errno);
403 #elif defined (HAVE_ON_EXIT)
404 result = on_exit ((void (*)(int, void *)) func, NULL);
406 error = g_strerror (errno);
409 error = "no implementation";
410 #endif /* G_NATIVE_ATEXIT */
413 g_error ("Could not register atexit() function: %s", error);
416 /* Based on execvp() from GNU Libc.
417 * Some of this code is cut-and-pasted into gspawn.c
421 my_strchrnul (const gchar *str,
424 gchar *p = (gchar*)str;
425 while (*p && (*p != c))
433 static gchar *inner_find_program_in_path (const gchar *program);
436 g_find_program_in_path (const gchar *program)
438 const gchar *last_dot = strrchr (program, '.');
440 if (last_dot == NULL ||
441 strchr (last_dot, '\\') != NULL ||
442 strchr (last_dot, '/') != NULL)
444 const gint program_length = strlen (program);
445 gchar *pathext = g_build_path (";",
446 ".exe;.cmd;.bat;.com",
447 g_getenv ("PATHEXT"),
450 gchar *decorated_program;
456 gchar *q = my_strchrnul (p, ';');
458 decorated_program = g_malloc (program_length + (q-p) + 1);
459 memcpy (decorated_program, program, program_length);
460 memcpy (decorated_program+program_length, p, q-p);
461 decorated_program [program_length + (q-p)] = '\0';
463 retval = inner_find_program_in_path (decorated_program);
464 g_free (decorated_program);
472 } while (*p++ != '\0');
477 return inner_find_program_in_path (program);
483 * g_find_program_in_path:
484 * @program: a program name in the GLib file name encoding
486 * Locates the first executable named @program in the user's path, in the
487 * same way that execvp() would locate it. Returns an allocated string
488 * with the absolute path name, or %NULL if the program is not found in
489 * the path. If @program is already an absolute path, returns a copy of
490 * @program if @program exists and is executable, and %NULL otherwise.
492 * On Windows, if @program does not have a file type suffix, tries
493 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
494 * the <envar>PATHEXT</envar> environment variable.
496 * On Windows, it looks for the file in the same way as CreateProcess()
497 * would. This means first in the directory where the executing
498 * program was loaded from, then in the current directory, then in the
499 * Windows 32-bit system directory, then in the Windows directory, and
500 * finally in the directories in the <envar>PATH</envar> environment
501 * variable. If the program is found, the return value contains the
502 * full name including the type suffix.
504 * Return value: absolute path, or %NULL
508 inner_find_program_in_path (const gchar *program)
511 g_find_program_in_path (const gchar *program)
514 const gchar *path, *p;
515 gchar *name, *freeme;
517 const gchar *path_copy;
518 gchar *filename = NULL, *appdir = NULL;
519 gchar *sysdir = NULL, *windir = NULL;
521 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
527 g_return_val_if_fail (program != NULL, NULL);
529 /* If it is an absolute path, or a relative path including subdirectories,
530 * don't look in PATH.
532 if (g_path_is_absolute (program)
533 || strchr (program, G_DIR_SEPARATOR) != NULL
535 || strchr (program, '/') != NULL
539 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
540 !g_file_test (program, G_FILE_TEST_IS_DIR))
541 return g_strdup (program);
546 path = g_getenv ("PATH");
547 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
550 /* There is no `PATH' in the environment. The default
551 * search path in GNU libc is the current directory followed by
552 * the path `confstr' returns for `_CS_PATH'.
555 /* In GLib we put . last, for security, and don't use the
556 * unportable confstr(); UNIX98 does not actually specify
557 * what to search if PATH is unset. POSIX may, dunno.
560 path = "/bin:/usr/bin:.";
563 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
564 if (n > 0 && n < MAXPATHLEN)
565 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
567 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
568 if (n > 0 && n < MAXPATHLEN)
569 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
571 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
572 if (n > 0 && n < MAXPATHLEN)
573 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
577 appdir = g_path_get_dirname (filename);
581 path = g_strdup (path);
585 const gchar *tem = path;
586 path = g_strconcat (windir, ";", path, NULL);
587 g_free ((gchar *) tem);
593 const gchar *tem = path;
594 path = g_strconcat (sysdir, ";", path, NULL);
595 g_free ((gchar *) tem);
600 const gchar *tem = path;
601 path = g_strconcat (".;", path, NULL);
602 g_free ((gchar *) tem);
607 const gchar *tem = path;
608 path = g_strconcat (appdir, ";", path, NULL);
609 g_free ((gchar *) tem);
616 len = strlen (program) + 1;
617 pathlen = strlen (path);
618 freeme = name = g_malloc (pathlen + len + 1);
620 /* Copy the file name at the top, including '\0' */
621 memcpy (name + pathlen + 1, program, len);
622 name = name + pathlen;
623 /* And add the slash before the filename */
624 *name = G_DIR_SEPARATOR;
632 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
635 /* Two adjacent colons, or a colon at the beginning or the end
636 * of `PATH' means to search the current directory.
640 startp = memcpy (name - (p - path), path, p - path);
642 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
643 !g_file_test (startp, G_FILE_TEST_IS_DIR))
646 ret = g_strdup (startp);
649 g_free ((gchar *) path_copy);
654 while (*p++ != '\0');
658 g_free ((gchar *) path_copy);
666 * @file_name: the name of the file.
668 * Gets the name of the file without any leading directory components.
669 * It returns a pointer into the given file name string.
671 * Return value: the name of the file without any leading directory components.
673 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
674 * g_path_get_basename() allocates new memory for the returned string, unlike
675 * this function which returns a pointer into the argument.
678 g_basename (const gchar *file_name)
680 register gchar *base;
682 g_return_val_if_fail (file_name != NULL, NULL);
684 base = strrchr (file_name, G_DIR_SEPARATOR);
688 gchar *q = strrchr (file_name, '/');
689 if (base == NULL || (q != NULL && q > base))
698 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
699 return (gchar*) file_name + 2;
700 #endif /* G_OS_WIN32 */
702 return (gchar*) file_name;
706 * g_path_get_basename:
707 * @file_name: the name of the file.
709 * Gets the last component of the filename. If @file_name ends with a
710 * directory separator it gets the component before the last slash. If
711 * @file_name consists only of directory separators (and on Windows,
712 * possibly a drive letter), a single separator is returned. If
713 * @file_name is empty, it gets ".".
715 * Return value: a newly allocated string containing the last component of
719 g_path_get_basename (const gchar *file_name)
721 register gssize base;
722 register gssize last_nonslash;
726 g_return_val_if_fail (file_name != NULL, NULL);
728 if (file_name[0] == '\0')
730 return g_strdup (".");
732 last_nonslash = strlen (file_name) - 1;
734 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
737 if (last_nonslash == -1)
738 /* string only containing slashes */
739 return g_strdup (G_DIR_SEPARATOR_S);
742 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
743 /* string only containing slashes and a drive */
744 return g_strdup (G_DIR_SEPARATOR_S);
745 #endif /* G_OS_WIN32 */
747 base = last_nonslash;
749 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
753 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
755 #endif /* G_OS_WIN32 */
757 len = last_nonslash - base;
758 retval = g_malloc (len + 1);
759 memcpy (retval, file_name + base + 1, len);
765 * g_path_is_absolute:
766 * @file_name: a file name.
768 * Returns %TRUE if the given @file_name is an absolute file name.
769 * Note that this is a somewhat vague concept on Windows.
771 * On POSIX systems, an absolute file name is well-defined. It always
772 * starts from the single root directory. For example "/usr/local".
774 * On Windows, the concepts of current drive and drive-specific
775 * current directory introduce vagueness. This function interprets as
776 * an absolute file name one that either begins with a directory
777 * separator such as "\Users\tml" or begins with the root on a drive,
778 * for example "C:\Windows". The first case also includes UNC paths
779 * such as "\\myserver\docs\foo". In all cases, either slashes or
780 * backslashes are accepted.
782 * Note that a file name relative to the current drive root does not
783 * truly specify a file uniquely over time and across processes, as
784 * the current drive is a per-process value and can be changed.
786 * File names relative the current directory on some specific drive,
787 * such as "D:foo/bar", are not interpreted as absolute by this
788 * function, but they obviously are not relative to the normal current
789 * directory as returned by getcwd() or g_get_current_dir()
790 * either. Such paths should be avoided, or need to be handled using
791 * Windows-specific code.
793 * Returns: %TRUE if @file_name is absolute.
796 g_path_is_absolute (const gchar *file_name)
798 g_return_val_if_fail (file_name != NULL, FALSE);
800 if (G_IS_DIR_SEPARATOR (file_name[0]))
804 /* Recognize drive letter on native Windows */
805 if (g_ascii_isalpha (file_name[0]) &&
806 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
808 #endif /* G_OS_WIN32 */
815 * @file_name: a file name.
817 * Returns a pointer into @file_name after the root component, i.e. after
818 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
819 * path it returns %NULL.
821 * Returns: a pointer into @file_name after the root component.
824 g_path_skip_root (const gchar *file_name)
826 g_return_val_if_fail (file_name != NULL, NULL);
828 #ifdef G_PLATFORM_WIN32
829 /* Skip \\server\share or //server/share */
830 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
831 G_IS_DIR_SEPARATOR (file_name[1]) &&
833 !G_IS_DIR_SEPARATOR (file_name[2]))
837 p = strchr (file_name + 2, G_DIR_SEPARATOR);
840 gchar *q = strchr (file_name + 2, '/');
841 if (p == NULL || (q != NULL && q < p))
851 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
854 /* Possibly skip a backslash after the share name */
855 if (G_IS_DIR_SEPARATOR (file_name[0]))
858 return (gchar *)file_name;
863 /* Skip initial slashes */
864 if (G_IS_DIR_SEPARATOR (file_name[0]))
866 while (G_IS_DIR_SEPARATOR (file_name[0]))
868 return (gchar *)file_name;
873 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
874 return (gchar *)file_name + 3;
882 * @mask: a #gulong containing flags
883 * @nth_bit: the index of the bit to start the search from
885 * Find the position of the first bit set in @mask, searching
886 * from (but not including) @nth_bit upwards. Bits are numbered
887 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
888 * usually). To start searching from the 0th bit, set @nth_bit to -1.
890 * Returns: the index of the first bit set which is higher than @nth_bit
895 * @mask: a #gulong containing flags
896 * @nth_bit: the index of the bit to start the search from
898 * Find the position of the first bit set in @mask, searching
899 * from (but not including) @nth_bit downwards. Bits are numbered
900 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
901 * usually). To start searching from the last bit, set @nth_bit to
902 * -1 or GLIB_SIZEOF_LONG * 8.
904 * Returns: the index of the first bit set which is lower than @nth_bit
911 * Gets the number of bits used to hold @number,
912 * e.g. if @number is 4, 3 bits are needed.
914 * Returns: the number of bits used to hold @number
919 * @file_name: the name of the file
921 * Gets the directory components of a file name.
922 * If the file name has no directory components "." is returned.
923 * The returned string should be freed when no longer needed.
925 * Returns: the directory components of the file
927 * Deprecated: use g_path_get_dirname() instead
931 * g_path_get_dirname:
932 * @file_name: the name of the file.
934 * Gets the directory components of a file name. If the file name has no
935 * directory components "." is returned. The returned string should be
936 * freed when no longer needed.
938 * Returns: the directory components of the file.
941 g_path_get_dirname (const gchar *file_name)
943 register gchar *base;
946 g_return_val_if_fail (file_name != NULL, NULL);
948 base = strrchr (file_name, G_DIR_SEPARATOR);
951 gchar *q = strrchr (file_name, '/');
952 if (base == NULL || (q != NULL && q > base))
959 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
961 gchar drive_colon_dot[4];
963 drive_colon_dot[0] = file_name[0];
964 drive_colon_dot[1] = ':';
965 drive_colon_dot[2] = '.';
966 drive_colon_dot[3] = '\0';
968 return g_strdup (drive_colon_dot);
971 return g_strdup (".");
974 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
978 /* base points to the char before the last slash.
980 * In case file_name is the root of a drive (X:\) or a child of the
981 * root of a drive (X:\foo), include the slash.
983 * In case file_name is the root share of an UNC path
984 * (\\server\share), add a slash, returning \\server\share\ .
986 * In case file_name is a direct child of a share in an UNC path
987 * (\\server\share\foo), include the slash after the share name,
988 * returning \\server\share\ .
990 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
992 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
993 G_IS_DIR_SEPARATOR (file_name[1]) &&
995 !G_IS_DIR_SEPARATOR (file_name[2]) &&
996 base >= file_name + 2)
998 const gchar *p = file_name + 2;
999 while (*p && !G_IS_DIR_SEPARATOR (*p))
1003 len = (guint) strlen (file_name) + 1;
1004 base = g_new (gchar, len + 1);
1005 strcpy (base, file_name);
1006 base[len-1] = G_DIR_SEPARATOR;
1010 if (G_IS_DIR_SEPARATOR (*p))
1013 while (*p && !G_IS_DIR_SEPARATOR (*p))
1021 len = (guint) 1 + base - file_name;
1023 base = g_new (gchar, len + 1);
1024 g_memmove (base, file_name, len);
1031 * g_get_current_dir:
1033 * Gets the current directory.
1034 * The returned string should be freed when no longer needed. The encoding
1035 * of the returned string is system defined. On Windows, it is always UTF-8.
1037 * Returns: the current directory.
1040 g_get_current_dir (void)
1045 wchar_t dummy[2], *wdir;
1048 len = GetCurrentDirectoryW (2, dummy);
1049 wdir = g_new (wchar_t, len);
1051 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1052 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1057 dir = g_strdup ("\\");
1063 gchar *buffer = NULL;
1065 static gulong max_len = 0;
1068 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1070 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1071 * and, if that wasn't bad enough, hangs in doing so.
1073 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1074 buffer = g_new (gchar, max_len + 1);
1076 dir = getwd (buffer);
1077 #else /* !sun || !HAVE_GETCWD */
1078 while (max_len < G_MAXULONG / 2)
1081 buffer = g_new (gchar, max_len + 1);
1083 dir = getcwd (buffer, max_len);
1085 if (dir || errno != ERANGE)
1090 #endif /* !sun || !HAVE_GETCWD */
1092 if (!dir || !*buffer)
1094 /* hm, should we g_error() out here?
1095 * this can happen if e.g. "./" has mode \0000
1097 buffer[0] = G_DIR_SEPARATOR;
1101 dir = g_strdup (buffer);
1110 * @variable: the environment variable to get, in the GLib file name encoding.
1112 * Returns the value of an environment variable. The name and value
1113 * are in the GLib file name encoding. On UNIX, this means the actual
1114 * bytes which might or might not be in some consistent character set
1115 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1116 * environment variable's value contains references to other
1117 * environment variables, they are expanded.
1119 * Return value: the value of the environment variable, or %NULL if
1120 * the environment variable is not found. The returned string may be
1121 * overwritten by the next call to g_getenv(), g_setenv() or
1125 g_getenv (const gchar *variable)
1129 g_return_val_if_fail (variable != NULL, NULL);
1131 return getenv (variable);
1133 #else /* G_OS_WIN32 */
1137 wchar_t dummy[2], *wname, *wvalue;
1140 g_return_val_if_fail (variable != NULL, NULL);
1141 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1143 /* On Windows NT, it is relatively typical that environment
1144 * variables contain references to other environment variables. If
1145 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1146 * environment variables would be stored in the Registry as
1147 * REG_EXPAND_SZ type values, and would then get automatically
1148 * expanded before a program sees them. But there is broken software
1149 * that stores environment variables as REG_SZ values even if they
1150 * contain references to other environment variables.)
1153 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1155 len = GetEnvironmentVariableW (wname, dummy, 2);
1165 wvalue = g_new (wchar_t, len);
1167 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1174 if (wcschr (wvalue, L'%') != NULL)
1176 wchar_t *tem = wvalue;
1178 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1182 wvalue = g_new (wchar_t, len);
1184 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1194 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1199 quark = g_quark_from_string (value);
1202 return g_quark_to_string (quark);
1204 #endif /* G_OS_WIN32 */
1207 /* _g_getenv_nomalloc
1208 * this function does a getenv() without doing any kind of allocation
1209 * through glib. it's suitable for chars <= 127 only (both, for the
1210 * variable name and the contents) and for contents < 1024 chars in
1211 * length. also, it aliases "" to a NULL return value.
1214 _g_getenv_nomalloc (const gchar *variable,
1217 const gchar *retval = getenv (variable);
1218 if (retval && retval[0])
1220 gint l = strlen (retval);
1223 strncpy (buffer, retval, l);
1233 * @variable: the environment variable to set, must not contain '='.
1234 * @value: the value for to set the variable to.
1235 * @overwrite: whether to change the variable if it already exists.
1237 * Sets an environment variable. Both the variable's name and value
1238 * should be in the GLib file name encoding. On UNIX, this means that
1239 * they can be any sequence of bytes. On Windows, they should be in
1242 * Note that on some systems, when variables are overwritten, the memory
1243 * used for the previous variables and its value isn't reclaimed.
1246 * Environment variable handling in UNIX is not thread-safe, and your
1247 * program may crash if one thread calls g_setenv() while another
1248 * thread is calling getenv(). (And note that many functions, such as
1249 * gettext(), call getenv() internally.) This function is only safe to
1250 * use at the very start of your program, before creating any other
1251 * threads (or creating objects that create worker threads of their
1255 * Returns: %FALSE if the environment variable couldn't be set.
1260 g_setenv (const gchar *variable,
1271 g_return_val_if_fail (variable != NULL, FALSE);
1272 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1275 result = setenv (variable, value, overwrite);
1277 if (!overwrite && getenv (variable) != NULL)
1280 /* This results in a leak when you overwrite existing
1281 * settings. It would be fairly easy to fix this by keeping
1282 * our own parallel array or hash table.
1284 string = g_strconcat (variable, "=", value, NULL);
1285 result = putenv (string);
1289 #else /* G_OS_WIN32 */
1292 wchar_t *wname, *wvalue, *wassignment;
1295 g_return_val_if_fail (variable != NULL, FALSE);
1296 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1297 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1298 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1300 if (!overwrite && g_getenv (variable) != NULL)
1303 /* We want to (if possible) set both the environment variable copy
1304 * kept by the C runtime and the one kept by the system.
1306 * We can't use only the C runtime's putenv or _wputenv() as that
1307 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1308 * (with main() and not wmain()). In a "main()" app the C runtime
1309 * initializes the C runtime's environment table by converting the
1310 * real (wide char) environment variables to system codepage, thus
1311 * breaking those that aren't representable in the system codepage.
1313 * As the C runtime's putenv() will also set the system copy, we do
1314 * the putenv() first, then call SetEnvironmentValueW ourselves.
1317 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1318 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1319 tem = g_strconcat (variable, "=", value, NULL);
1320 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1323 _wputenv (wassignment);
1324 g_free (wassignment);
1326 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1333 #endif /* G_OS_WIN32 */
1336 #ifdef HAVE__NSGETENVIRON
1337 #define environ (*_NSGetEnviron())
1338 #elif !defined(G_OS_WIN32)
1340 /* According to the Single Unix Specification, environ is not in
1341 * any system header, although unistd.h often declares it.
1343 extern char **environ;
1348 * @variable: the environment variable to remove, must not contain '='.
1350 * Removes an environment variable from the environment.
1352 * Note that on some systems, when variables are overwritten, the memory
1353 * used for the previous variables and its value isn't reclaimed.
1356 * Environment variable handling in UNIX is not thread-safe, and your
1357 * program may crash if one thread calls g_unsetenv() while another
1358 * thread is calling getenv(). (And note that many functions, such as
1359 * gettext(), call getenv() internally.) This function is only safe to
1360 * use at the very start of your program, before creating any other
1361 * threads (or creating objects that create worker threads of their
1368 g_unsetenv (const gchar *variable)
1372 #ifdef HAVE_UNSETENV
1373 g_return_if_fail (variable != NULL);
1374 g_return_if_fail (strchr (variable, '=') == NULL);
1376 unsetenv (variable);
1377 #else /* !HAVE_UNSETENV */
1381 g_return_if_fail (variable != NULL);
1382 g_return_if_fail (strchr (variable, '=') == NULL);
1384 len = strlen (variable);
1386 /* Mess directly with the environ array.
1387 * This seems to be the only portable way to do this.
1389 * Note that we remove *all* environment entries for
1390 * the variable name, not just the first.
1395 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1403 #endif /* !HAVE_UNSETENV */
1405 #else /* G_OS_WIN32 */
1407 wchar_t *wname, *wassignment;
1410 g_return_if_fail (variable != NULL);
1411 g_return_if_fail (strchr (variable, '=') == NULL);
1412 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1414 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1415 tem = g_strconcat (variable, "=", NULL);
1416 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1419 _wputenv (wassignment);
1420 g_free (wassignment);
1422 SetEnvironmentVariableW (wname, NULL);
1426 #endif /* G_OS_WIN32 */
1432 * Gets the names of all variables set in the environment.
1434 * Returns: (array zero-terminated=1) (transfer full): a %NULL-terminated list of strings which must be freed
1435 * with g_strfreev().
1437 * Programs that want to be portable to Windows should typically use
1438 * this function and g_getenv() instead of using the environ array
1439 * from the C library directly. On Windows, the strings in the environ
1440 * array are in system codepage encoding, while in most of the typical
1441 * use cases for environment variables in GLib-using programs you want
1442 * the UTF-8 encoding that this function and g_getenv() provide.
1450 gchar **result, *eq;
1453 len = g_strv_length (environ);
1454 result = g_new0 (gchar *, len + 1);
1457 for (i = 0; i < len; i++)
1459 eq = strchr (environ[i], '=');
1461 result[j++] = g_strndup (environ[i], eq - environ[i]);
1468 gchar **result, *eq;
1472 p = (wchar_t *) GetEnvironmentStringsW ();
1478 q += wcslen (q) + 1;
1482 result = g_new0 (gchar *, len + 1);
1488 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1489 if (result[j] != NULL)
1491 eq = strchr (result[j], '=');
1492 if (eq && eq > result[j])
1500 q += wcslen (q) + 1;
1503 FreeEnvironmentStringsW (p);
1512 * Gets the list of environment variables for the current process. The
1513 * list is %NULL terminated and each item in the list is of the form
1516 * This is equivalent to direct access to the 'environ' global variable,
1519 * The return value is freshly allocated and it should be freed with
1520 * g_strfreev() when it is no longer needed.
1522 * Returns: (array zero-terminated=1) (transfer full): the list of environment variables
1527 g_get_environ (void)
1530 return g_strdupv (environ);
1536 strings = GetEnvironmentStringsW ();
1537 for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1538 result = g_new (char *, n + 1);
1539 for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1540 result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1541 FreeEnvironmentStringsW (strings);
1548 G_LOCK_DEFINE_STATIC (g_utils_global);
1550 static gchar *g_tmp_dir = NULL;
1551 static gchar *g_user_name = NULL;
1552 static gchar *g_real_name = NULL;
1553 static gchar *g_home_dir = NULL;
1554 static gchar *g_host_name = NULL;
1557 /* System codepage versions of the above, kept at file level so that they,
1558 * too, are produced only once.
1560 static gchar *g_tmp_dir_cp = NULL;
1561 static gchar *g_user_name_cp = NULL;
1562 static gchar *g_real_name_cp = NULL;
1563 static gchar *g_home_dir_cp = NULL;
1566 static gchar *g_user_data_dir = NULL;
1567 static gchar **g_system_data_dirs = NULL;
1568 static gchar *g_user_cache_dir = NULL;
1569 static gchar *g_user_config_dir = NULL;
1570 static gchar **g_system_config_dirs = NULL;
1572 static gchar **g_user_special_dirs = NULL;
1574 /* fifteen minutes of fame for everybody */
1575 #define G_USER_DIRS_EXPIRE 15 * 60
1580 get_special_folder (int csidl)
1582 wchar_t path[MAX_PATH+1];
1584 LPITEMIDLIST pidl = NULL;
1586 gchar *retval = NULL;
1588 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1591 b = SHGetPathFromIDListW (pidl, path);
1593 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1594 CoTaskMemFree (pidl);
1600 get_windows_directory_root (void)
1602 wchar_t wwindowsdir[MAX_PATH];
1604 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1606 /* Usually X:\Windows, but in terminal server environments
1607 * might be an UNC path, AFAIK.
1609 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1612 if (windowsdir == NULL)
1613 return g_strdup ("C:\\");
1615 p = (char *) g_path_skip_root (windowsdir);
1616 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1622 return g_strdup ("C:\\");
1627 /* HOLDS: g_utils_global_lock */
1629 g_get_any_init_do (void)
1631 gchar hostname[100];
1633 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1634 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1635 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1636 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1637 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1640 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1641 g_tmp_dir = get_windows_directory_root ();
1644 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1647 g_tmp_dir = g_strdup (P_tmpdir);
1648 k = strlen (g_tmp_dir);
1649 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1650 g_tmp_dir[k - 1] = '\0';
1654 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1656 g_tmp_dir = g_strdup ("/tmp");
1658 #endif /* !G_OS_WIN32 */
1661 /* We check $HOME first for Win32, though it is a last resort for Unix
1662 * where we prefer the results of getpwuid().
1664 g_home_dir = g_strdup (g_getenv ("HOME"));
1666 /* Only believe HOME if it is an absolute path and exists */
1669 if (!(g_path_is_absolute (g_home_dir) &&
1670 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1672 g_free (g_home_dir);
1677 /* In case HOME is Unix-style (it happens), convert it to
1683 while ((p = strchr (g_home_dir, '/')) != NULL)
1689 /* USERPROFILE is probably the closest equivalent to $HOME? */
1690 if (g_getenv ("USERPROFILE") != NULL)
1691 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1695 g_home_dir = get_special_folder (CSIDL_PROFILE);
1698 g_home_dir = get_windows_directory_root ();
1699 #endif /* G_OS_WIN32 */
1703 struct passwd *pw = NULL;
1704 gpointer buffer = NULL;
1708 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1710 # ifdef _SC_GETPW_R_SIZE_MAX
1711 /* This reurns the maximum length */
1712 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1716 # else /* _SC_GETPW_R_SIZE_MAX */
1718 # endif /* _SC_GETPW_R_SIZE_MAX */
1720 logname = (gchar *) g_getenv ("LOGNAME");
1725 /* we allocate 6 extra bytes to work around a bug in
1726 * Mac OS < 10.3. See #156446
1728 buffer = g_malloc (bufsize + 6);
1731 # ifdef HAVE_POSIX_GETPWUID_R
1733 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1734 if (!pw || (pw->pw_uid != getuid ())) {
1735 /* LOGNAME is lying, fall back to looking up the uid */
1736 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1739 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1741 error = error < 0 ? errno : error;
1742 # else /* HAVE_NONPOSIX_GETPWUID_R */
1743 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1744 # if defined(_AIX) || defined(__hpux)
1745 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1746 pw = error == 0 ? &pwd : NULL;
1749 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1750 if (!pw || (pw->pw_uid != getuid ())) {
1751 /* LOGNAME is lying, fall back to looking up the uid */
1752 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1755 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1757 error = pw ? 0 : errno;
1759 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1763 /* we bail out prematurely if the user id can't be found
1764 * (should be pretty rare case actually), or if the buffer
1765 * should be sufficiently big and lookups are still not
1768 if (error == 0 || error == ENOENT)
1770 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1771 (gulong) getuid ());
1774 if (bufsize > 32 * 1024)
1776 g_warning ("getpwuid_r(): failed due to: %s.",
1777 g_strerror (error));
1785 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1790 pw = getpwuid (getuid ());
1795 g_user_name = g_strdup (pw->pw_name);
1797 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1799 gchar **gecos_fields;
1802 /* split the gecos field and substitute '&' */
1803 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1804 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1805 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1806 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1807 g_strfreev (gecos_fields);
1808 g_strfreev (name_parts);
1812 g_home_dir = g_strdup (pw->pw_dir);
1817 #else /* !HAVE_PWD_H */
1821 guint len = UNLEN+1;
1822 wchar_t buffer[UNLEN+1];
1824 if (GetUserNameW (buffer, (LPDWORD) &len))
1826 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1827 g_real_name = g_strdup (g_user_name);
1830 #endif /* G_OS_WIN32 */
1832 #endif /* !HAVE_PWD_H */
1836 g_home_dir = g_strdup (g_getenv ("HOME"));
1840 /* change '\\' in %HOME% to '/' */
1841 g_strdelimit (g_home_dir, "\\",'/');
1844 g_user_name = g_strdup ("somebody");
1846 g_real_name = g_strdup ("Unknown");
1850 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1852 DWORD size = sizeof (hostname);
1853 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1855 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1859 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1860 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1861 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1864 g_tmp_dir_cp = g_strdup ("\\");
1865 if (!g_user_name_cp)
1866 g_user_name_cp = g_strdup ("somebody");
1867 if (!g_real_name_cp)
1868 g_real_name_cp = g_strdup ("Unknown");
1870 /* home_dir might be NULL, unlike tmp_dir, user_name and
1874 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1876 g_home_dir_cp = NULL;
1877 #endif /* G_OS_WIN32 */
1881 g_get_any_init (void)
1884 g_get_any_init_do ();
1888 g_get_any_init_locked (void)
1890 G_LOCK (g_utils_global);
1892 G_UNLOCK (g_utils_global);
1899 * Gets the user name of the current user. The encoding of the returned
1900 * string is system-defined. On UNIX, it might be the preferred file name
1901 * encoding, or something else, and there is no guarantee that it is even
1902 * consistent on a machine. On Windows, it is always UTF-8.
1904 * Returns: the user name of the current user.
1907 g_get_user_name (void)
1909 g_get_any_init_locked ();
1916 * Gets the real name of the user. This usually comes from the user's entry
1917 * in the <filename>passwd</filename> file. The encoding of the returned
1918 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1919 * If the real user name cannot be determined, the string "Unknown" is
1922 * Returns: the user's real name.
1925 g_get_real_name (void)
1927 g_get_any_init_locked ();
1934 * Gets the current user's home directory as defined in the
1935 * password database.
1937 * Note that in contrast to traditional UNIX tools, this function
1938 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1939 * environment variable.
1941 * One of the reasons for this decision is that applications in many
1942 * cases need special handling to deal with the case where
1943 * <envar>HOME</envar> is
1945 * <member>Not owned by the user</member>
1946 * <member>Not writeable</member>
1947 * <member>Not even readable</member>
1949 * Since applications are in general <emphasis>not</emphasis> written
1950 * to deal with these situations it was considered better to make
1951 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1952 * return the real home directory for the user. If applications
1953 * want to pay attention to <envar>HOME</envar>, they can do:
1955 * const char *homedir = g_getenv ("HOME");
1957 * homedir = g_get_home_dir (<!-- -->);
1960 * Returns: the current user's home directory
1963 g_get_home_dir (void)
1965 g_get_any_init_locked ();
1972 * Gets the directory to use for temporary files. This is found from
1973 * inspecting the environment variables <envar>TMPDIR</envar>,
1974 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1975 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1976 * The encoding of the returned string is system-defined. On Windows,
1977 * it is always UTF-8. The return value is never %NULL or the empty string.
1979 * Returns: the directory to use for temporary files.
1982 g_get_tmp_dir (void)
1984 g_get_any_init_locked ();
1991 * Return a name for the machine.
1993 * The returned name is not necessarily a fully-qualified domain name,
1994 * or even present in DNS or some other name service at all. It need
1995 * not even be unique on your local network or site, but usually it
1996 * is. Callers should not rely on the return value having any specific
1997 * properties like uniqueness for security purposes. Even if the name
1998 * of the machine is changed while an application is running, the
1999 * return value from this function does not change. The returned
2000 * string is owned by GLib and should not be modified or freed. If no
2001 * name can be determined, a default fixed string "localhost" is
2004 * Returns: the host name of the machine.
2009 g_get_host_name (void)
2011 g_get_any_init_locked ();
2015 G_LOCK_DEFINE_STATIC (g_prgname);
2016 static gchar *g_prgname = NULL;
2021 * Gets the name of the program. This name should <emphasis>not</emphasis>
2022 * be localized, contrast with g_get_application_name().
2023 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
2024 * which is called by gtk_init(). The program name is found by taking
2025 * the last component of <literal>argv[0]</literal>.)
2027 * Returns: the name of the program. The returned string belongs
2028 * to GLib and must not be modified or freed.
2031 g_get_prgname (void)
2037 if (g_prgname == NULL)
2039 static gboolean beenhere = FALSE;
2043 gchar *utf8_buf = NULL;
2044 wchar_t buf[MAX_PATH+1];
2047 if (GetModuleFileNameW (GetModuleHandle (NULL),
2048 buf, G_N_ELEMENTS (buf)) > 0)
2049 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2053 g_prgname = g_path_get_basename (utf8_buf);
2060 G_UNLOCK (g_prgname);
2067 * @prgname: the name of the program.
2069 * Sets the name of the program. This name should <emphasis>not</emphasis>
2070 * be localized, contrast with g_set_application_name(). Note that for
2071 * thread-safety reasons this function can only be called once.
2074 g_set_prgname (const gchar *prgname)
2078 g_prgname = g_strdup (prgname);
2079 G_UNLOCK (g_prgname);
2082 G_LOCK_DEFINE_STATIC (g_application_name);
2083 static gchar *g_application_name = NULL;
2086 * g_get_application_name:
2088 * Gets a human-readable name for the application, as set by
2089 * g_set_application_name(). This name should be localized if
2090 * possible, and is intended for display to the user. Contrast with
2091 * g_get_prgname(), which gets a non-localized name. If
2092 * g_set_application_name() has not been called, returns the result of
2093 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2096 * Return value: human-readable application name. may return %NULL
2101 g_get_application_name (void)
2105 G_LOCK (g_application_name);
2106 retval = g_application_name;
2107 G_UNLOCK (g_application_name);
2110 return g_get_prgname ();
2116 * g_set_application_name:
2117 * @application_name: localized name of the application
2119 * Sets a human-readable name for the application. This name should be
2120 * localized if possible, and is intended for display to the user.
2121 * Contrast with g_set_prgname(), which sets a non-localized name.
2122 * g_set_prgname() will be called automatically by gtk_init(),
2123 * but g_set_application_name() will not.
2125 * Note that for thread safety reasons, this function can only
2128 * The application name will be used in contexts such as error messages,
2129 * or when displaying an application's name in the task list.
2134 g_set_application_name (const gchar *application_name)
2136 gboolean already_set = FALSE;
2138 G_LOCK (g_application_name);
2139 if (g_application_name)
2142 g_application_name = g_strdup (application_name);
2143 G_UNLOCK (g_application_name);
2146 g_warning ("g_set_application_name() called multiple times");
2150 * g_get_user_data_dir:
2152 * Returns a base directory in which to access application data such
2153 * as icons that is customized for a particular user.
2155 * On UNIX platforms this is determined using the mechanisms described in
2156 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2157 * XDG Base Directory Specification</ulink>.
2158 * In this case the directory retrieved will be XDG_DATA_HOME.
2160 * On Windows this is the folder to use for local (as opposed to
2161 * roaming) application data. See documentation for
2162 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2163 * what g_get_user_config_dir() returns.
2165 * Return value: a string owned by GLib that must not be modified
2170 g_get_user_data_dir (void)
2174 G_LOCK (g_utils_global);
2176 if (!g_user_data_dir)
2179 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2181 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2183 if (data_dir && data_dir[0])
2184 data_dir = g_strdup (data_dir);
2186 if (!data_dir || !data_dir[0])
2191 data_dir = g_build_filename (g_home_dir, ".local",
2194 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2198 g_user_data_dir = data_dir;
2201 data_dir = g_user_data_dir;
2203 G_UNLOCK (g_utils_global);
2209 g_init_user_config_dir (void)
2213 if (!g_user_config_dir)
2216 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2218 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2220 if (config_dir && config_dir[0])
2221 config_dir = g_strdup (config_dir);
2223 if (!config_dir || !config_dir[0])
2228 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2230 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2233 g_user_config_dir = config_dir;
2238 * g_get_user_config_dir:
2240 * Returns a base directory in which to store user-specific application
2241 * configuration information such as user preferences and settings.
2243 * On UNIX platforms this is determined using the mechanisms described in
2244 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2245 * XDG Base Directory Specification</ulink>.
2246 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2248 * On Windows this is the folder to use for local (as opposed to
2249 * roaming) application data. See documentation for
2250 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2251 * what g_get_user_data_dir() returns.
2253 * Return value: a string owned by GLib that must not be modified
2258 g_get_user_config_dir (void)
2260 G_LOCK (g_utils_global);
2262 g_init_user_config_dir ();
2264 G_UNLOCK (g_utils_global);
2266 return g_user_config_dir;
2270 * g_get_user_cache_dir:
2272 * Returns a base directory in which to store non-essential, cached
2273 * data specific to particular user.
2275 * On UNIX platforms this is determined using the mechanisms described in
2276 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2277 * XDG Base Directory Specification</ulink>.
2278 * In this case the directory retrieved will be XDG_CACHE_HOME.
2280 * On Windows is the directory that serves as a common repository for
2281 * temporary Internet files. A typical path is
2282 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2283 * See documentation for CSIDL_INTERNET_CACHE.
2285 * Return value: a string owned by GLib that must not be modified
2290 g_get_user_cache_dir (void)
2294 G_LOCK (g_utils_global);
2296 if (!g_user_cache_dir)
2299 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2301 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2303 if (cache_dir && cache_dir[0])
2304 cache_dir = g_strdup (cache_dir);
2306 if (!cache_dir || !cache_dir[0])
2311 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2313 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2315 g_user_cache_dir = cache_dir;
2318 cache_dir = g_user_cache_dir;
2320 G_UNLOCK (g_utils_global);
2326 * g_get_user_runtime_dir:
2328 * Returns a directory that is unique to the current user on the local
2331 * On UNIX platforms this is determined using the mechanisms described in
2332 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2333 * XDG Base Directory Specification</ulink>. This is the directory
2334 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2335 * In the case that this variable is not set, GLib will issue a warning
2336 * message to stderr and return the value of g_get_user_cache_dir().
2338 * On Windows this is the folder to use for local (as opposed to
2339 * roaming) application data. See documentation for
2340 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2341 * what g_get_user_config_dir() returns.
2343 * Returns: a string owned by GLib that must not be modified or freed.
2348 g_get_user_runtime_dir (void)
2351 static const gchar *runtime_dir;
2352 static gsize initialised;
2354 if (g_once_init_enter (&initialised))
2356 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2358 g_once_init_leave (&initialised, 1);
2364 /* Both fallback for UNIX and the default
2365 * in Windows: use the user cache directory.
2369 return g_get_user_cache_dir ();
2375 find_folder (OSType type)
2377 gchar *filename = NULL;
2380 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2382 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2386 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2390 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2394 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2396 CFStringGetCString (path, filename,
2397 CFStringGetLength (path) * 3 + 1,
2398 kCFStringEncodingUTF8);
2412 load_user_special_dirs (void)
2414 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2415 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2416 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2417 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2418 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2419 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2420 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2421 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2424 #endif /* HAVE_CARBON */
2426 #if defined(G_OS_WIN32)
2428 load_user_special_dirs (void)
2430 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2434 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2436 static const GUID FOLDERID_Downloads =
2437 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2438 static const GUID FOLDERID_Public =
2439 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2443 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2444 "SHGetKnownFolderPath");
2446 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2447 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2449 if (p_SHGetKnownFolderPath == NULL)
2451 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2456 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2459 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2460 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2461 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2462 CoTaskMemFree (wcp);
2465 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2468 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2469 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2471 if (p_SHGetKnownFolderPath == NULL)
2474 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2479 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2482 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2483 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2484 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2485 CoTaskMemFree (wcp);
2488 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2491 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2492 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2494 #endif /* G_OS_WIN32 */
2496 static void g_init_user_config_dir (void);
2498 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2500 /* adapted from xdg-user-dir-lookup.c
2502 * Copyright (C) 2007 Red Hat Inc.
2504 * Permission is hereby granted, free of charge, to any person
2505 * obtaining a copy of this software and associated documentation files
2506 * (the "Software"), to deal in the Software without restriction,
2507 * including without limitation the rights to use, copy, modify, merge,
2508 * publish, distribute, sublicense, and/or sell copies of the Software,
2509 * and to permit persons to whom the Software is furnished to do so,
2510 * subject to the following conditions:
2512 * The above copyright notice and this permission notice shall be
2513 * included in all copies or substantial portions of the Software.
2515 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2516 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2517 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2518 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2519 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2520 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2521 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2525 load_user_special_dirs (void)
2532 g_init_user_config_dir ();
2533 config_file = g_build_filename (g_user_config_dir,
2537 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2539 g_free (config_file);
2543 lines = g_strsplit (data, "\n", -1);
2544 n_lines = g_strv_length (lines);
2547 for (i = 0; i < n_lines; i++)
2549 gchar *buffer = lines[i];
2552 gboolean is_relative = FALSE;
2553 GUserDirectory directory;
2555 /* Remove newline at end */
2556 len = strlen (buffer);
2557 if (len > 0 && buffer[len - 1] == '\n')
2558 buffer[len - 1] = 0;
2561 while (*p == ' ' || *p == '\t')
2564 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2566 directory = G_USER_DIRECTORY_DESKTOP;
2567 p += strlen ("XDG_DESKTOP_DIR");
2569 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2571 directory = G_USER_DIRECTORY_DOCUMENTS;
2572 p += strlen ("XDG_DOCUMENTS_DIR");
2574 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2576 directory = G_USER_DIRECTORY_DOWNLOAD;
2577 p += strlen ("XDG_DOWNLOAD_DIR");
2579 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2581 directory = G_USER_DIRECTORY_MUSIC;
2582 p += strlen ("XDG_MUSIC_DIR");
2584 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2586 directory = G_USER_DIRECTORY_PICTURES;
2587 p += strlen ("XDG_PICTURES_DIR");
2589 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2591 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2592 p += strlen ("XDG_PUBLICSHARE_DIR");
2594 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2596 directory = G_USER_DIRECTORY_TEMPLATES;
2597 p += strlen ("XDG_TEMPLATES_DIR");
2599 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2601 directory = G_USER_DIRECTORY_VIDEOS;
2602 p += strlen ("XDG_VIDEOS_DIR");
2607 while (*p == ' ' || *p == '\t')
2614 while (*p == ' ' || *p == '\t')
2621 if (strncmp (p, "$HOME", 5) == 0)
2629 d = strrchr (p, '"');
2636 /* remove trailing slashes */
2638 if (d[len - 1] == '/')
2644 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2647 g_user_special_dirs[directory] = g_strdup (d);
2651 g_free (config_file);
2654 #endif /* G_OS_UNIX && !HAVE_CARBON */
2658 * g_reload_user_special_dirs_cache:
2660 * Resets the cache used for g_get_user_special_dir(), so
2661 * that the latest on-disk version is used. Call this only
2662 * if you just changed the data on disk yourself.
2664 * Due to threadsafety issues this may cause leaking of strings
2665 * that were previously returned from g_get_user_special_dir()
2666 * that can't be freed. We ensure to only leak the data for
2667 * the directories that actually changed value though.
2672 g_reload_user_special_dirs_cache (void)
2676 G_LOCK (g_utils_global);
2678 if (g_user_special_dirs != NULL)
2680 /* save a copy of the pointer, to check if some memory can be preserved */
2681 char **old_g_user_special_dirs = g_user_special_dirs;
2684 /* recreate and reload our cache */
2685 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2686 load_user_special_dirs ();
2688 /* only leak changed directories */
2689 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2691 old_val = old_g_user_special_dirs[i];
2692 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2695 g_free (g_user_special_dirs[i]);
2696 g_user_special_dirs[i] = old_val;
2702 /* free the old array */
2703 g_free (old_g_user_special_dirs);
2706 G_UNLOCK (g_utils_global);
2710 * g_get_user_special_dir:
2711 * @directory: the logical id of special directory
2713 * Returns the full path of a special directory using its logical id.
2715 * On Unix this is done using the XDG special user directories.
2716 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2717 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2718 * user directories have not been set up.
2720 * Depending on the platform, the user might be able to change the path
2721 * of the special directory without requiring the session to restart; GLib
2722 * will not reflect any change once the special directories are loaded.
2724 * Return value: the path to the specified special directory, or %NULL
2725 * if the logical id was not found. The returned string is owned by
2726 * GLib and should not be modified or freed.
2731 g_get_user_special_dir (GUserDirectory directory)
2733 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2734 directory < G_USER_N_DIRECTORIES, NULL);
2736 G_LOCK (g_utils_global);
2738 if (G_UNLIKELY (g_user_special_dirs == NULL))
2740 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2742 load_user_special_dirs ();
2744 /* Special-case desktop for historical compatibility */
2745 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2749 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2750 g_build_filename (g_home_dir, "Desktop", NULL);
2754 G_UNLOCK (g_utils_global);
2756 return g_user_special_dirs[directory];
2761 #undef g_get_system_data_dirs
2764 get_module_for_address (gconstpointer address)
2766 /* Holds the g_utils_global lock */
2768 static gboolean beenhere = FALSE;
2769 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2770 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2771 HMODULE hmodule = NULL;
2778 p_GetModuleHandleExA =
2779 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2780 "GetModuleHandleExA");
2784 if (p_GetModuleHandleExA == NULL ||
2785 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2786 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2789 MEMORY_BASIC_INFORMATION mbi;
2790 VirtualQuery (address, &mbi, sizeof (mbi));
2791 hmodule = (HMODULE) mbi.AllocationBase;
2798 get_module_share_dir (gconstpointer address)
2804 hmodule = get_module_for_address (address);
2805 if (hmodule == NULL)
2808 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2809 retval = g_build_filename (filename, "share", NULL);
2815 const gchar * const *
2816 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2820 static GHashTable *per_module_data_dirs = NULL;
2825 if (address_of_function)
2827 G_LOCK (g_utils_global);
2828 hmodule = get_module_for_address (address_of_function);
2829 if (hmodule != NULL)
2831 if (per_module_data_dirs == NULL)
2832 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2835 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2839 G_UNLOCK (g_utils_global);
2840 return (const gchar * const *) retval;
2846 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2848 /* Documents and Settings\All Users\Application Data */
2849 p = get_special_folder (CSIDL_COMMON_APPDATA);
2851 g_array_append_val (data_dirs, p);
2853 /* Documents and Settings\All Users\Documents */
2854 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2856 g_array_append_val (data_dirs, p);
2858 /* Using the above subfolders of Documents and Settings perhaps
2859 * makes sense from a Windows perspective.
2861 * But looking at the actual use cases of this function in GTK+
2862 * and GNOME software, what we really want is the "share"
2863 * subdirectory of the installation directory for the package
2864 * our caller is a part of.
2866 * The address_of_function parameter, if non-NULL, points to a
2867 * function in the calling module. Use that to determine that
2868 * module's installation folder, and use its "share" subfolder.
2870 * Additionally, also use the "share" subfolder of the installation
2871 * locations of GLib and the .exe file being run.
2873 * To guard against none of the above being what is really wanted,
2874 * callers of this function should have Win32-specific code to look
2875 * up their installation folder themselves, and handle a subfolder
2876 * "share" of it in the same way as the folders returned from this
2880 p = get_module_share_dir (address_of_function);
2882 g_array_append_val (data_dirs, p);
2884 if (glib_dll != NULL)
2886 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2887 p = g_build_filename (glib_root, "share", NULL);
2889 g_array_append_val (data_dirs, p);
2893 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2894 p = g_build_filename (exe_root, "share", NULL);
2896 g_array_append_val (data_dirs, p);
2899 retval = (gchar **) g_array_free (data_dirs, FALSE);
2901 if (address_of_function)
2903 if (hmodule != NULL)
2904 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2905 G_UNLOCK (g_utils_global);
2908 return (const gchar * const *) retval;
2914 * g_get_system_data_dirs:
2916 * Returns an ordered list of base directories in which to access
2917 * system-wide application data.
2919 * On UNIX platforms this is determined using the mechanisms described in
2920 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2921 * XDG Base Directory Specification</ulink>
2922 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2924 * On Windows the first elements in the list are the Application Data
2925 * and Documents folders for All Users. (These can be determined only
2926 * on Windows 2000 or later and are not present in the list on other
2927 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2928 * CSIDL_COMMON_DOCUMENTS.
2930 * Then follows the "share" subfolder in the installation folder for
2931 * the package containing the DLL that calls this function, if it can
2934 * Finally the list contains the "share" subfolder in the installation
2935 * folder for GLib, and in the installation folder for the package the
2936 * application's .exe file belongs to.
2938 * The installation folders above are determined by looking up the
2939 * folder where the module (DLL or EXE) in question is located. If the
2940 * folder's name is "bin", its parent is used, otherwise the folder
2943 * Note that on Windows the returned list can vary depending on where
2944 * this function is called.
2946 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2947 * not be modified or freed.
2950 const gchar * const *
2951 g_get_system_data_dirs (void)
2953 gchar **data_dir_vector;
2955 G_LOCK (g_utils_global);
2957 if (!g_system_data_dirs)
2960 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2962 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2964 if (!data_dirs || !data_dirs[0])
2965 data_dirs = "/usr/local/share/:/usr/share/";
2967 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2970 g_system_data_dirs = data_dir_vector;
2973 data_dir_vector = g_system_data_dirs;
2975 G_UNLOCK (g_utils_global);
2977 return (const gchar * const *) data_dir_vector;
2981 * g_get_system_config_dirs:
2983 * Returns an ordered list of base directories in which to access
2984 * system-wide configuration information.
2986 * On UNIX platforms this is determined using the mechanisms described in
2987 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2988 * XDG Base Directory Specification</ulink>.
2989 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2991 * On Windows is the directory that contains application data for all users.
2992 * A typical path is C:\Documents and Settings\All Users\Application Data.
2993 * This folder is used for application data that is not user specific.
2994 * For example, an application can store a spell-check dictionary, a database
2995 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2996 * This information will not roam and is available to anyone using the computer.
2998 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2999 * not be modified or freed.
3002 const gchar * const *
3003 g_get_system_config_dirs (void)
3005 gchar *conf_dirs, **conf_dir_vector;
3007 G_LOCK (g_utils_global);
3009 if (!g_system_config_dirs)
3012 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
3015 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3020 /* Return empty list */
3021 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
3024 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
3026 if (!conf_dirs || !conf_dirs[0])
3027 conf_dirs = "/etc/xdg";
3029 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3032 g_system_config_dirs = conf_dir_vector;
3035 conf_dir_vector = g_system_config_dirs;
3036 G_UNLOCK (g_utils_global);
3038 return (const gchar * const *) conf_dir_vector;
3043 static GHashTable *alias_table = NULL;
3045 /* read an alias file for the locales */
3047 read_aliases (gchar *file)
3053 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3054 fp = fopen (file,"r");
3057 while (fgets (buf, 256, fp))
3063 /* Line is a comment */
3064 if ((buf[0] == '#') || (buf[0] == '\0'))
3067 /* Reads first column */
3068 for (p = buf, q = NULL; *p; p++) {
3069 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3072 while ((*q == '\t') || (*q == ' ')) {
3078 /* The line only had one column */
3079 if (!q || *q == '\0')
3082 /* Read second column */
3083 for (p = q; *p; p++) {
3084 if ((*p == '\t') || (*p == ' ')) {
3090 /* Add to alias table if necessary */
3091 if (!g_hash_table_lookup (alias_table, buf)) {
3092 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3101 unalias_lang (char *lang)
3108 read_aliases ("/usr/share/locale/locale.alias");
3111 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3116 static gboolean said_before = FALSE;
3118 g_warning ("Too many alias levels for a locale, "
3119 "may indicate a loop");
3128 /* Mask for components of locale spec. The ordering here is from
3129 * least significant to most significant
3133 COMPONENT_CODESET = 1 << 0,
3134 COMPONENT_TERRITORY = 1 << 1,
3135 COMPONENT_MODIFIER = 1 << 2
3138 /* Break an X/Open style locale specification into components
3141 explode_locale (const gchar *locale,
3147 const gchar *uscore_pos;
3148 const gchar *at_pos;
3149 const gchar *dot_pos;
3153 uscore_pos = strchr (locale, '_');
3154 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3155 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3159 mask |= COMPONENT_MODIFIER;
3160 *modifier = g_strdup (at_pos);
3163 at_pos = locale + strlen (locale);
3167 mask |= COMPONENT_CODESET;
3168 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3175 mask |= COMPONENT_TERRITORY;
3176 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3179 uscore_pos = dot_pos;
3181 *language = g_strndup (locale, uscore_pos - locale);
3187 * Compute all interesting variants for a given locale name -
3188 * by stripping off different components of the value.
3190 * For simplicity, we assume that the locale is in
3191 * X/Open format: language[_territory][.codeset][@modifier]
3193 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3194 * as well. We could just copy the code from glibc wholesale
3195 * but it is big, ugly, and complicated, so I'm reluctant
3196 * to do so when this should handle 99% of the time...
3199 append_locale_variants (GPtrArray *array,
3200 const gchar *locale)
3202 gchar *language = NULL;
3203 gchar *territory = NULL;
3204 gchar *codeset = NULL;
3205 gchar *modifier = NULL;
3210 g_return_if_fail (locale != NULL);
3212 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3214 /* Iterate through all possible combinations, from least attractive
3215 * to most attractive.
3217 for (j = 0; j <= mask; ++j)
3221 if ((i & ~mask) == 0)
3223 gchar *val = g_strconcat (language,
3224 (i & COMPONENT_TERRITORY) ? territory : "",
3225 (i & COMPONENT_CODESET) ? codeset : "",
3226 (i & COMPONENT_MODIFIER) ? modifier : "",
3228 g_ptr_array_add (array, val);
3233 if (mask & COMPONENT_CODESET)
3235 if (mask & COMPONENT_TERRITORY)
3237 if (mask & COMPONENT_MODIFIER)
3242 * g_get_locale_variants:
3243 * @locale: a locale identifier
3245 * Returns a list of derived variants of @locale, which can be used to
3246 * e.g. construct locale-dependent filenames or search paths. The returned
3247 * list is sorted from most desirable to least desirable.
3248 * This function handles territory, charset and extra locale modifiers.
3250 * For example, if @locale is "fr_BE", then the returned list
3253 * If you need the list of variants for the <emphasis>current locale</emphasis>,
3254 * use g_get_language_names().
3256 * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
3257 * allocated array of newly allocated strings with the locale variants. Free with
3263 g_get_locale_variants (const gchar *locale)
3267 g_return_val_if_fail (locale != NULL, NULL);
3269 array = g_ptr_array_sized_new (8);
3270 append_locale_variants (array, locale);
3271 g_ptr_array_add (array, NULL);
3273 return (gchar **) g_ptr_array_free (array, FALSE);
3276 /* The following is (partly) taken from the gettext package.
3277 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3279 static const gchar *
3280 guess_category_value (const gchar *category_name)
3282 const gchar *retval;
3284 /* The highest priority value is the `LANGUAGE' environment
3285 variable. This is a GNU extension. */
3286 retval = g_getenv ("LANGUAGE");
3287 if ((retval != NULL) && (retval[0] != '\0'))
3290 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3291 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3292 systems this can be done by the `setlocale' function itself. */
3294 /* Setting of LC_ALL overwrites all other. */
3295 retval = g_getenv ("LC_ALL");
3296 if ((retval != NULL) && (retval[0] != '\0'))
3299 /* Next comes the name of the desired category. */
3300 retval = g_getenv (category_name);
3301 if ((retval != NULL) && (retval[0] != '\0'))
3304 /* Last possibility is the LANG environment variable. */
3305 retval = g_getenv ("LANG");
3306 if ((retval != NULL) && (retval[0] != '\0'))
3309 #ifdef G_PLATFORM_WIN32
3310 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3311 * LANG, which we already did above. Oh well. The main point of
3312 * calling g_win32_getlocale() is to get the thread's locale as used
3313 * by Windows and the Microsoft C runtime (in the "English_United
3314 * States" format) translated into the Unixish format.
3317 char *locale = g_win32_getlocale ();
3318 retval = g_intern_string (locale);
3327 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3329 struct _GLanguageNamesCache {
3331 gchar **language_names;
3335 language_names_cache_free (gpointer data)
3337 GLanguageNamesCache *cache = data;
3338 g_free (cache->languages);
3339 g_strfreev (cache->language_names);
3344 * g_get_language_names:
3346 * Computes a list of applicable locale names, which can be used to
3347 * e.g. construct locale-dependent filenames or search paths. The returned
3348 * list is sorted from most desirable to least desirable and always contains
3349 * the default locale "C".
3351 * For example, if LANGUAGE=de:en_US, then the returned list is
3352 * "de", "en_US", "en", "C".
3354 * This function consults the environment variables <envar>LANGUAGE</envar>,
3355 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3356 * to find the list of locales specified by the user.
3358 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
3359 * that must not be modified or freed.
3363 const gchar * const *
3364 g_get_language_names (void)
3366 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3367 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3372 cache = g_new0 (GLanguageNamesCache, 1);
3373 g_static_private_set (&cache_private, cache, language_names_cache_free);
3376 value = guess_category_value ("LC_MESSAGES");
3380 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3385 g_free (cache->languages);
3386 g_strfreev (cache->language_names);
3387 cache->languages = g_strdup (value);
3389 array = g_ptr_array_sized_new (8);
3391 alist = g_strsplit (value, ":", 0);
3392 for (a = alist; *a; a++)
3393 append_locale_variants (array, unalias_lang (*a));
3395 g_ptr_array_add (array, g_strdup ("C"));
3396 g_ptr_array_add (array, NULL);
3398 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3401 return (const gchar * const *) cache->language_names;
3405 * g_nullify_pointer:
3406 * @nullify_location: the memory address of the pointer.
3408 * Set the pointer at the specified location to %NULL.
3411 g_nullify_pointer (gpointer *nullify_location)
3413 g_return_if_fail (nullify_location != NULL);
3415 *nullify_location = NULL;
3421 * Get the codeset for the current locale.
3423 * Return value: a newly allocated string containing the name
3424 * of the codeset. This string must be freed with g_free().
3427 g_get_codeset (void)
3429 const gchar *charset;
3431 g_get_charset (&charset);
3433 return g_strdup (charset);
3439 * _glib_get_locale_dir:
3441 * Return the path to the share\locale or lib\locale subfolder of the
3442 * GLib installation folder. The path is in the system codepage. We
3443 * have to use system codepage as bindtextdomain() doesn't have a
3447 _glib_get_locale_dir (void)
3449 gchar *install_dir = NULL, *locale_dir;
3450 gchar *retval = NULL;
3452 if (glib_dll != NULL)
3453 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3458 * Append "/share/locale" or "/lib/locale" depending on whether
3459 * autoconfigury detected GNU gettext or not.
3461 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3467 locale_dir = g_build_filename (install_dir, p, NULL);
3469 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3471 g_free (install_dir);
3472 g_free (locale_dir);
3478 return g_strdup ("");
3481 #undef GLIB_LOCALE_DIR
3483 #endif /* G_OS_WIN32 */
3486 ensure_gettext_initialized (void)
3488 static gsize initialised;
3490 if (g_once_init_enter (&initialised))
3493 gchar *tmp = _glib_get_locale_dir ();
3494 bindtextdomain (GETTEXT_PACKAGE, tmp);
3497 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3499 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3500 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3502 g_once_init_leave (&initialised, TRUE);
3508 * @str: The string to be translated
3510 * Returns the translated string from the glib translations.
3511 * This is an internal function and should only be used by
3512 * the internals of glib (such as libgio).
3514 * Returns: the transation of @str to the current locale
3517 glib_gettext (const gchar *str)
3519 ensure_gettext_initialized();
3521 return g_dgettext (GETTEXT_PACKAGE, str);
3526 * @msgctxtid: a combined message context and message id, separated
3527 * by a \004 character
3528 * @msgidoffset: the offset of the message id in @msgctxid
3530 * This function is a variant of glib_gettext() which supports
3531 * a disambiguating message context. See g_dpgettext() for full
3534 * This is an internal function and should only be used by
3535 * the internals of glib (such as libgio).
3537 * Returns: the transation of @str to the current locale
3540 glib_pgettext(const gchar *msgctxtid,
3543 ensure_gettext_initialized();
3545 return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3548 #if defined (G_OS_WIN32) && !defined (_WIN64)
3550 /* Binary compatibility versions. Not for newly compiled code. */
3552 #undef g_find_program_in_path
3555 g_find_program_in_path (const gchar *program)
3557 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3558 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3561 g_free (utf8_program);
3562 if (utf8_retval == NULL)
3564 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3565 g_free (utf8_retval);
3570 #undef g_get_current_dir
3573 g_get_current_dir (void)
3575 gchar *utf8_dir = g_get_current_dir_utf8 ();
3576 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3584 g_getenv (const gchar *variable)
3586 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3587 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3591 g_free (utf8_variable);
3594 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3595 quark = g_quark_from_string (value);
3598 return g_quark_to_string (quark);
3604 g_setenv (const gchar *variable,
3608 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3609 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3610 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3612 g_free (utf8_variable);
3613 g_free (utf8_value);
3621 g_unsetenv (const gchar *variable)
3623 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3625 g_unsetenv_utf8 (utf8_variable);
3627 g_free (utf8_variable);
3630 #undef g_get_user_name
3633 g_get_user_name (void)
3635 g_get_any_init_locked ();
3636 return g_user_name_cp;
3639 #undef g_get_real_name
3642 g_get_real_name (void)
3644 g_get_any_init_locked ();
3645 return g_real_name_cp;
3648 #undef g_get_home_dir
3651 g_get_home_dir (void)
3653 g_get_any_init_locked ();
3654 return g_home_dir_cp;
3657 #undef g_get_tmp_dir
3660 g_get_tmp_dir (void)
3662 g_get_any_init_locked ();
3663 return g_tmp_dir_cp;