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);
665 debug_key_matches (const gchar *key,
669 /* may not call GLib functions: see note in g_parse_debug_string() */
670 for (; length; length--, key++, token++)
672 char k = (*key == '_') ? '-' : tolower (*key );
673 char t = (*token == '_') ? '-' : tolower (*token);
683 * g_parse_debug_string:
684 * @string: (allow-none): a list of debug options separated by colons, spaces, or
686 * @keys: (array length=nkeys): pointer to an array of #GDebugKey which associate
687 * strings with bit flags.
688 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
690 * Parses a string containing debugging options
691 * into a %guint containing bit flags. This is used
692 * within GDK and GTK+ to parse the debug options passed on the
693 * command line or through environment variables.
695 * If @string is equal to "all", all flags are set. If @string
696 * is equal to "help", all the available keys in @keys are printed
697 * out to standard error.
699 * Returns: the combined set of bit flags.
702 g_parse_debug_string (const gchar *string,
703 const GDebugKey *keys,
712 /* this function is used during the initialisation of gmessages, gmem
713 * and gslice, so it may not do anything that causes memory to be
714 * allocated or risks messages being emitted.
716 * this means, more or less, that this code may not call anything
720 if (!strcasecmp (string, "all"))
722 for (i=0; i<nkeys; i++)
723 result |= keys[i].value;
725 else if (!strcasecmp (string, "help"))
727 /* using stdio directly for the reason stated above */
728 fprintf (stderr, "Supported debug values: ");
729 for (i=0; i<nkeys; i++)
730 fprintf (stderr, " %s", keys[i].key);
731 fprintf (stderr, "\n");
735 const gchar *p = string;
740 q = strpbrk (p, ":;, \t");
744 for (i = 0; i < nkeys; i++)
745 if (debug_key_matches (keys[i].key, p, q - p))
746 result |= keys[i].value;
759 * @file_name: the name of the file.
761 * Gets the name of the file without any leading directory components.
762 * It returns a pointer into the given file name string.
764 * Return value: the name of the file without any leading directory components.
766 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
767 * g_path_get_basename() allocates new memory for the returned string, unlike
768 * this function which returns a pointer into the argument.
771 g_basename (const gchar *file_name)
773 register gchar *base;
775 g_return_val_if_fail (file_name != NULL, NULL);
777 base = strrchr (file_name, G_DIR_SEPARATOR);
781 gchar *q = strrchr (file_name, '/');
782 if (base == NULL || (q != NULL && q > base))
791 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
792 return (gchar*) file_name + 2;
793 #endif /* G_OS_WIN32 */
795 return (gchar*) file_name;
799 * g_path_get_basename:
800 * @file_name: the name of the file.
802 * Gets the last component of the filename. If @file_name ends with a
803 * directory separator it gets the component before the last slash. If
804 * @file_name consists only of directory separators (and on Windows,
805 * possibly a drive letter), a single separator is returned. If
806 * @file_name is empty, it gets ".".
808 * Return value: a newly allocated string containing the last component of
812 g_path_get_basename (const gchar *file_name)
814 register gssize base;
815 register gssize last_nonslash;
819 g_return_val_if_fail (file_name != NULL, NULL);
821 if (file_name[0] == '\0')
823 return g_strdup (".");
825 last_nonslash = strlen (file_name) - 1;
827 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
830 if (last_nonslash == -1)
831 /* string only containing slashes */
832 return g_strdup (G_DIR_SEPARATOR_S);
835 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
836 /* string only containing slashes and a drive */
837 return g_strdup (G_DIR_SEPARATOR_S);
838 #endif /* G_OS_WIN32 */
840 base = last_nonslash;
842 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
846 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
848 #endif /* G_OS_WIN32 */
850 len = last_nonslash - base;
851 retval = g_malloc (len + 1);
852 memcpy (retval, file_name + base + 1, len);
858 * g_path_is_absolute:
859 * @file_name: a file name.
861 * Returns %TRUE if the given @file_name is an absolute file name.
862 * Note that this is a somewhat vague concept on Windows.
864 * On POSIX systems, an absolute file name is well-defined. It always
865 * starts from the single root directory. For example "/usr/local".
867 * On Windows, the concepts of current drive and drive-specific
868 * current directory introduce vagueness. This function interprets as
869 * an absolute file name one that either begins with a directory
870 * separator such as "\Users\tml" or begins with the root on a drive,
871 * for example "C:\Windows". The first case also includes UNC paths
872 * such as "\\myserver\docs\foo". In all cases, either slashes or
873 * backslashes are accepted.
875 * Note that a file name relative to the current drive root does not
876 * truly specify a file uniquely over time and across processes, as
877 * the current drive is a per-process value and can be changed.
879 * File names relative the current directory on some specific drive,
880 * such as "D:foo/bar", are not interpreted as absolute by this
881 * function, but they obviously are not relative to the normal current
882 * directory as returned by getcwd() or g_get_current_dir()
883 * either. Such paths should be avoided, or need to be handled using
884 * Windows-specific code.
886 * Returns: %TRUE if @file_name is absolute.
889 g_path_is_absolute (const gchar *file_name)
891 g_return_val_if_fail (file_name != NULL, FALSE);
893 if (G_IS_DIR_SEPARATOR (file_name[0]))
897 /* Recognize drive letter on native Windows */
898 if (g_ascii_isalpha (file_name[0]) &&
899 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
901 #endif /* G_OS_WIN32 */
908 * @file_name: a file name.
910 * Returns a pointer into @file_name after the root component, i.e. after
911 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
912 * path it returns %NULL.
914 * Returns: a pointer into @file_name after the root component.
917 g_path_skip_root (const gchar *file_name)
919 g_return_val_if_fail (file_name != NULL, NULL);
921 #ifdef G_PLATFORM_WIN32
922 /* Skip \\server\share or //server/share */
923 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
924 G_IS_DIR_SEPARATOR (file_name[1]) &&
926 !G_IS_DIR_SEPARATOR (file_name[2]))
930 p = strchr (file_name + 2, G_DIR_SEPARATOR);
933 gchar *q = strchr (file_name + 2, '/');
934 if (p == NULL || (q != NULL && q < p))
944 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
947 /* Possibly skip a backslash after the share name */
948 if (G_IS_DIR_SEPARATOR (file_name[0]))
951 return (gchar *)file_name;
956 /* Skip initial slashes */
957 if (G_IS_DIR_SEPARATOR (file_name[0]))
959 while (G_IS_DIR_SEPARATOR (file_name[0]))
961 return (gchar *)file_name;
966 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
967 return (gchar *)file_name + 3;
975 * @mask: a #gulong containing flags
976 * @nth_bit: the index of the bit to start the search from
978 * Find the position of the first bit set in @mask, searching
979 * from (but not including) @nth_bit upwards. Bits are numbered
980 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
981 * usually). To start searching from the 0th bit, set @nth_bit to -1.
983 * Returns: the index of the first bit set which is higher than @nth_bit
988 * @mask: a #gulong containing flags
989 * @nth_bit: the index of the bit to start the search from
991 * Find the position of the first bit set in @mask, searching
992 * from (but not including) @nth_bit downwards. Bits are numbered
993 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
994 * usually). To start searching from the last bit, set @nth_bit to
995 * -1 or GLIB_SIZEOF_LONG * 8.
997 * Returns: the index of the first bit set which is lower than @nth_bit
1004 * Gets the number of bits used to hold @number,
1005 * e.g. if @number is 4, 3 bits are needed.
1007 * Returns: the number of bits used to hold @number
1012 * @file_name: the name of the file
1014 * Gets the directory components of a file name.
1015 * If the file name has no directory components "." is returned.
1016 * The returned string should be freed when no longer needed.
1018 * Returns: the directory components of the file
1020 * Deprecated: use g_path_get_dirname() instead
1024 * g_path_get_dirname:
1025 * @file_name: the name of the file.
1027 * Gets the directory components of a file name. If the file name has no
1028 * directory components "." is returned. The returned string should be
1029 * freed when no longer needed.
1031 * Returns: the directory components of the file.
1034 g_path_get_dirname (const gchar *file_name)
1036 register gchar *base;
1039 g_return_val_if_fail (file_name != NULL, NULL);
1041 base = strrchr (file_name, G_DIR_SEPARATOR);
1044 gchar *q = strrchr (file_name, '/');
1045 if (base == NULL || (q != NULL && q > base))
1052 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
1054 gchar drive_colon_dot[4];
1056 drive_colon_dot[0] = file_name[0];
1057 drive_colon_dot[1] = ':';
1058 drive_colon_dot[2] = '.';
1059 drive_colon_dot[3] = '\0';
1061 return g_strdup (drive_colon_dot);
1064 return g_strdup (".");
1067 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
1071 /* base points to the char before the last slash.
1073 * In case file_name is the root of a drive (X:\) or a child of the
1074 * root of a drive (X:\foo), include the slash.
1076 * In case file_name is the root share of an UNC path
1077 * (\\server\share), add a slash, returning \\server\share\ .
1079 * In case file_name is a direct child of a share in an UNC path
1080 * (\\server\share\foo), include the slash after the share name,
1081 * returning \\server\share\ .
1083 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
1085 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
1086 G_IS_DIR_SEPARATOR (file_name[1]) &&
1088 !G_IS_DIR_SEPARATOR (file_name[2]) &&
1089 base >= file_name + 2)
1091 const gchar *p = file_name + 2;
1092 while (*p && !G_IS_DIR_SEPARATOR (*p))
1096 len = (guint) strlen (file_name) + 1;
1097 base = g_new (gchar, len + 1);
1098 strcpy (base, file_name);
1099 base[len-1] = G_DIR_SEPARATOR;
1103 if (G_IS_DIR_SEPARATOR (*p))
1106 while (*p && !G_IS_DIR_SEPARATOR (*p))
1114 len = (guint) 1 + base - file_name;
1116 base = g_new (gchar, len + 1);
1117 g_memmove (base, file_name, len);
1124 * g_get_current_dir:
1126 * Gets the current directory.
1127 * The returned string should be freed when no longer needed. The encoding
1128 * of the returned string is system defined. On Windows, it is always UTF-8.
1130 * Returns: the current directory.
1133 g_get_current_dir (void)
1138 wchar_t dummy[2], *wdir;
1141 len = GetCurrentDirectoryW (2, dummy);
1142 wdir = g_new (wchar_t, len);
1144 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1145 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1150 dir = g_strdup ("\\");
1156 gchar *buffer = NULL;
1158 static gulong max_len = 0;
1161 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1163 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1164 * and, if that wasn't bad enough, hangs in doing so.
1166 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1167 buffer = g_new (gchar, max_len + 1);
1169 dir = getwd (buffer);
1170 #else /* !sun || !HAVE_GETCWD */
1171 while (max_len < G_MAXULONG / 2)
1174 buffer = g_new (gchar, max_len + 1);
1176 dir = getcwd (buffer, max_len);
1178 if (dir || errno != ERANGE)
1183 #endif /* !sun || !HAVE_GETCWD */
1185 if (!dir || !*buffer)
1187 /* hm, should we g_error() out here?
1188 * this can happen if e.g. "./" has mode \0000
1190 buffer[0] = G_DIR_SEPARATOR;
1194 dir = g_strdup (buffer);
1203 * @variable: the environment variable to get, in the GLib file name encoding.
1205 * Returns the value of an environment variable. The name and value
1206 * are in the GLib file name encoding. On UNIX, this means the actual
1207 * bytes which might or might not be in some consistent character set
1208 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1209 * environment variable's value contains references to other
1210 * environment variables, they are expanded.
1212 * Return value: the value of the environment variable, or %NULL if
1213 * the environment variable is not found. The returned string may be
1214 * overwritten by the next call to g_getenv(), g_setenv() or
1218 g_getenv (const gchar *variable)
1222 g_return_val_if_fail (variable != NULL, NULL);
1224 return getenv (variable);
1226 #else /* G_OS_WIN32 */
1230 wchar_t dummy[2], *wname, *wvalue;
1233 g_return_val_if_fail (variable != NULL, NULL);
1234 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1236 /* On Windows NT, it is relatively typical that environment
1237 * variables contain references to other environment variables. If
1238 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1239 * environment variables would be stored in the Registry as
1240 * REG_EXPAND_SZ type values, and would then get automatically
1241 * expanded before a program sees them. But there is broken software
1242 * that stores environment variables as REG_SZ values even if they
1243 * contain references to other environment variables.)
1246 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1248 len = GetEnvironmentVariableW (wname, dummy, 2);
1258 wvalue = g_new (wchar_t, len);
1260 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1267 if (wcschr (wvalue, L'%') != NULL)
1269 wchar_t *tem = wvalue;
1271 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1275 wvalue = g_new (wchar_t, len);
1277 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1287 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1292 quark = g_quark_from_string (value);
1295 return g_quark_to_string (quark);
1297 #endif /* G_OS_WIN32 */
1300 /* _g_getenv_nomalloc
1301 * this function does a getenv() without doing any kind of allocation
1302 * through glib. it's suitable for chars <= 127 only (both, for the
1303 * variable name and the contents) and for contents < 1024 chars in
1304 * length. also, it aliases "" to a NULL return value.
1307 _g_getenv_nomalloc (const gchar *variable,
1310 const gchar *retval = getenv (variable);
1311 if (retval && retval[0])
1313 gint l = strlen (retval);
1316 strncpy (buffer, retval, l);
1326 * @variable: the environment variable to set, must not contain '='.
1327 * @value: the value for to set the variable to.
1328 * @overwrite: whether to change the variable if it already exists.
1330 * Sets an environment variable. Both the variable's name and value
1331 * should be in the GLib file name encoding. On UNIX, this means that
1332 * they can be any sequence of bytes. On Windows, they should be in
1335 * Note that on some systems, when variables are overwritten, the memory
1336 * used for the previous variables and its value isn't reclaimed.
1339 * Environment variable handling in UNIX is not thread-safe, and your
1340 * program may crash if one thread calls g_setenv() while another
1341 * thread is calling getenv(). (And note that many functions, such as
1342 * gettext(), call getenv() internally.) This function is only safe to
1343 * use at the very start of your program, before creating any other
1344 * threads (or creating objects that create worker threads of their
1348 * Returns: %FALSE if the environment variable couldn't be set.
1353 g_setenv (const gchar *variable,
1364 g_return_val_if_fail (variable != NULL, FALSE);
1365 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1368 result = setenv (variable, value, overwrite);
1370 if (!overwrite && getenv (variable) != NULL)
1373 /* This results in a leak when you overwrite existing
1374 * settings. It would be fairly easy to fix this by keeping
1375 * our own parallel array or hash table.
1377 string = g_strconcat (variable, "=", value, NULL);
1378 result = putenv (string);
1382 #else /* G_OS_WIN32 */
1385 wchar_t *wname, *wvalue, *wassignment;
1388 g_return_val_if_fail (variable != NULL, FALSE);
1389 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1390 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1391 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1393 if (!overwrite && g_getenv (variable) != NULL)
1396 /* We want to (if possible) set both the environment variable copy
1397 * kept by the C runtime and the one kept by the system.
1399 * We can't use only the C runtime's putenv or _wputenv() as that
1400 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1401 * (with main() and not wmain()). In a "main()" app the C runtime
1402 * initializes the C runtime's environment table by converting the
1403 * real (wide char) environment variables to system codepage, thus
1404 * breaking those that aren't representable in the system codepage.
1406 * As the C runtime's putenv() will also set the system copy, we do
1407 * the putenv() first, then call SetEnvironmentValueW ourselves.
1410 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1411 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1412 tem = g_strconcat (variable, "=", value, NULL);
1413 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1416 _wputenv (wassignment);
1417 g_free (wassignment);
1419 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1426 #endif /* G_OS_WIN32 */
1429 #ifdef HAVE__NSGETENVIRON
1430 #define environ (*_NSGetEnviron())
1431 #elif !defined(G_OS_WIN32)
1433 /* According to the Single Unix Specification, environ is not in
1434 * any system header, although unistd.h often declares it.
1436 extern char **environ;
1441 * @variable: the environment variable to remove, must not contain '='.
1443 * Removes an environment variable from the environment.
1445 * Note that on some systems, when variables are overwritten, the memory
1446 * used for the previous variables and its value isn't reclaimed.
1449 * Environment variable handling in UNIX is not thread-safe, and your
1450 * program may crash if one thread calls g_unsetenv() while another
1451 * thread is calling getenv(). (And note that many functions, such as
1452 * gettext(), call getenv() internally.) This function is only safe to
1453 * use at the very start of your program, before creating any other
1454 * threads (or creating objects that create worker threads of their
1461 g_unsetenv (const gchar *variable)
1465 #ifdef HAVE_UNSETENV
1466 g_return_if_fail (variable != NULL);
1467 g_return_if_fail (strchr (variable, '=') == NULL);
1469 unsetenv (variable);
1470 #else /* !HAVE_UNSETENV */
1474 g_return_if_fail (variable != NULL);
1475 g_return_if_fail (strchr (variable, '=') == NULL);
1477 len = strlen (variable);
1479 /* Mess directly with the environ array.
1480 * This seems to be the only portable way to do this.
1482 * Note that we remove *all* environment entries for
1483 * the variable name, not just the first.
1488 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1496 #endif /* !HAVE_UNSETENV */
1498 #else /* G_OS_WIN32 */
1500 wchar_t *wname, *wassignment;
1503 g_return_if_fail (variable != NULL);
1504 g_return_if_fail (strchr (variable, '=') == NULL);
1505 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1507 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1508 tem = g_strconcat (variable, "=", NULL);
1509 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1512 _wputenv (wassignment);
1513 g_free (wassignment);
1515 SetEnvironmentVariableW (wname, NULL);
1519 #endif /* G_OS_WIN32 */
1525 * Gets the names of all variables set in the environment.
1527 * Returns: (array zero-terminated=1) (transfer full): a %NULL-terminated list of strings which must be freed
1528 * with g_strfreev().
1530 * Programs that want to be portable to Windows should typically use
1531 * this function and g_getenv() instead of using the environ array
1532 * from the C library directly. On Windows, the strings in the environ
1533 * array are in system codepage encoding, while in most of the typical
1534 * use cases for environment variables in GLib-using programs you want
1535 * the UTF-8 encoding that this function and g_getenv() provide.
1543 gchar **result, *eq;
1546 len = g_strv_length (environ);
1547 result = g_new0 (gchar *, len + 1);
1550 for (i = 0; i < len; i++)
1552 eq = strchr (environ[i], '=');
1554 result[j++] = g_strndup (environ[i], eq - environ[i]);
1561 gchar **result, *eq;
1565 p = (wchar_t *) GetEnvironmentStringsW ();
1571 q += wcslen (q) + 1;
1575 result = g_new0 (gchar *, len + 1);
1581 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1582 if (result[j] != NULL)
1584 eq = strchr (result[j], '=');
1585 if (eq && eq > result[j])
1593 q += wcslen (q) + 1;
1596 FreeEnvironmentStringsW (p);
1605 * Gets the list of environment variables for the current process. The
1606 * list is %NULL terminated and each item in the list is of the form
1609 * This is equivalent to direct access to the 'environ' global variable,
1612 * The return value is freshly allocated and it should be freed with
1613 * g_strfreev() when it is no longer needed.
1615 * Returns: (array zero-terminated=1) (transfer full): the list of environment variables
1620 g_get_environ (void)
1623 return g_strdupv (environ);
1629 strings = GetEnvironmentStringsW ();
1630 for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1631 result = g_new (char *, n + 1);
1632 for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1633 result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1634 FreeEnvironmentStringsW (strings);
1641 G_LOCK_DEFINE_STATIC (g_utils_global);
1643 static gchar *g_tmp_dir = NULL;
1644 static gchar *g_user_name = NULL;
1645 static gchar *g_real_name = NULL;
1646 static gchar *g_home_dir = NULL;
1647 static gchar *g_host_name = NULL;
1650 /* System codepage versions of the above, kept at file level so that they,
1651 * too, are produced only once.
1653 static gchar *g_tmp_dir_cp = NULL;
1654 static gchar *g_user_name_cp = NULL;
1655 static gchar *g_real_name_cp = NULL;
1656 static gchar *g_home_dir_cp = NULL;
1659 static gchar *g_user_data_dir = NULL;
1660 static gchar **g_system_data_dirs = NULL;
1661 static gchar *g_user_cache_dir = NULL;
1662 static gchar *g_user_config_dir = NULL;
1663 static gchar **g_system_config_dirs = NULL;
1665 static gchar **g_user_special_dirs = NULL;
1667 /* fifteen minutes of fame for everybody */
1668 #define G_USER_DIRS_EXPIRE 15 * 60
1673 get_special_folder (int csidl)
1675 wchar_t path[MAX_PATH+1];
1677 LPITEMIDLIST pidl = NULL;
1679 gchar *retval = NULL;
1681 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1684 b = SHGetPathFromIDListW (pidl, path);
1686 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1687 CoTaskMemFree (pidl);
1693 get_windows_directory_root (void)
1695 wchar_t wwindowsdir[MAX_PATH];
1697 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1699 /* Usually X:\Windows, but in terminal server environments
1700 * might be an UNC path, AFAIK.
1702 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1705 if (windowsdir == NULL)
1706 return g_strdup ("C:\\");
1708 p = (char *) g_path_skip_root (windowsdir);
1709 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1715 return g_strdup ("C:\\");
1720 /* HOLDS: g_utils_global_lock */
1722 g_get_any_init_do (void)
1724 gchar hostname[100];
1726 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1727 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1728 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1729 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1730 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1733 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1734 g_tmp_dir = get_windows_directory_root ();
1737 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1740 g_tmp_dir = g_strdup (P_tmpdir);
1741 k = strlen (g_tmp_dir);
1742 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1743 g_tmp_dir[k - 1] = '\0';
1747 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1749 g_tmp_dir = g_strdup ("/tmp");
1751 #endif /* !G_OS_WIN32 */
1754 /* We check $HOME first for Win32, though it is a last resort for Unix
1755 * where we prefer the results of getpwuid().
1757 g_home_dir = g_strdup (g_getenv ("HOME"));
1759 /* Only believe HOME if it is an absolute path and exists */
1762 if (!(g_path_is_absolute (g_home_dir) &&
1763 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1765 g_free (g_home_dir);
1770 /* In case HOME is Unix-style (it happens), convert it to
1776 while ((p = strchr (g_home_dir, '/')) != NULL)
1782 /* USERPROFILE is probably the closest equivalent to $HOME? */
1783 if (g_getenv ("USERPROFILE") != NULL)
1784 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1788 g_home_dir = get_special_folder (CSIDL_PROFILE);
1791 g_home_dir = get_windows_directory_root ();
1792 #endif /* G_OS_WIN32 */
1796 struct passwd *pw = NULL;
1797 gpointer buffer = NULL;
1801 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1803 # ifdef _SC_GETPW_R_SIZE_MAX
1804 /* This reurns the maximum length */
1805 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1809 # else /* _SC_GETPW_R_SIZE_MAX */
1811 # endif /* _SC_GETPW_R_SIZE_MAX */
1813 logname = (gchar *) g_getenv ("LOGNAME");
1818 /* we allocate 6 extra bytes to work around a bug in
1819 * Mac OS < 10.3. See #156446
1821 buffer = g_malloc (bufsize + 6);
1824 # ifdef HAVE_POSIX_GETPWUID_R
1826 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1827 if (!pw || (pw->pw_uid != getuid ())) {
1828 /* LOGNAME is lying, fall back to looking up the uid */
1829 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1832 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1834 error = error < 0 ? errno : error;
1835 # else /* HAVE_NONPOSIX_GETPWUID_R */
1836 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1837 # if defined(_AIX) || defined(__hpux)
1838 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1839 pw = error == 0 ? &pwd : NULL;
1842 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1843 if (!pw || (pw->pw_uid != getuid ())) {
1844 /* LOGNAME is lying, fall back to looking up the uid */
1845 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1848 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1850 error = pw ? 0 : errno;
1852 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1856 /* we bail out prematurely if the user id can't be found
1857 * (should be pretty rare case actually), or if the buffer
1858 * should be sufficiently big and lookups are still not
1861 if (error == 0 || error == ENOENT)
1863 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1864 (gulong) getuid ());
1867 if (bufsize > 32 * 1024)
1869 g_warning ("getpwuid_r(): failed due to: %s.",
1870 g_strerror (error));
1878 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1883 pw = getpwuid (getuid ());
1888 g_user_name = g_strdup (pw->pw_name);
1890 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1892 gchar **gecos_fields;
1895 /* split the gecos field and substitute '&' */
1896 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1897 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1898 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1899 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1900 g_strfreev (gecos_fields);
1901 g_strfreev (name_parts);
1905 g_home_dir = g_strdup (pw->pw_dir);
1910 #else /* !HAVE_PWD_H */
1914 guint len = UNLEN+1;
1915 wchar_t buffer[UNLEN+1];
1917 if (GetUserNameW (buffer, (LPDWORD) &len))
1919 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1920 g_real_name = g_strdup (g_user_name);
1923 #endif /* G_OS_WIN32 */
1925 #endif /* !HAVE_PWD_H */
1929 g_home_dir = g_strdup (g_getenv ("HOME"));
1933 /* change '\\' in %HOME% to '/' */
1934 g_strdelimit (g_home_dir, "\\",'/');
1937 g_user_name = g_strdup ("somebody");
1939 g_real_name = g_strdup ("Unknown");
1943 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1945 DWORD size = sizeof (hostname);
1946 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1948 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1952 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1953 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1954 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1957 g_tmp_dir_cp = g_strdup ("\\");
1958 if (!g_user_name_cp)
1959 g_user_name_cp = g_strdup ("somebody");
1960 if (!g_real_name_cp)
1961 g_real_name_cp = g_strdup ("Unknown");
1963 /* home_dir might be NULL, unlike tmp_dir, user_name and
1967 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1969 g_home_dir_cp = NULL;
1970 #endif /* G_OS_WIN32 */
1974 g_get_any_init (void)
1977 g_get_any_init_do ();
1981 g_get_any_init_locked (void)
1983 G_LOCK (g_utils_global);
1985 G_UNLOCK (g_utils_global);
1992 * Gets the user name of the current user. The encoding of the returned
1993 * string is system-defined. On UNIX, it might be the preferred file name
1994 * encoding, or something else, and there is no guarantee that it is even
1995 * consistent on a machine. On Windows, it is always UTF-8.
1997 * Returns: the user name of the current user.
2000 g_get_user_name (void)
2002 g_get_any_init_locked ();
2009 * Gets the real name of the user. This usually comes from the user's entry
2010 * in the <filename>passwd</filename> file. The encoding of the returned
2011 * string is system-defined. (On Windows, it is, however, always UTF-8.)
2012 * If the real user name cannot be determined, the string "Unknown" is
2015 * Returns: the user's real name.
2018 g_get_real_name (void)
2020 g_get_any_init_locked ();
2027 * Gets the current user's home directory as defined in the
2028 * password database.
2030 * Note that in contrast to traditional UNIX tools, this function
2031 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
2032 * environment variable.
2034 * One of the reasons for this decision is that applications in many
2035 * cases need special handling to deal with the case where
2036 * <envar>HOME</envar> is
2038 * <member>Not owned by the user</member>
2039 * <member>Not writeable</member>
2040 * <member>Not even readable</member>
2042 * Since applications are in general <emphasis>not</emphasis> written
2043 * to deal with these situations it was considered better to make
2044 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
2045 * return the real home directory for the user. If applications
2046 * want to pay attention to <envar>HOME</envar>, they can do:
2048 * const char *homedir = g_getenv ("HOME");
2050 * homedir = g_get_home_dir (<!-- -->);
2053 * Returns: the current user's home directory
2056 g_get_home_dir (void)
2058 g_get_any_init_locked ();
2065 * Gets the directory to use for temporary files. This is found from
2066 * inspecting the environment variables <envar>TMPDIR</envar>,
2067 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
2068 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
2069 * The encoding of the returned string is system-defined. On Windows,
2070 * it is always UTF-8. The return value is never %NULL or the empty string.
2072 * Returns: the directory to use for temporary files.
2075 g_get_tmp_dir (void)
2077 g_get_any_init_locked ();
2084 * Return a name for the machine.
2086 * The returned name is not necessarily a fully-qualified domain name,
2087 * or even present in DNS or some other name service at all. It need
2088 * not even be unique on your local network or site, but usually it
2089 * is. Callers should not rely on the return value having any specific
2090 * properties like uniqueness for security purposes. Even if the name
2091 * of the machine is changed while an application is running, the
2092 * return value from this function does not change. The returned
2093 * string is owned by GLib and should not be modified or freed. If no
2094 * name can be determined, a default fixed string "localhost" is
2097 * Returns: the host name of the machine.
2102 g_get_host_name (void)
2104 g_get_any_init_locked ();
2108 G_LOCK_DEFINE_STATIC (g_prgname);
2109 static gchar *g_prgname = NULL;
2114 * Gets the name of the program. This name should <emphasis>not</emphasis>
2115 * be localized, contrast with g_get_application_name().
2116 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
2117 * which is called by gtk_init(). The program name is found by taking
2118 * the last component of <literal>argv[0]</literal>.)
2120 * Returns: the name of the program. The returned string belongs
2121 * to GLib and must not be modified or freed.
2124 g_get_prgname (void)
2130 if (g_prgname == NULL)
2132 static gboolean beenhere = FALSE;
2136 gchar *utf8_buf = NULL;
2137 wchar_t buf[MAX_PATH+1];
2140 if (GetModuleFileNameW (GetModuleHandle (NULL),
2141 buf, G_N_ELEMENTS (buf)) > 0)
2142 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2146 g_prgname = g_path_get_basename (utf8_buf);
2153 G_UNLOCK (g_prgname);
2160 * @prgname: the name of the program.
2162 * Sets the name of the program. This name should <emphasis>not</emphasis>
2163 * be localized, contrast with g_set_application_name(). Note that for
2164 * thread-safety reasons this function can only be called once.
2167 g_set_prgname (const gchar *prgname)
2171 g_prgname = g_strdup (prgname);
2172 G_UNLOCK (g_prgname);
2175 G_LOCK_DEFINE_STATIC (g_application_name);
2176 static gchar *g_application_name = NULL;
2179 * g_get_application_name:
2181 * Gets a human-readable name for the application, as set by
2182 * g_set_application_name(). This name should be localized if
2183 * possible, and is intended for display to the user. Contrast with
2184 * g_get_prgname(), which gets a non-localized name. If
2185 * g_set_application_name() has not been called, returns the result of
2186 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2189 * Return value: human-readable application name. may return %NULL
2194 g_get_application_name (void)
2198 G_LOCK (g_application_name);
2199 retval = g_application_name;
2200 G_UNLOCK (g_application_name);
2203 return g_get_prgname ();
2209 * g_set_application_name:
2210 * @application_name: localized name of the application
2212 * Sets a human-readable name for the application. This name should be
2213 * localized if possible, and is intended for display to the user.
2214 * Contrast with g_set_prgname(), which sets a non-localized name.
2215 * g_set_prgname() will be called automatically by gtk_init(),
2216 * but g_set_application_name() will not.
2218 * Note that for thread safety reasons, this function can only
2221 * The application name will be used in contexts such as error messages,
2222 * or when displaying an application's name in the task list.
2227 g_set_application_name (const gchar *application_name)
2229 gboolean already_set = FALSE;
2231 G_LOCK (g_application_name);
2232 if (g_application_name)
2235 g_application_name = g_strdup (application_name);
2236 G_UNLOCK (g_application_name);
2239 g_warning ("g_set_application_name() called multiple times");
2243 * g_get_user_data_dir:
2245 * Returns a base directory in which to access application data such
2246 * as icons that is customized for a particular user.
2248 * On UNIX platforms this is determined using the mechanisms described in
2249 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2250 * XDG Base Directory Specification</ulink>.
2251 * In this case the directory retrieved will be XDG_DATA_HOME.
2253 * On Windows this is the folder to use for local (as opposed to
2254 * roaming) application data. See documentation for
2255 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2256 * what g_get_user_config_dir() returns.
2258 * Return value: a string owned by GLib that must not be modified
2263 g_get_user_data_dir (void)
2267 G_LOCK (g_utils_global);
2269 if (!g_user_data_dir)
2272 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2274 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2276 if (data_dir && data_dir[0])
2277 data_dir = g_strdup (data_dir);
2279 if (!data_dir || !data_dir[0])
2284 data_dir = g_build_filename (g_home_dir, ".local",
2287 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2291 g_user_data_dir = data_dir;
2294 data_dir = g_user_data_dir;
2296 G_UNLOCK (g_utils_global);
2302 g_init_user_config_dir (void)
2306 if (!g_user_config_dir)
2309 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2311 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2313 if (config_dir && config_dir[0])
2314 config_dir = g_strdup (config_dir);
2316 if (!config_dir || !config_dir[0])
2321 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2323 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2326 g_user_config_dir = config_dir;
2331 * g_get_user_config_dir:
2333 * Returns a base directory in which to store user-specific application
2334 * configuration information such as user preferences and settings.
2336 * On UNIX platforms this is determined using the mechanisms described in
2337 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2338 * XDG Base Directory Specification</ulink>.
2339 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2341 * On Windows this is the folder to use for local (as opposed to
2342 * roaming) application data. See documentation for
2343 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2344 * what g_get_user_data_dir() returns.
2346 * Return value: a string owned by GLib that must not be modified
2351 g_get_user_config_dir (void)
2353 G_LOCK (g_utils_global);
2355 g_init_user_config_dir ();
2357 G_UNLOCK (g_utils_global);
2359 return g_user_config_dir;
2363 * g_get_user_cache_dir:
2365 * Returns a base directory in which to store non-essential, cached
2366 * data specific to particular user.
2368 * On UNIX platforms this is determined using the mechanisms described in
2369 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2370 * XDG Base Directory Specification</ulink>.
2371 * In this case the directory retrieved will be XDG_CACHE_HOME.
2373 * On Windows is the directory that serves as a common repository for
2374 * temporary Internet files. A typical path is
2375 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2376 * See documentation for CSIDL_INTERNET_CACHE.
2378 * Return value: a string owned by GLib that must not be modified
2383 g_get_user_cache_dir (void)
2387 G_LOCK (g_utils_global);
2389 if (!g_user_cache_dir)
2392 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2394 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2396 if (cache_dir && cache_dir[0])
2397 cache_dir = g_strdup (cache_dir);
2399 if (!cache_dir || !cache_dir[0])
2404 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2406 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2408 g_user_cache_dir = cache_dir;
2411 cache_dir = g_user_cache_dir;
2413 G_UNLOCK (g_utils_global);
2419 * g_get_user_runtime_dir:
2421 * Returns a directory that is unique to the current user on the local
2424 * On UNIX platforms this is determined using the mechanisms described in
2425 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2426 * XDG Base Directory Specification</ulink>. This is the directory
2427 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2428 * In the case that this variable is not set, GLib will issue a warning
2429 * message to stderr and return the value of g_get_user_cache_dir().
2431 * On Windows this is the folder to use for local (as opposed to
2432 * roaming) application data. See documentation for
2433 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2434 * what g_get_user_config_dir() returns.
2436 * Returns: a string owned by GLib that must not be modified or freed.
2441 g_get_user_runtime_dir (void)
2444 static const gchar *runtime_dir;
2445 static gsize initialised;
2447 if (g_once_init_enter (&initialised))
2449 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2451 g_once_init_leave (&initialised, 1);
2457 /* Both fallback for UNIX and the default
2458 * in Windows: use the user cache directory.
2462 return g_get_user_cache_dir ();
2468 find_folder (OSType type)
2470 gchar *filename = NULL;
2473 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2475 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2479 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2483 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2487 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2489 CFStringGetCString (path, filename,
2490 CFStringGetLength (path) * 3 + 1,
2491 kCFStringEncodingUTF8);
2505 load_user_special_dirs (void)
2507 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2508 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2509 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2510 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2511 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2512 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2513 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2514 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2517 #endif /* HAVE_CARBON */
2519 #if defined(G_OS_WIN32)
2521 load_user_special_dirs (void)
2523 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2527 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2529 static const GUID FOLDERID_Downloads =
2530 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2531 static const GUID FOLDERID_Public =
2532 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2536 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2537 "SHGetKnownFolderPath");
2539 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2540 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2542 if (p_SHGetKnownFolderPath == NULL)
2544 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2549 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2552 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2553 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2554 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2555 CoTaskMemFree (wcp);
2558 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2561 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2562 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2564 if (p_SHGetKnownFolderPath == NULL)
2567 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2572 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2575 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2576 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2577 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2578 CoTaskMemFree (wcp);
2581 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2584 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2585 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2587 #endif /* G_OS_WIN32 */
2589 static void g_init_user_config_dir (void);
2591 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2593 /* adapted from xdg-user-dir-lookup.c
2595 * Copyright (C) 2007 Red Hat Inc.
2597 * Permission is hereby granted, free of charge, to any person
2598 * obtaining a copy of this software and associated documentation files
2599 * (the "Software"), to deal in the Software without restriction,
2600 * including without limitation the rights to use, copy, modify, merge,
2601 * publish, distribute, sublicense, and/or sell copies of the Software,
2602 * and to permit persons to whom the Software is furnished to do so,
2603 * subject to the following conditions:
2605 * The above copyright notice and this permission notice shall be
2606 * included in all copies or substantial portions of the Software.
2608 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2609 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2610 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2611 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2612 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2613 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2614 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2618 load_user_special_dirs (void)
2625 g_init_user_config_dir ();
2626 config_file = g_build_filename (g_user_config_dir,
2630 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2632 g_free (config_file);
2636 lines = g_strsplit (data, "\n", -1);
2637 n_lines = g_strv_length (lines);
2640 for (i = 0; i < n_lines; i++)
2642 gchar *buffer = lines[i];
2645 gboolean is_relative = FALSE;
2646 GUserDirectory directory;
2648 /* Remove newline at end */
2649 len = strlen (buffer);
2650 if (len > 0 && buffer[len - 1] == '\n')
2651 buffer[len - 1] = 0;
2654 while (*p == ' ' || *p == '\t')
2657 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2659 directory = G_USER_DIRECTORY_DESKTOP;
2660 p += strlen ("XDG_DESKTOP_DIR");
2662 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2664 directory = G_USER_DIRECTORY_DOCUMENTS;
2665 p += strlen ("XDG_DOCUMENTS_DIR");
2667 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2669 directory = G_USER_DIRECTORY_DOWNLOAD;
2670 p += strlen ("XDG_DOWNLOAD_DIR");
2672 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2674 directory = G_USER_DIRECTORY_MUSIC;
2675 p += strlen ("XDG_MUSIC_DIR");
2677 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2679 directory = G_USER_DIRECTORY_PICTURES;
2680 p += strlen ("XDG_PICTURES_DIR");
2682 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2684 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2685 p += strlen ("XDG_PUBLICSHARE_DIR");
2687 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2689 directory = G_USER_DIRECTORY_TEMPLATES;
2690 p += strlen ("XDG_TEMPLATES_DIR");
2692 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2694 directory = G_USER_DIRECTORY_VIDEOS;
2695 p += strlen ("XDG_VIDEOS_DIR");
2700 while (*p == ' ' || *p == '\t')
2707 while (*p == ' ' || *p == '\t')
2714 if (strncmp (p, "$HOME", 5) == 0)
2722 d = strrchr (p, '"');
2729 /* remove trailing slashes */
2731 if (d[len - 1] == '/')
2737 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2740 g_user_special_dirs[directory] = g_strdup (d);
2744 g_free (config_file);
2747 #endif /* G_OS_UNIX && !HAVE_CARBON */
2751 * g_reload_user_special_dirs_cache:
2753 * Resets the cache used for g_get_user_special_dir(), so
2754 * that the latest on-disk version is used. Call this only
2755 * if you just changed the data on disk yourself.
2757 * Due to threadsafety issues this may cause leaking of strings
2758 * that were previously returned from g_get_user_special_dir()
2759 * that can't be freed. We ensure to only leak the data for
2760 * the directories that actually changed value though.
2765 g_reload_user_special_dirs_cache (void)
2769 G_LOCK (g_utils_global);
2771 if (g_user_special_dirs != NULL)
2773 /* save a copy of the pointer, to check if some memory can be preserved */
2774 char **old_g_user_special_dirs = g_user_special_dirs;
2777 /* recreate and reload our cache */
2778 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2779 load_user_special_dirs ();
2781 /* only leak changed directories */
2782 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2784 old_val = old_g_user_special_dirs[i];
2785 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2788 g_free (g_user_special_dirs[i]);
2789 g_user_special_dirs[i] = old_val;
2795 /* free the old array */
2796 g_free (old_g_user_special_dirs);
2799 G_UNLOCK (g_utils_global);
2803 * g_get_user_special_dir:
2804 * @directory: the logical id of special directory
2806 * Returns the full path of a special directory using its logical id.
2808 * On Unix this is done using the XDG special user directories.
2809 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2810 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2811 * user directories have not been set up.
2813 * Depending on the platform, the user might be able to change the path
2814 * of the special directory without requiring the session to restart; GLib
2815 * will not reflect any change once the special directories are loaded.
2817 * Return value: the path to the specified special directory, or %NULL
2818 * if the logical id was not found. The returned string is owned by
2819 * GLib and should not be modified or freed.
2824 g_get_user_special_dir (GUserDirectory directory)
2826 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2827 directory < G_USER_N_DIRECTORIES, NULL);
2829 G_LOCK (g_utils_global);
2831 if (G_UNLIKELY (g_user_special_dirs == NULL))
2833 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2835 load_user_special_dirs ();
2837 /* Special-case desktop for historical compatibility */
2838 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2842 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2843 g_build_filename (g_home_dir, "Desktop", NULL);
2847 G_UNLOCK (g_utils_global);
2849 return g_user_special_dirs[directory];
2854 #undef g_get_system_data_dirs
2857 get_module_for_address (gconstpointer address)
2859 /* Holds the g_utils_global lock */
2861 static gboolean beenhere = FALSE;
2862 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2863 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2864 HMODULE hmodule = NULL;
2871 p_GetModuleHandleExA =
2872 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2873 "GetModuleHandleExA");
2877 if (p_GetModuleHandleExA == NULL ||
2878 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2879 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2882 MEMORY_BASIC_INFORMATION mbi;
2883 VirtualQuery (address, &mbi, sizeof (mbi));
2884 hmodule = (HMODULE) mbi.AllocationBase;
2891 get_module_share_dir (gconstpointer address)
2897 hmodule = get_module_for_address (address);
2898 if (hmodule == NULL)
2901 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2902 retval = g_build_filename (filename, "share", NULL);
2908 const gchar * const *
2909 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2913 static GHashTable *per_module_data_dirs = NULL;
2918 if (address_of_function)
2920 G_LOCK (g_utils_global);
2921 hmodule = get_module_for_address (address_of_function);
2922 if (hmodule != NULL)
2924 if (per_module_data_dirs == NULL)
2925 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2928 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2932 G_UNLOCK (g_utils_global);
2933 return (const gchar * const *) retval;
2939 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2941 /* Documents and Settings\All Users\Application Data */
2942 p = get_special_folder (CSIDL_COMMON_APPDATA);
2944 g_array_append_val (data_dirs, p);
2946 /* Documents and Settings\All Users\Documents */
2947 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2949 g_array_append_val (data_dirs, p);
2951 /* Using the above subfolders of Documents and Settings perhaps
2952 * makes sense from a Windows perspective.
2954 * But looking at the actual use cases of this function in GTK+
2955 * and GNOME software, what we really want is the "share"
2956 * subdirectory of the installation directory for the package
2957 * our caller is a part of.
2959 * The address_of_function parameter, if non-NULL, points to a
2960 * function in the calling module. Use that to determine that
2961 * module's installation folder, and use its "share" subfolder.
2963 * Additionally, also use the "share" subfolder of the installation
2964 * locations of GLib and the .exe file being run.
2966 * To guard against none of the above being what is really wanted,
2967 * callers of this function should have Win32-specific code to look
2968 * up their installation folder themselves, and handle a subfolder
2969 * "share" of it in the same way as the folders returned from this
2973 p = get_module_share_dir (address_of_function);
2975 g_array_append_val (data_dirs, p);
2977 if (glib_dll != NULL)
2979 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2980 p = g_build_filename (glib_root, "share", NULL);
2982 g_array_append_val (data_dirs, p);
2986 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2987 p = g_build_filename (exe_root, "share", NULL);
2989 g_array_append_val (data_dirs, p);
2992 retval = (gchar **) g_array_free (data_dirs, FALSE);
2994 if (address_of_function)
2996 if (hmodule != NULL)
2997 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2998 G_UNLOCK (g_utils_global);
3001 return (const gchar * const *) retval;
3007 * g_get_system_data_dirs:
3009 * Returns an ordered list of base directories in which to access
3010 * system-wide application data.
3012 * On UNIX platforms this is determined using the mechanisms described in
3013 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
3014 * XDG Base Directory Specification</ulink>
3015 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
3017 * On Windows the first elements in the list are the Application Data
3018 * and Documents folders for All Users. (These can be determined only
3019 * on Windows 2000 or later and are not present in the list on other
3020 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
3021 * CSIDL_COMMON_DOCUMENTS.
3023 * Then follows the "share" subfolder in the installation folder for
3024 * the package containing the DLL that calls this function, if it can
3027 * Finally the list contains the "share" subfolder in the installation
3028 * folder for GLib, and in the installation folder for the package the
3029 * application's .exe file belongs to.
3031 * The installation folders above are determined by looking up the
3032 * folder where the module (DLL or EXE) in question is located. If the
3033 * folder's name is "bin", its parent is used, otherwise the folder
3036 * Note that on Windows the returned list can vary depending on where
3037 * this function is called.
3039 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
3040 * not be modified or freed.
3043 const gchar * const *
3044 g_get_system_data_dirs (void)
3046 gchar **data_dir_vector;
3048 G_LOCK (g_utils_global);
3050 if (!g_system_data_dirs)
3053 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
3055 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
3057 if (!data_dirs || !data_dirs[0])
3058 data_dirs = "/usr/local/share/:/usr/share/";
3060 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3063 g_system_data_dirs = data_dir_vector;
3066 data_dir_vector = g_system_data_dirs;
3068 G_UNLOCK (g_utils_global);
3070 return (const gchar * const *) data_dir_vector;
3074 * g_get_system_config_dirs:
3076 * Returns an ordered list of base directories in which to access
3077 * system-wide configuration information.
3079 * On UNIX platforms this is determined using the mechanisms described in
3080 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
3081 * XDG Base Directory Specification</ulink>.
3082 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
3084 * On Windows is the directory that contains application data for all users.
3085 * A typical path is C:\Documents and Settings\All Users\Application Data.
3086 * This folder is used for application data that is not user specific.
3087 * For example, an application can store a spell-check dictionary, a database
3088 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
3089 * This information will not roam and is available to anyone using the computer.
3091 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
3092 * not be modified or freed.
3095 const gchar * const *
3096 g_get_system_config_dirs (void)
3098 gchar *conf_dirs, **conf_dir_vector;
3100 G_LOCK (g_utils_global);
3102 if (!g_system_config_dirs)
3105 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
3108 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3113 /* Return empty list */
3114 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
3117 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
3119 if (!conf_dirs || !conf_dirs[0])
3120 conf_dirs = "/etc/xdg";
3122 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3125 g_system_config_dirs = conf_dir_vector;
3128 conf_dir_vector = g_system_config_dirs;
3129 G_UNLOCK (g_utils_global);
3131 return (const gchar * const *) conf_dir_vector;
3136 static GHashTable *alias_table = NULL;
3138 /* read an alias file for the locales */
3140 read_aliases (gchar *file)
3146 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3147 fp = fopen (file,"r");
3150 while (fgets (buf, 256, fp))
3156 /* Line is a comment */
3157 if ((buf[0] == '#') || (buf[0] == '\0'))
3160 /* Reads first column */
3161 for (p = buf, q = NULL; *p; p++) {
3162 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3165 while ((*q == '\t') || (*q == ' ')) {
3171 /* The line only had one column */
3172 if (!q || *q == '\0')
3175 /* Read second column */
3176 for (p = q; *p; p++) {
3177 if ((*p == '\t') || (*p == ' ')) {
3183 /* Add to alias table if necessary */
3184 if (!g_hash_table_lookup (alias_table, buf)) {
3185 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3194 unalias_lang (char *lang)
3201 read_aliases ("/usr/share/locale/locale.alias");
3204 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3209 static gboolean said_before = FALSE;
3211 g_warning ("Too many alias levels for a locale, "
3212 "may indicate a loop");
3221 /* Mask for components of locale spec. The ordering here is from
3222 * least significant to most significant
3226 COMPONENT_CODESET = 1 << 0,
3227 COMPONENT_TERRITORY = 1 << 1,
3228 COMPONENT_MODIFIER = 1 << 2
3231 /* Break an X/Open style locale specification into components
3234 explode_locale (const gchar *locale,
3240 const gchar *uscore_pos;
3241 const gchar *at_pos;
3242 const gchar *dot_pos;
3246 uscore_pos = strchr (locale, '_');
3247 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3248 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3252 mask |= COMPONENT_MODIFIER;
3253 *modifier = g_strdup (at_pos);
3256 at_pos = locale + strlen (locale);
3260 mask |= COMPONENT_CODESET;
3261 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3268 mask |= COMPONENT_TERRITORY;
3269 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3272 uscore_pos = dot_pos;
3274 *language = g_strndup (locale, uscore_pos - locale);
3280 * Compute all interesting variants for a given locale name -
3281 * by stripping off different components of the value.
3283 * For simplicity, we assume that the locale is in
3284 * X/Open format: language[_territory][.codeset][@modifier]
3286 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3287 * as well. We could just copy the code from glibc wholesale
3288 * but it is big, ugly, and complicated, so I'm reluctant
3289 * to do so when this should handle 99% of the time...
3292 append_locale_variants (GPtrArray *array,
3293 const gchar *locale)
3295 gchar *language = NULL;
3296 gchar *territory = NULL;
3297 gchar *codeset = NULL;
3298 gchar *modifier = NULL;
3303 g_return_if_fail (locale != NULL);
3305 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3307 /* Iterate through all possible combinations, from least attractive
3308 * to most attractive.
3310 for (j = 0; j <= mask; ++j)
3314 if ((i & ~mask) == 0)
3316 gchar *val = g_strconcat (language,
3317 (i & COMPONENT_TERRITORY) ? territory : "",
3318 (i & COMPONENT_CODESET) ? codeset : "",
3319 (i & COMPONENT_MODIFIER) ? modifier : "",
3321 g_ptr_array_add (array, val);
3326 if (mask & COMPONENT_CODESET)
3328 if (mask & COMPONENT_TERRITORY)
3330 if (mask & COMPONENT_MODIFIER)
3335 * g_get_locale_variants:
3336 * @locale: a locale identifier
3338 * Returns a list of derived variants of @locale, which can be used to
3339 * e.g. construct locale-dependent filenames or search paths. The returned
3340 * list is sorted from most desirable to least desirable.
3341 * This function handles territory, charset and extra locale modifiers.
3343 * For example, if @locale is "fr_BE", then the returned list
3346 * If you need the list of variants for the <emphasis>current locale</emphasis>,
3347 * use g_get_language_names().
3349 * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
3350 * allocated array of newly allocated strings with the locale variants. Free with
3356 g_get_locale_variants (const gchar *locale)
3360 g_return_val_if_fail (locale != NULL, NULL);
3362 array = g_ptr_array_sized_new (8);
3363 append_locale_variants (array, locale);
3364 g_ptr_array_add (array, NULL);
3366 return (gchar **) g_ptr_array_free (array, FALSE);
3369 /* The following is (partly) taken from the gettext package.
3370 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3372 static const gchar *
3373 guess_category_value (const gchar *category_name)
3375 const gchar *retval;
3377 /* The highest priority value is the `LANGUAGE' environment
3378 variable. This is a GNU extension. */
3379 retval = g_getenv ("LANGUAGE");
3380 if ((retval != NULL) && (retval[0] != '\0'))
3383 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3384 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3385 systems this can be done by the `setlocale' function itself. */
3387 /* Setting of LC_ALL overwrites all other. */
3388 retval = g_getenv ("LC_ALL");
3389 if ((retval != NULL) && (retval[0] != '\0'))
3392 /* Next comes the name of the desired category. */
3393 retval = g_getenv (category_name);
3394 if ((retval != NULL) && (retval[0] != '\0'))
3397 /* Last possibility is the LANG environment variable. */
3398 retval = g_getenv ("LANG");
3399 if ((retval != NULL) && (retval[0] != '\0'))
3402 #ifdef G_PLATFORM_WIN32
3403 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3404 * LANG, which we already did above. Oh well. The main point of
3405 * calling g_win32_getlocale() is to get the thread's locale as used
3406 * by Windows and the Microsoft C runtime (in the "English_United
3407 * States" format) translated into the Unixish format.
3410 char *locale = g_win32_getlocale ();
3411 retval = g_intern_string (locale);
3420 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3422 struct _GLanguageNamesCache {
3424 gchar **language_names;
3428 language_names_cache_free (gpointer data)
3430 GLanguageNamesCache *cache = data;
3431 g_free (cache->languages);
3432 g_strfreev (cache->language_names);
3437 * g_get_language_names:
3439 * Computes a list of applicable locale names, which can be used to
3440 * e.g. construct locale-dependent filenames or search paths. The returned
3441 * list is sorted from most desirable to least desirable and always contains
3442 * the default locale "C".
3444 * For example, if LANGUAGE=de:en_US, then the returned list is
3445 * "de", "en_US", "en", "C".
3447 * This function consults the environment variables <envar>LANGUAGE</envar>,
3448 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3449 * to find the list of locales specified by the user.
3451 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
3452 * that must not be modified or freed.
3456 const gchar * const *
3457 g_get_language_names (void)
3459 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3460 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3465 cache = g_new0 (GLanguageNamesCache, 1);
3466 g_static_private_set (&cache_private, cache, language_names_cache_free);
3469 value = guess_category_value ("LC_MESSAGES");
3473 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3478 g_free (cache->languages);
3479 g_strfreev (cache->language_names);
3480 cache->languages = g_strdup (value);
3482 array = g_ptr_array_sized_new (8);
3484 alist = g_strsplit (value, ":", 0);
3485 for (a = alist; *a; a++)
3486 append_locale_variants (array, unalias_lang (*a));
3488 g_ptr_array_add (array, g_strdup ("C"));
3489 g_ptr_array_add (array, NULL);
3491 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3494 return (const gchar * const *) cache->language_names;
3498 * g_nullify_pointer:
3499 * @nullify_location: the memory address of the pointer.
3501 * Set the pointer at the specified location to %NULL.
3504 g_nullify_pointer (gpointer *nullify_location)
3506 g_return_if_fail (nullify_location != NULL);
3508 *nullify_location = NULL;
3514 * Get the codeset for the current locale.
3516 * Return value: a newly allocated string containing the name
3517 * of the codeset. This string must be freed with g_free().
3520 g_get_codeset (void)
3522 const gchar *charset;
3524 g_get_charset (&charset);
3526 return g_strdup (charset);
3532 * _glib_get_locale_dir:
3534 * Return the path to the share\locale or lib\locale subfolder of the
3535 * GLib installation folder. The path is in the system codepage. We
3536 * have to use system codepage as bindtextdomain() doesn't have a
3540 _glib_get_locale_dir (void)
3542 gchar *install_dir = NULL, *locale_dir;
3543 gchar *retval = NULL;
3545 if (glib_dll != NULL)
3546 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3551 * Append "/share/locale" or "/lib/locale" depending on whether
3552 * autoconfigury detected GNU gettext or not.
3554 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3560 locale_dir = g_build_filename (install_dir, p, NULL);
3562 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3564 g_free (install_dir);
3565 g_free (locale_dir);
3571 return g_strdup ("");
3574 #undef GLIB_LOCALE_DIR
3576 #endif /* G_OS_WIN32 */
3579 ensure_gettext_initialized (void)
3581 static gsize initialised;
3583 g_thread_init_glib ();
3585 if (g_once_init_enter (&initialised))
3588 gchar *tmp = _glib_get_locale_dir ();
3589 bindtextdomain (GETTEXT_PACKAGE, tmp);
3592 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3594 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3595 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3597 g_once_init_leave (&initialised, TRUE);
3603 * @str: The string to be translated
3605 * Returns the translated string from the glib translations.
3606 * This is an internal function and should only be used by
3607 * the internals of glib (such as libgio).
3609 * Returns: the transation of @str to the current locale
3612 glib_gettext (const gchar *str)
3614 ensure_gettext_initialized();
3616 return g_dgettext (GETTEXT_PACKAGE, str);
3621 * @msgctxtid: a combined message context and message id, separated
3622 * by a \004 character
3623 * @msgidoffset: the offset of the message id in @msgctxid
3625 * This function is a variant of glib_gettext() which supports
3626 * a disambiguating message context. See g_dpgettext() for full
3629 * This is an internal function and should only be used by
3630 * the internals of glib (such as libgio).
3632 * Returns: the transation of @str to the current locale
3635 glib_pgettext(const gchar *msgctxtid,
3638 ensure_gettext_initialized();
3640 return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3643 #if defined (G_OS_WIN32) && !defined (_WIN64)
3645 /* Binary compatibility versions. Not for newly compiled code. */
3647 #undef g_find_program_in_path
3650 g_find_program_in_path (const gchar *program)
3652 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3653 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3656 g_free (utf8_program);
3657 if (utf8_retval == NULL)
3659 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3660 g_free (utf8_retval);
3665 #undef g_get_current_dir
3668 g_get_current_dir (void)
3670 gchar *utf8_dir = g_get_current_dir_utf8 ();
3671 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3679 g_getenv (const gchar *variable)
3681 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3682 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3686 g_free (utf8_variable);
3689 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3690 quark = g_quark_from_string (value);
3693 return g_quark_to_string (quark);
3699 g_setenv (const gchar *variable,
3703 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3704 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3705 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3707 g_free (utf8_variable);
3708 g_free (utf8_value);
3716 g_unsetenv (const gchar *variable)
3718 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3720 g_unsetenv_utf8 (utf8_variable);
3722 g_free (utf8_variable);
3725 #undef g_get_user_name
3728 g_get_user_name (void)
3730 g_get_any_init_locked ();
3731 return g_user_name_cp;
3734 #undef g_get_real_name
3737 g_get_real_name (void)
3739 g_get_any_init_locked ();
3740 return g_real_name_cp;
3743 #undef g_get_home_dir
3746 g_get_home_dir (void)
3748 g_get_any_init_locked ();
3749 return g_home_dir_cp;
3752 #undef g_get_tmp_dir
3755 g_get_tmp_dir (void)
3757 g_get_any_init_locked ();
3758 return g_tmp_dir_cp;