1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
41 #include <ctype.h> /* For tolower() */
43 #include <sys/types.h>
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
52 #ifdef HAVE_CRT_EXTERNS_H
53 #include <crt_externs.h> /* for _NSGetEnviron */
56 /* implement gutils's inline functions
58 #define G_IMPLEMENT_INLINES 1
62 #include "gfileutils.h"
65 #include "gprintfint.h"
67 #include "gthreadprivate.h"
68 #include "gtestutils.h"
70 #include "gstrfuncs.h"
74 #ifdef G_PLATFORM_WIN32
81 #define G_PATH_LENGTH MAXPATHLEN
82 #elif defined (PATH_MAX)
83 #define G_PATH_LENGTH PATH_MAX
84 #elif defined (_PC_PATH_MAX)
85 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
87 #define G_PATH_LENGTH 2048
90 #ifdef G_PLATFORM_WIN32
91 # define STRICT /* Strict typing, please */
94 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
95 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
96 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
98 # include <lmcons.h> /* For UNLEN */
99 #endif /* G_PLATFORM_WIN32 */
104 /* older SDK (e.g. msvc 5.0) does not have these*/
105 # ifndef CSIDL_MYMUSIC
106 # define CSIDL_MYMUSIC 13
108 # ifndef CSIDL_MYVIDEO
109 # define CSIDL_MYVIDEO 14
111 # ifndef CSIDL_INTERNET_CACHE
112 # define CSIDL_INTERNET_CACHE 32
114 # ifndef CSIDL_COMMON_APPDATA
115 # define CSIDL_COMMON_APPDATA 35
117 # ifndef CSIDL_MYPICTURES
118 # define CSIDL_MYPICTURES 0x27
120 # ifndef CSIDL_COMMON_DOCUMENTS
121 # define CSIDL_COMMON_DOCUMENTS 46
123 # ifndef CSIDL_PROFILE
124 # define CSIDL_PROFILE 40
126 # include <process.h>
130 #include <CoreServices/CoreServices.h>
134 #include <langinfo.h>
137 const guint glib_major_version = GLIB_MAJOR_VERSION;
138 const guint glib_minor_version = GLIB_MINOR_VERSION;
139 const guint glib_micro_version = GLIB_MICRO_VERSION;
140 const guint glib_interface_age = GLIB_INTERFACE_AGE;
141 const guint glib_binary_age = GLIB_BINARY_AGE;
143 #ifdef G_PLATFORM_WIN32
145 static HMODULE glib_dll = NULL;
150 DllMain (HINSTANCE hinstDLL,
154 if (fdwReason == DLL_PROCESS_ATTACH)
163 _glib_get_dll_directory (void)
167 wchar_t wc_fn[MAX_PATH];
170 if (glib_dll == NULL)
174 /* This code is different from that in
175 * g_win32_get_package_installation_directory_of_module() in that
176 * here we return the actual folder where the GLib DLL is. We don't
177 * do the check for it being in a "bin" or "lib" subfolder and then
178 * returning the parent of that.
180 * In a statically built GLib, glib_dll will be NULL and we will
181 * thus look up the application's .exe file's location.
183 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
186 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
188 p = strrchr (retval, G_DIR_SEPARATOR);
202 * glib_check_version:
203 * @required_major: the required major version.
204 * @required_minor: the required minor version.
205 * @required_micro: the required micro version.
207 * Checks that the GLib library in use is compatible with the
208 * given version. Generally you would pass in the constants
209 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
210 * as the three arguments to this function; that produces
211 * a check that the library in use is compatible with
212 * the version of GLib the application or module was compiled
215 * Compatibility is defined by two things: first the version
216 * of the running library is newer than the version
217 * @required_major.required_minor.@required_micro. Second
218 * the running library must be binary compatible with the
219 * version @required_major.required_minor.@required_micro
220 * (same major version.)
222 * Return value: %NULL if the GLib library is compatible with the
223 * given version, or a string describing the version mismatch.
224 * The returned string is owned by GLib and must not be modified
230 glib_check_version (guint required_major,
231 guint required_minor,
232 guint required_micro)
234 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
235 gint required_effective_micro = 100 * required_minor + required_micro;
237 if (required_major > GLIB_MAJOR_VERSION)
238 return "GLib version too old (major mismatch)";
239 if (required_major < GLIB_MAJOR_VERSION)
240 return "GLib version too new (major mismatch)";
241 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
242 return "GLib version too new (micro mismatch)";
243 if (required_effective_micro > glib_effective_micro)
244 return "GLib version too old (micro mismatch)";
248 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
251 * @dest: the destination address to copy the bytes to.
252 * @src: the source address to copy the bytes from.
253 * @len: the number of bytes to copy.
255 * Copies a block of memory @len bytes long, from @src to @dest.
256 * The source and destination areas may overlap.
258 * In order to use this function, you must include
259 * <filename>string.h</filename> yourself, because this macro will
260 * typically simply resolve to memmove() and GLib does not include
261 * <filename>string.h</filename> for you.
264 g_memmove (gpointer dest,
268 gchar* destptr = dest;
269 const gchar* srcptr = src;
270 if (src + len < dest || dest + len < src)
272 bcopy (src, dest, len);
275 else if (dest <= src)
278 *(destptr++) = *(srcptr++);
285 *(--destptr) = *(--srcptr);
288 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
296 * @func: (scope async): the function to call on normal program termination.
298 * Specifies a function to be called at normal program termination.
300 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
301 * macro that maps to a call to the atexit() function in the C
302 * library. This means that in case the code that calls g_atexit(),
303 * i.e. atexit(), is in a DLL, the function will be called when the
304 * DLL is detached from the program. This typically makes more sense
305 * than that the function is called when the GLib DLL is detached,
306 * which happened earlier when g_atexit() was a function in the GLib
309 * The behaviour of atexit() in the context of dynamically loaded
310 * modules is not formally specified and varies wildly.
312 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
313 * loaded module which is unloaded before the program terminates might
314 * well cause a crash at program exit.
316 * Some POSIX systems implement atexit() like Windows, and have each
317 * dynamically loaded module maintain an own atexit chain that is
318 * called when the module is unloaded.
320 * On other POSIX systems, before a dynamically loaded module is
321 * unloaded, the registered atexit functions (if any) residing in that
322 * module are called, regardless where the code that registered them
323 * resided. This is presumably the most robust approach.
325 * As can be seen from the above, for portability it's best to avoid
326 * calling g_atexit() (or atexit()) except in the main executable of a
330 g_atexit (GVoidFunc func)
333 const gchar *error = NULL;
335 /* keep this in sync with glib.h */
337 #ifdef G_NATIVE_ATEXIT
338 result = ATEXIT (func);
340 error = g_strerror (errno);
341 #elif defined (HAVE_ATEXIT)
342 # ifdef NeXT /* @#%@! NeXTStep */
343 result = !atexit ((void (*)(void)) func);
345 error = g_strerror (errno);
347 result = atexit ((void (*)(void)) func);
349 error = g_strerror (errno);
351 #elif defined (HAVE_ON_EXIT)
352 result = on_exit ((void (*)(int, void *)) func, NULL);
354 error = g_strerror (errno);
357 error = "no implementation";
358 #endif /* G_NATIVE_ATEXIT */
361 g_error ("Could not register atexit() function: %s", error);
364 /* Based on execvp() from GNU Libc.
365 * Some of this code is cut-and-pasted into gspawn.c
369 my_strchrnul (const gchar *str,
372 gchar *p = (gchar*)str;
373 while (*p && (*p != c))
381 static gchar *inner_find_program_in_path (const gchar *program);
384 g_find_program_in_path (const gchar *program)
386 const gchar *last_dot = strrchr (program, '.');
388 if (last_dot == NULL ||
389 strchr (last_dot, '\\') != NULL ||
390 strchr (last_dot, '/') != NULL)
392 const gint program_length = strlen (program);
393 gchar *pathext = g_build_path (";",
394 ".exe;.cmd;.bat;.com",
395 g_getenv ("PATHEXT"),
398 gchar *decorated_program;
404 gchar *q = my_strchrnul (p, ';');
406 decorated_program = g_malloc (program_length + (q-p) + 1);
407 memcpy (decorated_program, program, program_length);
408 memcpy (decorated_program+program_length, p, q-p);
409 decorated_program [program_length + (q-p)] = '\0';
411 retval = inner_find_program_in_path (decorated_program);
412 g_free (decorated_program);
420 } while (*p++ != '\0');
425 return inner_find_program_in_path (program);
431 * g_find_program_in_path:
432 * @program: a program name in the GLib file name encoding
434 * Locates the first executable named @program in the user's path, in the
435 * same way that execvp() would locate it. Returns an allocated string
436 * with the absolute path name, or %NULL if the program is not found in
437 * the path. If @program is already an absolute path, returns a copy of
438 * @program if @program exists and is executable, and %NULL otherwise.
440 * On Windows, if @program does not have a file type suffix, tries
441 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
442 * the <envar>PATHEXT</envar> environment variable.
444 * On Windows, it looks for the file in the same way as CreateProcess()
445 * would. This means first in the directory where the executing
446 * program was loaded from, then in the current directory, then in the
447 * Windows 32-bit system directory, then in the Windows directory, and
448 * finally in the directories in the <envar>PATH</envar> environment
449 * variable. If the program is found, the return value contains the
450 * full name including the type suffix.
452 * Return value: absolute path, or %NULL
456 inner_find_program_in_path (const gchar *program)
459 g_find_program_in_path (const gchar *program)
462 const gchar *path, *p;
463 gchar *name, *freeme;
465 const gchar *path_copy;
466 gchar *filename = NULL, *appdir = NULL;
467 gchar *sysdir = NULL, *windir = NULL;
469 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
475 g_return_val_if_fail (program != NULL, NULL);
477 /* If it is an absolute path, or a relative path including subdirectories,
478 * don't look in PATH.
480 if (g_path_is_absolute (program)
481 || strchr (program, G_DIR_SEPARATOR) != NULL
483 || strchr (program, '/') != NULL
487 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
488 !g_file_test (program, G_FILE_TEST_IS_DIR))
489 return g_strdup (program);
494 path = g_getenv ("PATH");
495 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
498 /* There is no `PATH' in the environment. The default
499 * search path in GNU libc is the current directory followed by
500 * the path `confstr' returns for `_CS_PATH'.
503 /* In GLib we put . last, for security, and don't use the
504 * unportable confstr(); UNIX98 does not actually specify
505 * what to search if PATH is unset. POSIX may, dunno.
508 path = "/bin:/usr/bin:.";
511 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
512 if (n > 0 && n < MAXPATHLEN)
513 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
515 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
516 if (n > 0 && n < MAXPATHLEN)
517 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
519 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
520 if (n > 0 && n < MAXPATHLEN)
521 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
525 appdir = g_path_get_dirname (filename);
529 path = g_strdup (path);
533 const gchar *tem = path;
534 path = g_strconcat (windir, ";", path, NULL);
535 g_free ((gchar *) tem);
541 const gchar *tem = path;
542 path = g_strconcat (sysdir, ";", path, NULL);
543 g_free ((gchar *) tem);
548 const gchar *tem = path;
549 path = g_strconcat (".;", path, NULL);
550 g_free ((gchar *) tem);
555 const gchar *tem = path;
556 path = g_strconcat (appdir, ";", path, NULL);
557 g_free ((gchar *) tem);
564 len = strlen (program) + 1;
565 pathlen = strlen (path);
566 freeme = name = g_malloc (pathlen + len + 1);
568 /* Copy the file name at the top, including '\0' */
569 memcpy (name + pathlen + 1, program, len);
570 name = name + pathlen;
571 /* And add the slash before the filename */
572 *name = G_DIR_SEPARATOR;
580 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
583 /* Two adjacent colons, or a colon at the beginning or the end
584 * of `PATH' means to search the current directory.
588 startp = memcpy (name - (p - path), path, p - path);
590 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
591 !g_file_test (startp, G_FILE_TEST_IS_DIR))
594 ret = g_strdup (startp);
597 g_free ((gchar *) path_copy);
602 while (*p++ != '\0');
606 g_free ((gchar *) path_copy);
613 debug_key_matches (const gchar *key,
617 for (; length; length--, key++, token++)
619 char k = (*key == '_') ? '-' : tolower (*key );
620 char t = (*token == '_') ? '-' : tolower (*token);
630 * g_parse_debug_string:
631 * @string: (allow-none): a list of debug options separated by colons, spaces, or
633 * @keys: (array length=nkeys): pointer to an array of #GDebugKey which associate
634 * strings with bit flags.
635 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
637 * Parses a string containing debugging options
638 * into a %guint containing bit flags. This is used
639 * within GDK and GTK+ to parse the debug options passed on the
640 * command line or through environment variables.
642 * If @string is equal to "all", all flags are set. If @string
643 * is equal to "help", all the available keys in @keys are printed
644 * out to standard error.
646 * Returns: the combined set of bit flags.
649 g_parse_debug_string (const gchar *string,
650 const GDebugKey *keys,
659 /* this function is used by gmem.c/gslice.c initialization code,
660 * so introducing malloc dependencies here would require adaptions
661 * of those code portions.
664 if (!g_ascii_strcasecmp (string, "all"))
666 for (i=0; i<nkeys; i++)
667 result |= keys[i].value;
669 else if (!g_ascii_strcasecmp (string, "help"))
671 /* using stdio directly for the reason stated above */
672 fprintf (stderr, "Supported debug values: ");
673 for (i=0; i<nkeys; i++)
674 fprintf (stderr, " %s", keys[i].key);
675 fprintf (stderr, "\n");
679 const gchar *p = string;
684 q = strpbrk (p, ":;, \t");
688 for (i = 0; i < nkeys; i++)
689 if (debug_key_matches (keys[i].key, p, q - p))
690 result |= keys[i].value;
703 * @file_name: the name of the file.
705 * Gets the name of the file without any leading directory components.
706 * It returns a pointer into the given file name string.
708 * Return value: the name of the file without any leading directory components.
710 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
711 * g_path_get_basename() allocates new memory for the returned string, unlike
712 * this function which returns a pointer into the argument.
714 G_CONST_RETURN gchar*
715 g_basename (const gchar *file_name)
717 register gchar *base;
719 g_return_val_if_fail (file_name != NULL, NULL);
721 base = strrchr (file_name, G_DIR_SEPARATOR);
725 gchar *q = strrchr (file_name, '/');
726 if (base == NULL || (q != NULL && q > base))
735 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
736 return (gchar*) file_name + 2;
737 #endif /* G_OS_WIN32 */
739 return (gchar*) file_name;
743 * g_path_get_basename:
744 * @file_name: the name of the file.
746 * Gets the last component of the filename. If @file_name ends with a
747 * directory separator it gets the component before the last slash. If
748 * @file_name consists only of directory separators (and on Windows,
749 * possibly a drive letter), a single separator is returned. If
750 * @file_name is empty, it gets ".".
752 * Return value: a newly allocated string containing the last component of
756 g_path_get_basename (const gchar *file_name)
758 register gssize base;
759 register gssize last_nonslash;
763 g_return_val_if_fail (file_name != NULL, NULL);
765 if (file_name[0] == '\0')
767 return g_strdup (".");
769 last_nonslash = strlen (file_name) - 1;
771 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
774 if (last_nonslash == -1)
775 /* string only containing slashes */
776 return g_strdup (G_DIR_SEPARATOR_S);
779 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
780 /* string only containing slashes and a drive */
781 return g_strdup (G_DIR_SEPARATOR_S);
782 #endif /* G_OS_WIN32 */
784 base = last_nonslash;
786 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
790 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
792 #endif /* G_OS_WIN32 */
794 len = last_nonslash - base;
795 retval = g_malloc (len + 1);
796 memcpy (retval, file_name + base + 1, len);
802 * g_path_is_absolute:
803 * @file_name: a file name.
805 * Returns %TRUE if the given @file_name is an absolute file name.
806 * Note that this is a somewhat vague concept on Windows.
808 * On POSIX systems, an absolute file name is well-defined. It always
809 * starts from the single root directory. For example "/usr/local".
811 * On Windows, the concepts of current drive and drive-specific
812 * current directory introduce vagueness. This function interprets as
813 * an absolute file name one that either begins with a directory
814 * separator such as "\Users\tml" or begins with the root on a drive,
815 * for example "C:\Windows". The first case also includes UNC paths
816 * such as "\\myserver\docs\foo". In all cases, either slashes or
817 * backslashes are accepted.
819 * Note that a file name relative to the current drive root does not
820 * truly specify a file uniquely over time and across processes, as
821 * the current drive is a per-process value and can be changed.
823 * File names relative the current directory on some specific drive,
824 * such as "D:foo/bar", are not interpreted as absolute by this
825 * function, but they obviously are not relative to the normal current
826 * directory as returned by getcwd() or g_get_current_dir()
827 * either. Such paths should be avoided, or need to be handled using
828 * Windows-specific code.
830 * Returns: %TRUE if @file_name is absolute.
833 g_path_is_absolute (const gchar *file_name)
835 g_return_val_if_fail (file_name != NULL, FALSE);
837 if (G_IS_DIR_SEPARATOR (file_name[0]))
841 /* Recognize drive letter on native Windows */
842 if (g_ascii_isalpha (file_name[0]) &&
843 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
845 #endif /* G_OS_WIN32 */
852 * @file_name: a file name.
854 * Returns a pointer into @file_name after the root component, i.e. after
855 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
856 * path it returns %NULL.
858 * Returns: a pointer into @file_name after the root component.
860 G_CONST_RETURN gchar*
861 g_path_skip_root (const gchar *file_name)
863 g_return_val_if_fail (file_name != NULL, NULL);
865 #ifdef G_PLATFORM_WIN32
866 /* Skip \\server\share or //server/share */
867 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
868 G_IS_DIR_SEPARATOR (file_name[1]) &&
870 !G_IS_DIR_SEPARATOR (file_name[2]))
874 p = strchr (file_name + 2, G_DIR_SEPARATOR);
877 gchar *q = strchr (file_name + 2, '/');
878 if (p == NULL || (q != NULL && q < p))
888 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
891 /* Possibly skip a backslash after the share name */
892 if (G_IS_DIR_SEPARATOR (file_name[0]))
895 return (gchar *)file_name;
900 /* Skip initial slashes */
901 if (G_IS_DIR_SEPARATOR (file_name[0]))
903 while (G_IS_DIR_SEPARATOR (file_name[0]))
905 return (gchar *)file_name;
910 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
911 return (gchar *)file_name + 3;
918 * g_path_get_dirname:
919 * @file_name: the name of the file.
921 * Gets the directory components of a file name. If the file name has no
922 * directory components "." is returned. The returned string should be
923 * freed when no longer needed.
925 * Returns: the directory components of the file.
928 g_path_get_dirname (const gchar *file_name)
930 register gchar *base;
933 g_return_val_if_fail (file_name != NULL, NULL);
935 base = strrchr (file_name, G_DIR_SEPARATOR);
938 gchar *q = strrchr (file_name, '/');
939 if (base == NULL || (q != NULL && q > base))
946 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
948 gchar drive_colon_dot[4];
950 drive_colon_dot[0] = file_name[0];
951 drive_colon_dot[1] = ':';
952 drive_colon_dot[2] = '.';
953 drive_colon_dot[3] = '\0';
955 return g_strdup (drive_colon_dot);
958 return g_strdup (".");
961 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
965 /* base points to the char before the last slash.
967 * In case file_name is the root of a drive (X:\) or a child of the
968 * root of a drive (X:\foo), include the slash.
970 * In case file_name is the root share of an UNC path
971 * (\\server\share), add a slash, returning \\server\share\ .
973 * In case file_name is a direct child of a share in an UNC path
974 * (\\server\share\foo), include the slash after the share name,
975 * returning \\server\share\ .
977 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
979 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
980 G_IS_DIR_SEPARATOR (file_name[1]) &&
982 !G_IS_DIR_SEPARATOR (file_name[2]) &&
983 base >= file_name + 2)
985 const gchar *p = file_name + 2;
986 while (*p && !G_IS_DIR_SEPARATOR (*p))
990 len = (guint) strlen (file_name) + 1;
991 base = g_new (gchar, len + 1);
992 strcpy (base, file_name);
993 base[len-1] = G_DIR_SEPARATOR;
997 if (G_IS_DIR_SEPARATOR (*p))
1000 while (*p && !G_IS_DIR_SEPARATOR (*p))
1008 len = (guint) 1 + base - file_name;
1010 base = g_new (gchar, len + 1);
1011 g_memmove (base, file_name, len);
1018 * g_get_current_dir:
1020 * Gets the current directory.
1021 * The returned string should be freed when no longer needed. The encoding
1022 * of the returned string is system defined. On Windows, it is always UTF-8.
1024 * Returns: the current directory.
1027 g_get_current_dir (void)
1032 wchar_t dummy[2], *wdir;
1035 len = GetCurrentDirectoryW (2, dummy);
1036 wdir = g_new (wchar_t, len);
1038 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1039 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1044 dir = g_strdup ("\\");
1050 gchar *buffer = NULL;
1052 static gulong max_len = 0;
1055 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1057 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1058 * and, if that wasn't bad enough, hangs in doing so.
1060 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1061 buffer = g_new (gchar, max_len + 1);
1063 dir = getwd (buffer);
1064 #else /* !sun || !HAVE_GETCWD */
1065 while (max_len < G_MAXULONG / 2)
1068 buffer = g_new (gchar, max_len + 1);
1070 dir = getcwd (buffer, max_len);
1072 if (dir || errno != ERANGE)
1077 #endif /* !sun || !HAVE_GETCWD */
1079 if (!dir || !*buffer)
1081 /* hm, should we g_error() out here?
1082 * this can happen if e.g. "./" has mode \0000
1084 buffer[0] = G_DIR_SEPARATOR;
1088 dir = g_strdup (buffer);
1097 * @variable: the environment variable to get, in the GLib file name encoding.
1099 * Returns the value of an environment variable. The name and value
1100 * are in the GLib file name encoding. On UNIX, this means the actual
1101 * bytes which might or might not be in some consistent character set
1102 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1103 * environment variable's value contains references to other
1104 * environment variables, they are expanded.
1106 * Return value: the value of the environment variable, or %NULL if
1107 * the environment variable is not found. The returned string may be
1108 * overwritten by the next call to g_getenv(), g_setenv() or
1111 G_CONST_RETURN gchar*
1112 g_getenv (const gchar *variable)
1116 g_return_val_if_fail (variable != NULL, NULL);
1118 return getenv (variable);
1120 #else /* G_OS_WIN32 */
1124 wchar_t dummy[2], *wname, *wvalue;
1127 g_return_val_if_fail (variable != NULL, NULL);
1128 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1130 /* On Windows NT, it is relatively typical that environment
1131 * variables contain references to other environment variables. If
1132 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1133 * environment variables would be stored in the Registry as
1134 * REG_EXPAND_SZ type values, and would then get automatically
1135 * expanded before a program sees them. But there is broken software
1136 * that stores environment variables as REG_SZ values even if they
1137 * contain references to other environment variables.)
1140 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1142 len = GetEnvironmentVariableW (wname, dummy, 2);
1152 wvalue = g_new (wchar_t, len);
1154 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1161 if (wcschr (wvalue, L'%') != NULL)
1163 wchar_t *tem = wvalue;
1165 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1169 wvalue = g_new (wchar_t, len);
1171 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1181 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1186 quark = g_quark_from_string (value);
1189 return g_quark_to_string (quark);
1191 #endif /* G_OS_WIN32 */
1194 /* _g_getenv_nomalloc
1195 * this function does a getenv() without doing any kind of allocation
1196 * through glib. it's suitable for chars <= 127 only (both, for the
1197 * variable name and the contents) and for contents < 1024 chars in
1198 * length. also, it aliases "" to a NULL return value.
1201 _g_getenv_nomalloc (const gchar *variable,
1204 const gchar *retval = getenv (variable);
1205 if (retval && retval[0])
1207 gint l = strlen (retval);
1210 strncpy (buffer, retval, l);
1220 * @variable: the environment variable to set, must not contain '='.
1221 * @value: the value for to set the variable to.
1222 * @overwrite: whether to change the variable if it already exists.
1224 * Sets an environment variable. Both the variable's name and value
1225 * should be in the GLib file name encoding. On UNIX, this means that
1226 * they can be any sequence of bytes. On Windows, they should be in
1229 * Note that on some systems, when variables are overwritten, the memory
1230 * used for the previous variables and its value isn't reclaimed.
1232 * Returns: %FALSE if the environment variable couldn't be set.
1237 g_setenv (const gchar *variable,
1248 g_return_val_if_fail (variable != NULL, FALSE);
1249 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1252 result = setenv (variable, value, overwrite);
1254 if (!overwrite && getenv (variable) != NULL)
1257 /* This results in a leak when you overwrite existing
1258 * settings. It would be fairly easy to fix this by keeping
1259 * our own parallel array or hash table.
1261 string = g_strconcat (variable, "=", value, NULL);
1262 result = putenv (string);
1266 #else /* G_OS_WIN32 */
1269 wchar_t *wname, *wvalue, *wassignment;
1272 g_return_val_if_fail (variable != NULL, FALSE);
1273 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1274 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1275 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1277 if (!overwrite && g_getenv (variable) != NULL)
1280 /* We want to (if possible) set both the environment variable copy
1281 * kept by the C runtime and the one kept by the system.
1283 * We can't use only the C runtime's putenv or _wputenv() as that
1284 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1285 * (with main() and not wmain()). In a "main()" app the C runtime
1286 * initializes the C runtime's environment table by converting the
1287 * real (wide char) environment variables to system codepage, thus
1288 * breaking those that aren't representable in the system codepage.
1290 * As the C runtime's putenv() will also set the system copy, we do
1291 * the putenv() first, then call SetEnvironmentValueW ourselves.
1294 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1295 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1296 tem = g_strconcat (variable, "=", value, NULL);
1297 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1300 _wputenv (wassignment);
1301 g_free (wassignment);
1303 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1310 #endif /* G_OS_WIN32 */
1313 #ifdef HAVE__NSGETENVIRON
1314 #define environ (*_NSGetEnviron())
1315 #elif !defined(G_OS_WIN32)
1317 /* According to the Single Unix Specification, environ is not in
1318 * any system header, although unistd.h often declares it.
1320 extern char **environ;
1325 * @variable: the environment variable to remove, must not contain '='.
1327 * Removes an environment variable from the environment.
1329 * Note that on some systems, when variables are overwritten, the memory
1330 * used for the previous variables and its value isn't reclaimed.
1331 * Furthermore, this function can't be guaranteed to operate in a
1337 g_unsetenv (const gchar *variable)
1341 #ifdef HAVE_UNSETENV
1342 g_return_if_fail (variable != NULL);
1343 g_return_if_fail (strchr (variable, '=') == NULL);
1345 unsetenv (variable);
1346 #else /* !HAVE_UNSETENV */
1350 g_return_if_fail (variable != NULL);
1351 g_return_if_fail (strchr (variable, '=') == NULL);
1353 len = strlen (variable);
1355 /* Mess directly with the environ array.
1356 * This seems to be the only portable way to do this.
1358 * Note that we remove *all* environment entries for
1359 * the variable name, not just the first.
1364 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1372 #endif /* !HAVE_UNSETENV */
1374 #else /* G_OS_WIN32 */
1376 wchar_t *wname, *wassignment;
1379 g_return_if_fail (variable != NULL);
1380 g_return_if_fail (strchr (variable, '=') == NULL);
1381 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1383 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1384 tem = g_strconcat (variable, "=", NULL);
1385 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1388 _wputenv (wassignment);
1389 g_free (wassignment);
1391 SetEnvironmentVariableW (wname, NULL);
1395 #endif /* G_OS_WIN32 */
1401 * Gets the names of all variables set in the environment.
1403 * Returns: (array zero-terminated=1) (transfer full): a %NULL-terminated list of strings which must be freed
1404 * with g_strfreev().
1406 * Programs that want to be portable to Windows should typically use
1407 * this function and g_getenv() instead of using the environ array
1408 * from the C library directly. On Windows, the strings in the environ
1409 * array are in system codepage encoding, while in most of the typical
1410 * use cases for environment variables in GLib-using programs you want
1411 * the UTF-8 encoding that this function and g_getenv() provide.
1419 gchar **result, *eq;
1422 len = g_strv_length (environ);
1423 result = g_new0 (gchar *, len + 1);
1426 for (i = 0; i < len; i++)
1428 eq = strchr (environ[i], '=');
1430 result[j++] = g_strndup (environ[i], eq - environ[i]);
1437 gchar **result, *eq;
1441 p = (wchar_t *) GetEnvironmentStringsW ();
1447 q += wcslen (q) + 1;
1451 result = g_new0 (gchar *, len + 1);
1457 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1458 if (result[j] != NULL)
1460 eq = strchr (result[j], '=');
1461 if (eq && eq > result[j])
1469 q += wcslen (q) + 1;
1472 FreeEnvironmentStringsW (p);
1481 * Gets the list of environment variables for the current process. The
1482 * list is %NULL terminated and each item in the list is of the form
1485 * This is equivalent to direct access to the 'environ' global variable,
1488 * The return value is freshly allocated and it should be freed with
1489 * g_strfreev() when it is no longer needed.
1491 * Returns: (array zero-terminated=1) (transfer full): the list of environment variables
1496 g_get_environ (void)
1499 return g_strdupv (environ);
1505 strings = GetEnvironmentStringsW ();
1506 for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1507 result = g_new (char *, n + 1);
1508 for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1509 result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1510 FreeEnvironmentStringsW (strings);
1517 G_LOCK_DEFINE_STATIC (g_utils_global);
1519 static gchar *g_tmp_dir = NULL;
1520 static gchar *g_user_name = NULL;
1521 static gchar *g_real_name = NULL;
1522 static gchar *g_home_dir = NULL;
1523 static gchar *g_host_name = NULL;
1526 /* System codepage versions of the above, kept at file level so that they,
1527 * too, are produced only once.
1529 static gchar *g_tmp_dir_cp = NULL;
1530 static gchar *g_user_name_cp = NULL;
1531 static gchar *g_real_name_cp = NULL;
1532 static gchar *g_home_dir_cp = NULL;
1535 static gchar *g_user_data_dir = NULL;
1536 static gchar **g_system_data_dirs = NULL;
1537 static gchar *g_user_cache_dir = NULL;
1538 static gchar *g_user_config_dir = NULL;
1539 static gchar **g_system_config_dirs = NULL;
1541 static gchar **g_user_special_dirs = NULL;
1543 /* fifteen minutes of fame for everybody */
1544 #define G_USER_DIRS_EXPIRE 15 * 60
1549 get_special_folder (int csidl)
1551 wchar_t path[MAX_PATH+1];
1553 LPITEMIDLIST pidl = NULL;
1555 gchar *retval = NULL;
1557 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1560 b = SHGetPathFromIDListW (pidl, path);
1562 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1563 CoTaskMemFree (pidl);
1569 get_windows_directory_root (void)
1571 wchar_t wwindowsdir[MAX_PATH];
1573 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1575 /* Usually X:\Windows, but in terminal server environments
1576 * might be an UNC path, AFAIK.
1578 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1581 if (windowsdir == NULL)
1582 return g_strdup ("C:\\");
1584 p = (char *) g_path_skip_root (windowsdir);
1585 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1591 return g_strdup ("C:\\");
1596 /* HOLDS: g_utils_global_lock */
1598 g_get_any_init_do (void)
1600 gchar hostname[100];
1602 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1603 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1604 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1605 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1606 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1609 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1610 g_tmp_dir = get_windows_directory_root ();
1613 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1616 g_tmp_dir = g_strdup (P_tmpdir);
1617 k = strlen (g_tmp_dir);
1618 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1619 g_tmp_dir[k - 1] = '\0';
1623 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1625 g_tmp_dir = g_strdup ("/tmp");
1627 #endif /* !G_OS_WIN32 */
1630 /* We check $HOME first for Win32, though it is a last resort for Unix
1631 * where we prefer the results of getpwuid().
1633 g_home_dir = g_strdup (g_getenv ("HOME"));
1635 /* Only believe HOME if it is an absolute path and exists */
1638 if (!(g_path_is_absolute (g_home_dir) &&
1639 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1641 g_free (g_home_dir);
1646 /* In case HOME is Unix-style (it happens), convert it to
1652 while ((p = strchr (g_home_dir, '/')) != NULL)
1658 /* USERPROFILE is probably the closest equivalent to $HOME? */
1659 if (g_getenv ("USERPROFILE") != NULL)
1660 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1664 g_home_dir = get_special_folder (CSIDL_PROFILE);
1667 g_home_dir = get_windows_directory_root ();
1668 #endif /* G_OS_WIN32 */
1672 struct passwd *pw = NULL;
1673 gpointer buffer = NULL;
1677 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1679 # ifdef _SC_GETPW_R_SIZE_MAX
1680 /* This reurns the maximum length */
1681 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1685 # else /* _SC_GETPW_R_SIZE_MAX */
1687 # endif /* _SC_GETPW_R_SIZE_MAX */
1689 logname = (gchar *) g_getenv ("LOGNAME");
1694 /* we allocate 6 extra bytes to work around a bug in
1695 * Mac OS < 10.3. See #156446
1697 buffer = g_malloc (bufsize + 6);
1700 # ifdef HAVE_POSIX_GETPWUID_R
1702 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1703 if (!pw || (pw->pw_uid != getuid ())) {
1704 /* LOGNAME is lying, fall back to looking up the uid */
1705 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1708 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1710 error = error < 0 ? errno : error;
1711 # else /* HAVE_NONPOSIX_GETPWUID_R */
1712 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1713 # if defined(_AIX) || defined(__hpux)
1714 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1715 pw = error == 0 ? &pwd : NULL;
1718 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1719 if (!pw || (pw->pw_uid != getuid ())) {
1720 /* LOGNAME is lying, fall back to looking up the uid */
1721 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1724 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1726 error = pw ? 0 : errno;
1728 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1732 /* we bail out prematurely if the user id can't be found
1733 * (should be pretty rare case actually), or if the buffer
1734 * should be sufficiently big and lookups are still not
1737 if (error == 0 || error == ENOENT)
1739 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1740 (gulong) getuid ());
1743 if (bufsize > 32 * 1024)
1745 g_warning ("getpwuid_r(): failed due to: %s.",
1746 g_strerror (error));
1754 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1759 pw = getpwuid (getuid ());
1764 g_user_name = g_strdup (pw->pw_name);
1766 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1768 gchar **gecos_fields;
1771 /* split the gecos field and substitute '&' */
1772 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1773 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1774 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1775 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1776 g_strfreev (gecos_fields);
1777 g_strfreev (name_parts);
1781 g_home_dir = g_strdup (pw->pw_dir);
1786 #else /* !HAVE_PWD_H */
1790 guint len = UNLEN+1;
1791 wchar_t buffer[UNLEN+1];
1793 if (GetUserNameW (buffer, (LPDWORD) &len))
1795 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1796 g_real_name = g_strdup (g_user_name);
1799 #endif /* G_OS_WIN32 */
1801 #endif /* !HAVE_PWD_H */
1805 g_home_dir = g_strdup (g_getenv ("HOME"));
1809 /* change '\\' in %HOME% to '/' */
1810 g_strdelimit (g_home_dir, "\\",'/');
1813 g_user_name = g_strdup ("somebody");
1815 g_real_name = g_strdup ("Unknown");
1819 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1821 DWORD size = sizeof (hostname);
1822 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1824 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1828 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1829 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1830 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1833 g_tmp_dir_cp = g_strdup ("\\");
1834 if (!g_user_name_cp)
1835 g_user_name_cp = g_strdup ("somebody");
1836 if (!g_real_name_cp)
1837 g_real_name_cp = g_strdup ("Unknown");
1839 /* home_dir might be NULL, unlike tmp_dir, user_name and
1843 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1845 g_home_dir_cp = NULL;
1846 #endif /* G_OS_WIN32 */
1850 g_get_any_init (void)
1853 g_get_any_init_do ();
1857 g_get_any_init_locked (void)
1859 G_LOCK (g_utils_global);
1861 G_UNLOCK (g_utils_global);
1868 * Gets the user name of the current user. The encoding of the returned
1869 * string is system-defined. On UNIX, it might be the preferred file name
1870 * encoding, or something else, and there is no guarantee that it is even
1871 * consistent on a machine. On Windows, it is always UTF-8.
1873 * Returns: the user name of the current user.
1875 G_CONST_RETURN gchar*
1876 g_get_user_name (void)
1878 g_get_any_init_locked ();
1885 * Gets the real name of the user. This usually comes from the user's entry
1886 * in the <filename>passwd</filename> file. The encoding of the returned
1887 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1888 * If the real user name cannot be determined, the string "Unknown" is
1891 * Returns: the user's real name.
1893 G_CONST_RETURN gchar*
1894 g_get_real_name (void)
1896 g_get_any_init_locked ();
1903 * Gets the current user's home directory as defined in the
1904 * password database.
1906 * Note that in contrast to traditional UNIX tools, this function
1907 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1908 * environment variable.
1910 * One of the reasons for this decision is that applications in many
1911 * cases need special handling to deal with the case where
1912 * <envar>HOME</envar> is
1914 * <member>Not owned by the user</member>
1915 * <member>Not writeable</member>
1916 * <member>Not even readable</member>
1918 * Since applications are in general <emphasis>not</emphasis> written
1919 * to deal with these situations it was considered better to make
1920 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1921 * return the real home directory for the user. If applications
1922 * want to pay attention to <envar>HOME</envar>, they can do:
1924 * const char *homedir = g_getenv ("HOME");
1926 * homedir = g_get_home_dir (<!-- -->);
1929 * Returns: the current user's home directory
1931 G_CONST_RETURN gchar*
1932 g_get_home_dir (void)
1934 g_get_any_init_locked ();
1941 * Gets the directory to use for temporary files. This is found from
1942 * inspecting the environment variables <envar>TMPDIR</envar>,
1943 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1944 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1945 * The encoding of the returned string is system-defined. On Windows,
1946 * it is always UTF-8. The return value is never %NULL or the empty string.
1948 * Returns: the directory to use for temporary files.
1950 G_CONST_RETURN gchar*
1951 g_get_tmp_dir (void)
1953 g_get_any_init_locked ();
1960 * Return a name for the machine.
1962 * The returned name is not necessarily a fully-qualified domain name,
1963 * or even present in DNS or some other name service at all. It need
1964 * not even be unique on your local network or site, but usually it
1965 * is. Callers should not rely on the return value having any specific
1966 * properties like uniqueness for security purposes. Even if the name
1967 * of the machine is changed while an application is running, the
1968 * return value from this function does not change. The returned
1969 * string is owned by GLib and should not be modified or freed. If no
1970 * name can be determined, a default fixed string "localhost" is
1973 * Returns: the host name of the machine.
1978 g_get_host_name (void)
1980 g_get_any_init_locked ();
1984 G_LOCK_DEFINE_STATIC (g_prgname);
1985 static gchar *g_prgname = NULL;
1990 * Gets the name of the program. This name should <emphasis>not</emphasis>
1991 * be localized, contrast with g_get_application_name().
1992 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1993 * which is called by gtk_init(). The program name is found by taking
1994 * the last component of <literal>argv[0]</literal>.)
1996 * Returns: the name of the program. The returned string belongs
1997 * to GLib and must not be modified or freed.
2000 g_get_prgname (void)
2006 if (g_prgname == NULL)
2008 static gboolean beenhere = FALSE;
2012 gchar *utf8_buf = NULL;
2013 wchar_t buf[MAX_PATH+1];
2016 if (GetModuleFileNameW (GetModuleHandle (NULL),
2017 buf, G_N_ELEMENTS (buf)) > 0)
2018 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2022 g_prgname = g_path_get_basename (utf8_buf);
2029 G_UNLOCK (g_prgname);
2036 * @prgname: the name of the program.
2038 * Sets the name of the program. This name should <emphasis>not</emphasis>
2039 * be localized, contrast with g_set_application_name(). Note that for
2040 * thread-safety reasons this function can only be called once.
2043 g_set_prgname (const gchar *prgname)
2047 g_prgname = g_strdup (prgname);
2048 G_UNLOCK (g_prgname);
2051 G_LOCK_DEFINE_STATIC (g_application_name);
2052 static gchar *g_application_name = NULL;
2055 * g_get_application_name:
2057 * Gets a human-readable name for the application, as set by
2058 * g_set_application_name(). This name should be localized if
2059 * possible, and is intended for display to the user. Contrast with
2060 * g_get_prgname(), which gets a non-localized name. If
2061 * g_set_application_name() has not been called, returns the result of
2062 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2065 * Return value: human-readable application name. may return %NULL
2069 G_CONST_RETURN gchar*
2070 g_get_application_name (void)
2074 G_LOCK (g_application_name);
2075 retval = g_application_name;
2076 G_UNLOCK (g_application_name);
2079 return g_get_prgname ();
2085 * g_set_application_name:
2086 * @application_name: localized name of the application
2088 * Sets a human-readable name for the application. This name should be
2089 * localized if possible, and is intended for display to the user.
2090 * Contrast with g_set_prgname(), which sets a non-localized name.
2091 * g_set_prgname() will be called automatically by gtk_init(),
2092 * but g_set_application_name() will not.
2094 * Note that for thread safety reasons, this function can only
2097 * The application name will be used in contexts such as error messages,
2098 * or when displaying an application's name in the task list.
2103 g_set_application_name (const gchar *application_name)
2105 gboolean already_set = FALSE;
2107 G_LOCK (g_application_name);
2108 if (g_application_name)
2111 g_application_name = g_strdup (application_name);
2112 G_UNLOCK (g_application_name);
2115 g_warning ("g_set_application_name() called multiple times");
2119 * g_get_user_data_dir:
2121 * Returns a base directory in which to access application data such
2122 * as icons that is customized for a particular user.
2124 * On UNIX platforms this is determined using the mechanisms described in
2125 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2126 * XDG Base Directory Specification</ulink>.
2127 * In this case the directory retrieved will be XDG_DATA_HOME.
2129 * On Windows this is the folder to use for local (as opposed to
2130 * roaming) application data. See documentation for
2131 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2132 * what g_get_user_config_dir() returns.
2134 * Return value: a string owned by GLib that must not be modified
2138 G_CONST_RETURN gchar*
2139 g_get_user_data_dir (void)
2143 G_LOCK (g_utils_global);
2145 if (!g_user_data_dir)
2148 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2150 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2152 if (data_dir && data_dir[0])
2153 data_dir = g_strdup (data_dir);
2155 if (!data_dir || !data_dir[0])
2160 data_dir = g_build_filename (g_home_dir, ".local",
2163 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2167 g_user_data_dir = data_dir;
2170 data_dir = g_user_data_dir;
2172 G_UNLOCK (g_utils_global);
2178 g_init_user_config_dir (void)
2182 if (!g_user_config_dir)
2185 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2187 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2189 if (config_dir && config_dir[0])
2190 config_dir = g_strdup (config_dir);
2192 if (!config_dir || !config_dir[0])
2197 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2199 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2202 g_user_config_dir = config_dir;
2207 * g_get_user_config_dir:
2209 * Returns a base directory in which to store user-specific application
2210 * configuration information such as user preferences and settings.
2212 * On UNIX platforms this is determined using the mechanisms described in
2213 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2214 * XDG Base Directory Specification</ulink>.
2215 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2217 * On Windows this is the folder to use for local (as opposed to
2218 * roaming) application data. See documentation for
2219 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2220 * what g_get_user_data_dir() returns.
2222 * Return value: a string owned by GLib that must not be modified
2226 G_CONST_RETURN gchar*
2227 g_get_user_config_dir (void)
2229 G_LOCK (g_utils_global);
2231 g_init_user_config_dir ();
2233 G_UNLOCK (g_utils_global);
2235 return g_user_config_dir;
2239 * g_get_user_cache_dir:
2241 * Returns a base directory in which to store non-essential, cached
2242 * data specific to particular user.
2244 * On UNIX platforms this is determined using the mechanisms described in
2245 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2246 * XDG Base Directory Specification</ulink>.
2247 * In this case the directory retrieved will be XDG_CACHE_HOME.
2249 * On Windows is the directory that serves as a common repository for
2250 * temporary Internet files. A typical path is
2251 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2252 * See documentation for CSIDL_INTERNET_CACHE.
2254 * Return value: a string owned by GLib that must not be modified
2258 G_CONST_RETURN gchar*
2259 g_get_user_cache_dir (void)
2263 G_LOCK (g_utils_global);
2265 if (!g_user_cache_dir)
2268 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2270 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2272 if (cache_dir && cache_dir[0])
2273 cache_dir = g_strdup (cache_dir);
2275 if (!cache_dir || !cache_dir[0])
2280 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2282 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2284 g_user_cache_dir = cache_dir;
2287 cache_dir = g_user_cache_dir;
2289 G_UNLOCK (g_utils_global);
2295 * g_get_user_runtime_dir:
2297 * Returns a directory that is unique to the current user on the local
2300 * On UNIX platforms this is determined using the mechanisms described in
2301 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2302 * XDG Base Directory Specification</ulink>. This is the directory
2303 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2304 * In the case that this variable is not set, GLib will issue a warning
2305 * message to stderr and return the value of g_get_user_cache_dir().
2307 * On Windows this is the folder to use for local (as opposed to
2308 * roaming) application data. See documentation for
2309 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2310 * what g_get_user_config_dir() returns.
2312 * Returns: a string owned by GLib that must not be modified or freed.
2317 g_get_user_runtime_dir (void)
2320 static const gchar *runtime_dir;
2321 static gsize initialised;
2323 if (g_once_init_enter (&initialised))
2325 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2327 g_once_init_leave (&initialised, 1);
2333 /* Both fallback for UNIX and the default
2334 * in Windows: use the user cache directory.
2338 return g_get_user_cache_dir ();
2344 find_folder (OSType type)
2346 gchar *filename = NULL;
2349 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2351 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2355 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2359 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2363 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2365 CFStringGetCString (path, filename,
2366 CFStringGetLength (path) * 3 + 1,
2367 kCFStringEncodingUTF8);
2381 load_user_special_dirs (void)
2383 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2384 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2385 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2386 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2387 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2388 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2389 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2390 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2393 #endif /* HAVE_CARBON */
2395 #if defined(G_OS_WIN32)
2397 load_user_special_dirs (void)
2399 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2403 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2405 static const GUID FOLDERID_Downloads =
2406 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2407 static const GUID FOLDERID_Public =
2408 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2412 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2413 "SHGetKnownFolderPath");
2415 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2416 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2418 if (p_SHGetKnownFolderPath == NULL)
2420 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2425 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2428 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2429 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2430 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2431 CoTaskMemFree (wcp);
2434 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2437 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2438 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2440 if (p_SHGetKnownFolderPath == NULL)
2443 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2448 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2451 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2452 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2453 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2454 CoTaskMemFree (wcp);
2457 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2460 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2461 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2463 #endif /* G_OS_WIN32 */
2465 static void g_init_user_config_dir (void);
2467 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2469 /* adapted from xdg-user-dir-lookup.c
2471 * Copyright (C) 2007 Red Hat Inc.
2473 * Permission is hereby granted, free of charge, to any person
2474 * obtaining a copy of this software and associated documentation files
2475 * (the "Software"), to deal in the Software without restriction,
2476 * including without limitation the rights to use, copy, modify, merge,
2477 * publish, distribute, sublicense, and/or sell copies of the Software,
2478 * and to permit persons to whom the Software is furnished to do so,
2479 * subject to the following conditions:
2481 * The above copyright notice and this permission notice shall be
2482 * included in all copies or substantial portions of the Software.
2484 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2485 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2486 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2487 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2488 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2489 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2490 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2494 load_user_special_dirs (void)
2501 g_init_user_config_dir ();
2502 config_file = g_build_filename (g_user_config_dir,
2506 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2508 g_free (config_file);
2512 lines = g_strsplit (data, "\n", -1);
2513 n_lines = g_strv_length (lines);
2516 for (i = 0; i < n_lines; i++)
2518 gchar *buffer = lines[i];
2521 gboolean is_relative = FALSE;
2522 GUserDirectory directory;
2524 /* Remove newline at end */
2525 len = strlen (buffer);
2526 if (len > 0 && buffer[len - 1] == '\n')
2527 buffer[len - 1] = 0;
2530 while (*p == ' ' || *p == '\t')
2533 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2535 directory = G_USER_DIRECTORY_DESKTOP;
2536 p += strlen ("XDG_DESKTOP_DIR");
2538 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2540 directory = G_USER_DIRECTORY_DOCUMENTS;
2541 p += strlen ("XDG_DOCUMENTS_DIR");
2543 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2545 directory = G_USER_DIRECTORY_DOWNLOAD;
2546 p += strlen ("XDG_DOWNLOAD_DIR");
2548 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2550 directory = G_USER_DIRECTORY_MUSIC;
2551 p += strlen ("XDG_MUSIC_DIR");
2553 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2555 directory = G_USER_DIRECTORY_PICTURES;
2556 p += strlen ("XDG_PICTURES_DIR");
2558 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2560 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2561 p += strlen ("XDG_PUBLICSHARE_DIR");
2563 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2565 directory = G_USER_DIRECTORY_TEMPLATES;
2566 p += strlen ("XDG_TEMPLATES_DIR");
2568 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2570 directory = G_USER_DIRECTORY_VIDEOS;
2571 p += strlen ("XDG_VIDEOS_DIR");
2576 while (*p == ' ' || *p == '\t')
2583 while (*p == ' ' || *p == '\t')
2590 if (strncmp (p, "$HOME", 5) == 0)
2598 d = strrchr (p, '"');
2605 /* remove trailing slashes */
2607 if (d[len - 1] == '/')
2613 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2616 g_user_special_dirs[directory] = g_strdup (d);
2620 g_free (config_file);
2623 #endif /* G_OS_UNIX && !HAVE_CARBON */
2627 * g_reload_user_special_dirs_cache:
2629 * Resets the cache used for g_get_user_special_dir(), so
2630 * that the latest on-disk version is used. Call this only
2631 * if you just changed the data on disk yourself.
2633 * Due to threadsafety issues this may cause leaking of strings
2634 * that were previously returned from g_get_user_special_dir()
2635 * that can't be freed. We ensure to only leak the data for
2636 * the directories that actually changed value though.
2641 g_reload_user_special_dirs_cache (void)
2645 G_LOCK (g_utils_global);
2647 if (g_user_special_dirs != NULL)
2649 /* save a copy of the pointer, to check if some memory can be preserved */
2650 char **old_g_user_special_dirs = g_user_special_dirs;
2653 /* recreate and reload our cache */
2654 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2655 load_user_special_dirs ();
2657 /* only leak changed directories */
2658 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2660 old_val = old_g_user_special_dirs[i];
2661 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2664 g_free (g_user_special_dirs[i]);
2665 g_user_special_dirs[i] = old_val;
2671 /* free the old array */
2672 g_free (old_g_user_special_dirs);
2675 G_UNLOCK (g_utils_global);
2679 * g_get_user_special_dir:
2680 * @directory: the logical id of special directory
2682 * Returns the full path of a special directory using its logical id.
2684 * On Unix this is done using the XDG special user directories.
2685 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2686 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2687 * user directories have not been set up.
2689 * Depending on the platform, the user might be able to change the path
2690 * of the special directory without requiring the session to restart; GLib
2691 * will not reflect any change once the special directories are loaded.
2693 * Return value: the path to the specified special directory, or %NULL
2694 * if the logical id was not found. The returned string is owned by
2695 * GLib and should not be modified or freed.
2699 G_CONST_RETURN gchar *
2700 g_get_user_special_dir (GUserDirectory directory)
2702 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2703 directory < G_USER_N_DIRECTORIES, NULL);
2705 G_LOCK (g_utils_global);
2707 if (G_UNLIKELY (g_user_special_dirs == NULL))
2709 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2711 load_user_special_dirs ();
2713 /* Special-case desktop for historical compatibility */
2714 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2718 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2719 g_build_filename (g_home_dir, "Desktop", NULL);
2723 G_UNLOCK (g_utils_global);
2725 return g_user_special_dirs[directory];
2730 #undef g_get_system_data_dirs
2733 get_module_for_address (gconstpointer address)
2735 /* Holds the g_utils_global lock */
2737 static gboolean beenhere = FALSE;
2738 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2739 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2740 HMODULE hmodule = NULL;
2747 p_GetModuleHandleExA =
2748 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2749 "GetModuleHandleExA");
2753 if (p_GetModuleHandleExA == NULL ||
2754 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2755 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2758 MEMORY_BASIC_INFORMATION mbi;
2759 VirtualQuery (address, &mbi, sizeof (mbi));
2760 hmodule = (HMODULE) mbi.AllocationBase;
2767 get_module_share_dir (gconstpointer address)
2773 hmodule = get_module_for_address (address);
2774 if (hmodule == NULL)
2777 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2778 retval = g_build_filename (filename, "share", NULL);
2784 G_CONST_RETURN gchar * G_CONST_RETURN *
2785 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2789 static GHashTable *per_module_data_dirs = NULL;
2794 if (address_of_function)
2796 G_LOCK (g_utils_global);
2797 hmodule = get_module_for_address (address_of_function);
2798 if (hmodule != NULL)
2800 if (per_module_data_dirs == NULL)
2801 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2804 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2808 G_UNLOCK (g_utils_global);
2809 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2815 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2817 /* Documents and Settings\All Users\Application Data */
2818 p = get_special_folder (CSIDL_COMMON_APPDATA);
2820 g_array_append_val (data_dirs, p);
2822 /* Documents and Settings\All Users\Documents */
2823 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2825 g_array_append_val (data_dirs, p);
2827 /* Using the above subfolders of Documents and Settings perhaps
2828 * makes sense from a Windows perspective.
2830 * But looking at the actual use cases of this function in GTK+
2831 * and GNOME software, what we really want is the "share"
2832 * subdirectory of the installation directory for the package
2833 * our caller is a part of.
2835 * The address_of_function parameter, if non-NULL, points to a
2836 * function in the calling module. Use that to determine that
2837 * module's installation folder, and use its "share" subfolder.
2839 * Additionally, also use the "share" subfolder of the installation
2840 * locations of GLib and the .exe file being run.
2842 * To guard against none of the above being what is really wanted,
2843 * callers of this function should have Win32-specific code to look
2844 * up their installation folder themselves, and handle a subfolder
2845 * "share" of it in the same way as the folders returned from this
2849 p = get_module_share_dir (address_of_function);
2851 g_array_append_val (data_dirs, p);
2853 if (glib_dll != NULL)
2855 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2856 p = g_build_filename (glib_root, "share", NULL);
2858 g_array_append_val (data_dirs, p);
2862 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2863 p = g_build_filename (exe_root, "share", NULL);
2865 g_array_append_val (data_dirs, p);
2868 retval = (gchar **) g_array_free (data_dirs, FALSE);
2870 if (address_of_function)
2872 if (hmodule != NULL)
2873 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2874 G_UNLOCK (g_utils_global);
2877 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2883 * g_get_system_data_dirs:
2885 * Returns an ordered list of base directories in which to access
2886 * system-wide application data.
2888 * On UNIX platforms this is determined using the mechanisms described in
2889 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2890 * XDG Base Directory Specification</ulink>
2891 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2893 * On Windows the first elements in the list are the Application Data
2894 * and Documents folders for All Users. (These can be determined only
2895 * on Windows 2000 or later and are not present in the list on other
2896 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2897 * CSIDL_COMMON_DOCUMENTS.
2899 * Then follows the "share" subfolder in the installation folder for
2900 * the package containing the DLL that calls this function, if it can
2903 * Finally the list contains the "share" subfolder in the installation
2904 * folder for GLib, and in the installation folder for the package the
2905 * application's .exe file belongs to.
2907 * The installation folders above are determined by looking up the
2908 * folder where the module (DLL or EXE) in question is located. If the
2909 * folder's name is "bin", its parent is used, otherwise the folder
2912 * Note that on Windows the returned list can vary depending on where
2913 * this function is called.
2915 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2916 * not be modified or freed.
2919 G_CONST_RETURN gchar * G_CONST_RETURN *
2920 g_get_system_data_dirs (void)
2922 gchar **data_dir_vector;
2924 G_LOCK (g_utils_global);
2926 if (!g_system_data_dirs)
2929 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2931 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2933 if (!data_dirs || !data_dirs[0])
2934 data_dirs = "/usr/local/share/:/usr/share/";
2936 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2939 g_system_data_dirs = data_dir_vector;
2942 data_dir_vector = g_system_data_dirs;
2944 G_UNLOCK (g_utils_global);
2946 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2950 * g_get_system_config_dirs:
2952 * Returns an ordered list of base directories in which to access
2953 * system-wide configuration information.
2955 * On UNIX platforms this is determined using the mechanisms described in
2956 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2957 * XDG Base Directory Specification</ulink>.
2958 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2960 * On Windows is the directory that contains application data for all users.
2961 * A typical path is C:\Documents and Settings\All Users\Application Data.
2962 * This folder is used for application data that is not user specific.
2963 * For example, an application can store a spell-check dictionary, a database
2964 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2965 * This information will not roam and is available to anyone using the computer.
2967 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2968 * not be modified or freed.
2971 G_CONST_RETURN gchar * G_CONST_RETURN *
2972 g_get_system_config_dirs (void)
2974 gchar *conf_dirs, **conf_dir_vector;
2976 G_LOCK (g_utils_global);
2978 if (!g_system_config_dirs)
2981 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2984 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2989 /* Return empty list */
2990 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2993 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2995 if (!conf_dirs || !conf_dirs[0])
2996 conf_dirs = "/etc/xdg";
2998 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3001 g_system_config_dirs = conf_dir_vector;
3004 conf_dir_vector = g_system_config_dirs;
3005 G_UNLOCK (g_utils_global);
3007 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
3012 static GHashTable *alias_table = NULL;
3014 /* read an alias file for the locales */
3016 read_aliases (gchar *file)
3022 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3023 fp = fopen (file,"r");
3026 while (fgets (buf, 256, fp))
3032 /* Line is a comment */
3033 if ((buf[0] == '#') || (buf[0] == '\0'))
3036 /* Reads first column */
3037 for (p = buf, q = NULL; *p; p++) {
3038 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3041 while ((*q == '\t') || (*q == ' ')) {
3047 /* The line only had one column */
3048 if (!q || *q == '\0')
3051 /* Read second column */
3052 for (p = q; *p; p++) {
3053 if ((*p == '\t') || (*p == ' ')) {
3059 /* Add to alias table if necessary */
3060 if (!g_hash_table_lookup (alias_table, buf)) {
3061 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3070 unalias_lang (char *lang)
3077 read_aliases ("/usr/share/locale/locale.alias");
3080 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3085 static gboolean said_before = FALSE;
3087 g_warning ("Too many alias levels for a locale, "
3088 "may indicate a loop");
3097 /* Mask for components of locale spec. The ordering here is from
3098 * least significant to most significant
3102 COMPONENT_CODESET = 1 << 0,
3103 COMPONENT_TERRITORY = 1 << 1,
3104 COMPONENT_MODIFIER = 1 << 2
3107 /* Break an X/Open style locale specification into components
3110 explode_locale (const gchar *locale,
3116 const gchar *uscore_pos;
3117 const gchar *at_pos;
3118 const gchar *dot_pos;
3122 uscore_pos = strchr (locale, '_');
3123 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3124 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3128 mask |= COMPONENT_MODIFIER;
3129 *modifier = g_strdup (at_pos);
3132 at_pos = locale + strlen (locale);
3136 mask |= COMPONENT_CODESET;
3137 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3144 mask |= COMPONENT_TERRITORY;
3145 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3148 uscore_pos = dot_pos;
3150 *language = g_strndup (locale, uscore_pos - locale);
3156 * Compute all interesting variants for a given locale name -
3157 * by stripping off different components of the value.
3159 * For simplicity, we assume that the locale is in
3160 * X/Open format: language[_territory][.codeset][@modifier]
3162 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3163 * as well. We could just copy the code from glibc wholesale
3164 * but it is big, ugly, and complicated, so I'm reluctant
3165 * to do so when this should handle 99% of the time...
3168 append_locale_variants (GPtrArray *array,
3169 const gchar *locale)
3171 gchar *language = NULL;
3172 gchar *territory = NULL;
3173 gchar *codeset = NULL;
3174 gchar *modifier = NULL;
3179 g_return_if_fail (locale != NULL);
3181 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3183 /* Iterate through all possible combinations, from least attractive
3184 * to most attractive.
3186 for (j = 0; j <= mask; ++j)
3190 if ((i & ~mask) == 0)
3192 gchar *val = g_strconcat (language,
3193 (i & COMPONENT_TERRITORY) ? territory : "",
3194 (i & COMPONENT_CODESET) ? codeset : "",
3195 (i & COMPONENT_MODIFIER) ? modifier : "",
3197 g_ptr_array_add (array, val);
3202 if (mask & COMPONENT_CODESET)
3204 if (mask & COMPONENT_TERRITORY)
3206 if (mask & COMPONENT_MODIFIER)
3211 * g_get_locale_variants:
3212 * @locale: a locale identifier
3214 * Returns a list of derived variants of @locale, which can be used to
3215 * e.g. construct locale-dependent filenames or search paths. The returned
3216 * list is sorted from most desirable to least desirable.
3217 * This function handles territory, charset and extra locale modifiers.
3219 * For example, if @locale is "fr_BE", then the returned list
3222 * If you need the list of variants for the <emphasis>current locale</emphasis>,
3223 * use g_get_language_names().
3225 * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
3226 * allocated array of newly allocated strings with the locale variants. Free with
3232 g_get_locale_variants (const gchar *locale)
3236 g_return_val_if_fail (locale != NULL, NULL);
3238 array = g_ptr_array_sized_new (8);
3239 append_locale_variants (array, locale);
3240 g_ptr_array_add (array, NULL);
3242 return (gchar **) g_ptr_array_free (array, FALSE);
3245 /* The following is (partly) taken from the gettext package.
3246 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3248 static const gchar *
3249 guess_category_value (const gchar *category_name)
3251 const gchar *retval;
3253 /* The highest priority value is the `LANGUAGE' environment
3254 variable. This is a GNU extension. */
3255 retval = g_getenv ("LANGUAGE");
3256 if ((retval != NULL) && (retval[0] != '\0'))
3259 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3260 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3261 systems this can be done by the `setlocale' function itself. */
3263 /* Setting of LC_ALL overwrites all other. */
3264 retval = g_getenv ("LC_ALL");
3265 if ((retval != NULL) && (retval[0] != '\0'))
3268 /* Next comes the name of the desired category. */
3269 retval = g_getenv (category_name);
3270 if ((retval != NULL) && (retval[0] != '\0'))
3273 /* Last possibility is the LANG environment variable. */
3274 retval = g_getenv ("LANG");
3275 if ((retval != NULL) && (retval[0] != '\0'))
3278 #ifdef G_PLATFORM_WIN32
3279 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3280 * LANG, which we already did above. Oh well. The main point of
3281 * calling g_win32_getlocale() is to get the thread's locale as used
3282 * by Windows and the Microsoft C runtime (in the "English_United
3283 * States" format) translated into the Unixish format.
3286 char *locale = g_win32_getlocale ();
3287 retval = g_intern_string (locale);
3296 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3298 struct _GLanguageNamesCache {
3300 gchar **language_names;
3304 language_names_cache_free (gpointer data)
3306 GLanguageNamesCache *cache = data;
3307 g_free (cache->languages);
3308 g_strfreev (cache->language_names);
3313 * g_get_language_names:
3315 * Computes a list of applicable locale names, which can be used to
3316 * e.g. construct locale-dependent filenames or search paths. The returned
3317 * list is sorted from most desirable to least desirable and always contains
3318 * the default locale "C".
3320 * For example, if LANGUAGE=de:en_US, then the returned list is
3321 * "de", "en_US", "en", "C".
3323 * This function consults the environment variables <envar>LANGUAGE</envar>,
3324 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3325 * to find the list of locales specified by the user.
3327 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
3328 * that must not be modified or freed.
3332 G_CONST_RETURN gchar * G_CONST_RETURN *
3333 g_get_language_names (void)
3335 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3336 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3341 cache = g_new0 (GLanguageNamesCache, 1);
3342 g_static_private_set (&cache_private, cache, language_names_cache_free);
3345 value = guess_category_value ("LC_MESSAGES");
3349 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3354 g_free (cache->languages);
3355 g_strfreev (cache->language_names);
3356 cache->languages = g_strdup (value);
3358 array = g_ptr_array_sized_new (8);
3360 alist = g_strsplit (value, ":", 0);
3361 for (a = alist; *a; a++)
3362 append_locale_variants (array, unalias_lang (*a));
3364 g_ptr_array_add (array, g_strdup ("C"));
3365 g_ptr_array_add (array, NULL);
3367 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3370 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3375 * @v: a #gpointer key
3377 * Converts a gpointer to a hash value.
3378 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3379 * when using pointers as keys in a #GHashTable.
3381 * Returns: a hash value corresponding to the key.
3384 g_direct_hash (gconstpointer v)
3386 return GPOINTER_TO_UINT (v);
3392 * @v2: a key to compare with @v1.
3394 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3395 * It can be passed to g_hash_table_new() as the @key_equal_func
3396 * parameter, when using pointers as keys in a #GHashTable.
3398 * Returns: %TRUE if the two keys match.
3401 g_direct_equal (gconstpointer v1,
3409 * @v1: a pointer to a #gint key.
3410 * @v2: a pointer to a #gint key to compare with @v1.
3412 * Compares the two #gint values being pointed to and returns
3413 * %TRUE if they are equal.
3414 * It can be passed to g_hash_table_new() as the @key_equal_func
3415 * parameter, when using pointers to integers as keys in a #GHashTable.
3417 * Returns: %TRUE if the two keys match.
3420 g_int_equal (gconstpointer v1,
3423 return *((const gint*) v1) == *((const gint*) v2);
3428 * @v: a pointer to a #gint key
3430 * Converts a pointer to a #gint to a hash value.
3431 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3432 * when using pointers to integers values as keys in a #GHashTable.
3434 * Returns: a hash value corresponding to the key.
3437 g_int_hash (gconstpointer v)
3439 return *(const gint*) v;
3444 * @v1: a pointer to a #gint64 key.
3445 * @v2: a pointer to a #gint64 key to compare with @v1.
3447 * Compares the two #gint64 values being pointed to and returns
3448 * %TRUE if they are equal.
3449 * It can be passed to g_hash_table_new() as the @key_equal_func
3450 * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3452 * Returns: %TRUE if the two keys match.
3457 g_int64_equal (gconstpointer v1,
3460 return *((const gint64*) v1) == *((const gint64*) v2);
3465 * @v: a pointer to a #gint64 key
3467 * Converts a pointer to a #gint64 to a hash value.
3468 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3469 * when using pointers to 64-bit integers values as keys in a #GHashTable.
3471 * Returns: a hash value corresponding to the key.
3476 g_int64_hash (gconstpointer v)
3478 return (guint) *(const gint64*) v;
3483 * @v1: a pointer to a #gdouble key.
3484 * @v2: a pointer to a #gdouble key to compare with @v1.
3486 * Compares the two #gdouble values being pointed to and returns
3487 * %TRUE if they are equal.
3488 * It can be passed to g_hash_table_new() as the @key_equal_func
3489 * parameter, when using pointers to doubles as keys in a #GHashTable.
3491 * Returns: %TRUE if the two keys match.
3496 g_double_equal (gconstpointer v1,
3499 return *((const gdouble*) v1) == *((const gdouble*) v2);
3504 * @v: a pointer to a #gdouble key
3506 * Converts a pointer to a #gdouble to a hash value.
3507 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3508 * when using pointers to doubles as keys in a #GHashTable.
3510 * Returns: a hash value corresponding to the key.
3515 g_double_hash (gconstpointer v)
3517 return (guint) *(const gdouble*) v;
3521 * g_nullify_pointer:
3522 * @nullify_location: the memory address of the pointer.
3524 * Set the pointer at the specified location to %NULL.
3527 g_nullify_pointer (gpointer *nullify_location)
3529 g_return_if_fail (nullify_location != NULL);
3531 *nullify_location = NULL;
3537 * Get the codeset for the current locale.
3539 * Return value: a newly allocated string containing the name
3540 * of the codeset. This string must be freed with g_free().
3543 g_get_codeset (void)
3545 const gchar *charset;
3547 g_get_charset (&charset);
3549 return g_strdup (charset);
3552 /* This is called from g_thread_init(). It's used to
3553 * initialize some static data in a threadsafe way.
3556 _g_utils_thread_init (void)
3558 g_get_language_names ();
3564 * _glib_get_locale_dir:
3566 * Return the path to the share\locale or lib\locale subfolder of the
3567 * GLib installation folder. The path is in the system codepage. We
3568 * have to use system codepage as bindtextdomain() doesn't have a
3572 _glib_get_locale_dir (void)
3574 gchar *install_dir = NULL, *locale_dir;
3575 gchar *retval = NULL;
3577 if (glib_dll != NULL)
3578 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3583 * Append "/share/locale" or "/lib/locale" depending on whether
3584 * autoconfigury detected GNU gettext or not.
3586 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3592 locale_dir = g_build_filename (install_dir, p, NULL);
3594 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3596 g_free (install_dir);
3597 g_free (locale_dir);
3603 return g_strdup ("");
3606 #undef GLIB_LOCALE_DIR
3608 #endif /* G_OS_WIN32 */
3611 ensure_gettext_initialized(void)
3613 static gboolean _glib_gettext_initialized = FALSE;
3615 if (!_glib_gettext_initialized)
3618 gchar *tmp = _glib_get_locale_dir ();
3619 bindtextdomain (GETTEXT_PACKAGE, tmp);
3622 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3624 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3625 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3627 _glib_gettext_initialized = TRUE;
3633 * @str: The string to be translated
3635 * Returns the translated string from the glib translations.
3636 * This is an internal function and should only be used by
3637 * the internals of glib (such as libgio).
3639 * Returns: the transation of @str to the current locale
3641 G_CONST_RETURN gchar *
3642 glib_gettext (const gchar *str)
3644 ensure_gettext_initialized();
3646 return g_dgettext (GETTEXT_PACKAGE, str);
3651 * @msgctxtid: a combined message context and message id, separated
3652 * by a \004 character
3653 * @msgidoffset: the offset of the message id in @msgctxid
3655 * This function is a variant of glib_gettext() which supports
3656 * a disambiguating message context. See g_dpgettext() for full
3659 * This is an internal function and should only be used by
3660 * the internals of glib (such as libgio).
3662 * Returns: the transation of @str to the current locale
3664 G_CONST_RETURN gchar *
3665 glib_pgettext(const gchar *msgctxtid,
3668 ensure_gettext_initialized();
3670 return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3673 #if defined (G_OS_WIN32) && !defined (_WIN64)
3675 /* Binary compatibility versions. Not for newly compiled code. */
3677 #undef g_find_program_in_path
3680 g_find_program_in_path (const gchar *program)
3682 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3683 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3686 g_free (utf8_program);
3687 if (utf8_retval == NULL)
3689 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3690 g_free (utf8_retval);
3695 #undef g_get_current_dir
3698 g_get_current_dir (void)
3700 gchar *utf8_dir = g_get_current_dir_utf8 ();
3701 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3708 G_CONST_RETURN gchar*
3709 g_getenv (const gchar *variable)
3711 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3712 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3716 g_free (utf8_variable);
3719 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3720 quark = g_quark_from_string (value);
3723 return g_quark_to_string (quark);
3729 g_setenv (const gchar *variable,
3733 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3734 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3735 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3737 g_free (utf8_variable);
3738 g_free (utf8_value);
3746 g_unsetenv (const gchar *variable)
3748 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3750 g_unsetenv_utf8 (utf8_variable);
3752 g_free (utf8_variable);
3755 #undef g_get_user_name
3757 G_CONST_RETURN gchar*
3758 g_get_user_name (void)
3760 g_get_any_init_locked ();
3761 return g_user_name_cp;
3764 #undef g_get_real_name
3766 G_CONST_RETURN gchar*
3767 g_get_real_name (void)
3769 g_get_any_init_locked ();
3770 return g_real_name_cp;
3773 #undef g_get_home_dir
3775 G_CONST_RETURN gchar*
3776 g_get_home_dir (void)
3778 g_get_any_init_locked ();
3779 return g_home_dir_cp;
3782 #undef g_get_tmp_dir
3784 G_CONST_RETURN gchar*
3785 g_get_tmp_dir (void)
3787 g_get_any_init_locked ();
3788 return g_tmp_dir_cp;