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"
73 #ifdef G_PLATFORM_WIN32
80 #define G_PATH_LENGTH MAXPATHLEN
81 #elif defined (PATH_MAX)
82 #define G_PATH_LENGTH PATH_MAX
83 #elif defined (_PC_PATH_MAX)
84 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
86 #define G_PATH_LENGTH 2048
89 #ifdef G_PLATFORM_WIN32
90 # define STRICT /* Strict typing, please */
93 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
94 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
95 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
97 # include <lmcons.h> /* For UNLEN */
98 #endif /* G_PLATFORM_WIN32 */
103 /* older SDK (e.g. msvc 5.0) does not have these*/
104 # ifndef CSIDL_MYMUSIC
105 # define CSIDL_MYMUSIC 13
107 # ifndef CSIDL_MYVIDEO
108 # define CSIDL_MYVIDEO 14
110 # ifndef CSIDL_INTERNET_CACHE
111 # define CSIDL_INTERNET_CACHE 32
113 # ifndef CSIDL_COMMON_APPDATA
114 # define CSIDL_COMMON_APPDATA 35
116 # ifndef CSIDL_MYPICTURES
117 # define CSIDL_MYPICTURES 0x27
119 # ifndef CSIDL_COMMON_DOCUMENTS
120 # define CSIDL_COMMON_DOCUMENTS 46
122 # ifndef CSIDL_PROFILE
123 # define CSIDL_PROFILE 40
125 # include <process.h>
129 #include <CoreServices/CoreServices.h>
133 #include <langinfo.h>
136 const guint glib_major_version = GLIB_MAJOR_VERSION;
137 const guint glib_minor_version = GLIB_MINOR_VERSION;
138 const guint glib_micro_version = GLIB_MICRO_VERSION;
139 const guint glib_interface_age = GLIB_INTERFACE_AGE;
140 const guint glib_binary_age = GLIB_BINARY_AGE;
142 #ifdef G_PLATFORM_WIN32
144 static HMODULE glib_dll = NULL;
149 DllMain (HINSTANCE hinstDLL,
153 if (fdwReason == DLL_PROCESS_ATTACH)
162 _glib_get_dll_directory (void)
166 wchar_t wc_fn[MAX_PATH];
169 if (glib_dll == NULL)
173 /* This code is different from that in
174 * g_win32_get_package_installation_directory_of_module() in that
175 * here we return the actual folder where the GLib DLL is. We don't
176 * do the check for it being in a "bin" or "lib" subfolder and then
177 * returning the parent of that.
179 * In a statically built GLib, glib_dll will be NULL and we will
180 * thus look up the application's .exe file's location.
182 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
185 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
187 p = strrchr (retval, G_DIR_SEPARATOR);
201 * glib_check_version:
202 * @required_major: the required major version.
203 * @required_minor: the required minor version.
204 * @required_micro: the required micro version.
206 * Checks that the GLib library in use is compatible with the
207 * given version. Generally you would pass in the constants
208 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
209 * as the three arguments to this function; that produces
210 * a check that the library in use is compatible with
211 * the version of GLib the application or module was compiled
214 * Compatibility is defined by two things: first the version
215 * of the running library is newer than the version
216 * @required_major.required_minor.@required_micro. Second
217 * the running library must be binary compatible with the
218 * version @required_major.required_minor.@required_micro
219 * (same major version.)
221 * Return value: %NULL if the GLib library is compatible with the
222 * given version, or a string describing the version mismatch.
223 * The returned string is owned by GLib and must not be modified
229 glib_check_version (guint required_major,
230 guint required_minor,
231 guint required_micro)
233 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
234 gint required_effective_micro = 100 * required_minor + required_micro;
236 if (required_major > GLIB_MAJOR_VERSION)
237 return "GLib version too old (major mismatch)";
238 if (required_major < GLIB_MAJOR_VERSION)
239 return "GLib version too new (major mismatch)";
240 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
241 return "GLib version too new (micro mismatch)";
242 if (required_effective_micro > glib_effective_micro)
243 return "GLib version too old (micro mismatch)";
247 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
250 * @dest: the destination address to copy the bytes to.
251 * @src: the source address to copy the bytes from.
252 * @len: the number of bytes to copy.
254 * Copies a block of memory @len bytes long, from @src to @dest.
255 * The source and destination areas may overlap.
257 * In order to use this function, you must include
258 * <filename>string.h</filename> yourself, because this macro will
259 * typically simply resolve to memmove() and GLib does not include
260 * <filename>string.h</filename> for you.
263 g_memmove (gpointer dest,
267 gchar* destptr = dest;
268 const gchar* srcptr = src;
269 if (src + len < dest || dest + len < src)
271 bcopy (src, dest, len);
274 else if (dest <= src)
277 *(destptr++) = *(srcptr++);
284 *(--destptr) = *(--srcptr);
287 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
295 * @func: the function to call on normal program termination.
297 * Specifies a function to be called at normal program termination.
299 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
300 * macro that maps to a call to the atexit() function in the C
301 * library. This means that in case the code that calls g_atexit(),
302 * i.e. atexit(), is in a DLL, the function will be called when the
303 * DLL is detached from the program. This typically makes more sense
304 * than that the function is called when the GLib DLL is detached,
305 * which happened earlier when g_atexit() was a function in the GLib
308 * The behaviour of atexit() in the context of dynamically loaded
309 * modules is not formally specified and varies wildly.
311 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
312 * loaded module which is unloaded before the program terminates might
313 * well cause a crash at program exit.
315 * Some POSIX systems implement atexit() like Windows, and have each
316 * dynamically loaded module maintain an own atexit chain that is
317 * called when the module is unloaded.
319 * On other POSIX systems, before a dynamically loaded module is
320 * unloaded, the registered atexit functions (if any) residing in that
321 * module are called, regardless where the code that registered them
322 * resided. This is presumably the most robust approach.
324 * As can be seen from the above, for portability it's best to avoid
325 * calling g_atexit() (or atexit()) except in the main executable of a
329 g_atexit (GVoidFunc func)
332 const gchar *error = NULL;
334 /* keep this in sync with glib.h */
336 #ifdef G_NATIVE_ATEXIT
337 result = ATEXIT (func);
339 error = g_strerror (errno);
340 #elif defined (HAVE_ATEXIT)
341 # ifdef NeXT /* @#%@! NeXTStep */
342 result = !atexit ((void (*)(void)) func);
344 error = g_strerror (errno);
346 result = atexit ((void (*)(void)) func);
348 error = g_strerror (errno);
350 #elif defined (HAVE_ON_EXIT)
351 result = on_exit ((void (*)(int, void *)) func, NULL);
353 error = g_strerror (errno);
356 error = "no implementation";
357 #endif /* G_NATIVE_ATEXIT */
360 g_error ("Could not register atexit() function: %s", error);
363 /* Based on execvp() from GNU Libc.
364 * Some of this code is cut-and-pasted into gspawn.c
368 my_strchrnul (const gchar *str,
371 gchar *p = (gchar*)str;
372 while (*p && (*p != c))
380 static gchar *inner_find_program_in_path (const gchar *program);
383 g_find_program_in_path (const gchar *program)
385 const gchar *last_dot = strrchr (program, '.');
387 if (last_dot == NULL ||
388 strchr (last_dot, '\\') != NULL ||
389 strchr (last_dot, '/') != NULL)
391 const gint program_length = strlen (program);
392 gchar *pathext = g_build_path (";",
393 ".exe;.cmd;.bat;.com",
394 g_getenv ("PATHEXT"),
397 gchar *decorated_program;
403 gchar *q = my_strchrnul (p, ';');
405 decorated_program = g_malloc (program_length + (q-p) + 1);
406 memcpy (decorated_program, program, program_length);
407 memcpy (decorated_program+program_length, p, q-p);
408 decorated_program [program_length + (q-p)] = '\0';
410 retval = inner_find_program_in_path (decorated_program);
411 g_free (decorated_program);
419 } while (*p++ != '\0');
424 return inner_find_program_in_path (program);
430 * g_find_program_in_path:
431 * @program: a program name in the GLib file name encoding
433 * Locates the first executable named @program in the user's path, in the
434 * same way that execvp() would locate it. Returns an allocated string
435 * with the absolute path name, or %NULL if the program is not found in
436 * the path. If @program is already an absolute path, returns a copy of
437 * @program if @program exists and is executable, and %NULL otherwise.
439 * On Windows, if @program does not have a file type suffix, tries
440 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
441 * the <envar>PATHEXT</envar> environment variable.
443 * On Windows, it looks for the file in the same way as CreateProcess()
444 * would. This means first in the directory where the executing
445 * program was loaded from, then in the current directory, then in the
446 * Windows 32-bit system directory, then in the Windows directory, and
447 * finally in the directories in the <envar>PATH</envar> environment
448 * variable. If the program is found, the return value contains the
449 * full name including the type suffix.
451 * Return value: absolute path, or %NULL
455 inner_find_program_in_path (const gchar *program)
458 g_find_program_in_path (const gchar *program)
461 const gchar *path, *p;
462 gchar *name, *freeme;
464 const gchar *path_copy;
465 gchar *filename = NULL, *appdir = NULL;
466 gchar *sysdir = NULL, *windir = NULL;
468 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
474 g_return_val_if_fail (program != NULL, NULL);
476 /* If it is an absolute path, or a relative path including subdirectories,
477 * don't look in PATH.
479 if (g_path_is_absolute (program)
480 || strchr (program, G_DIR_SEPARATOR) != NULL
482 || strchr (program, '/') != NULL
486 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
487 !g_file_test (program, G_FILE_TEST_IS_DIR))
488 return g_strdup (program);
493 path = g_getenv ("PATH");
494 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
497 /* There is no `PATH' in the environment. The default
498 * search path in GNU libc is the current directory followed by
499 * the path `confstr' returns for `_CS_PATH'.
502 /* In GLib we put . last, for security, and don't use the
503 * unportable confstr(); UNIX98 does not actually specify
504 * what to search if PATH is unset. POSIX may, dunno.
507 path = "/bin:/usr/bin:.";
510 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
511 if (n > 0 && n < MAXPATHLEN)
512 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
514 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
515 if (n > 0 && n < MAXPATHLEN)
516 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
518 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
519 if (n > 0 && n < MAXPATHLEN)
520 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
524 appdir = g_path_get_dirname (filename);
528 path = g_strdup (path);
532 const gchar *tem = path;
533 path = g_strconcat (windir, ";", path, NULL);
534 g_free ((gchar *) tem);
540 const gchar *tem = path;
541 path = g_strconcat (sysdir, ";", path, NULL);
542 g_free ((gchar *) tem);
547 const gchar *tem = path;
548 path = g_strconcat (".;", path, NULL);
549 g_free ((gchar *) tem);
554 const gchar *tem = path;
555 path = g_strconcat (appdir, ";", path, NULL);
556 g_free ((gchar *) tem);
563 len = strlen (program) + 1;
564 pathlen = strlen (path);
565 freeme = name = g_malloc (pathlen + len + 1);
567 /* Copy the file name at the top, including '\0' */
568 memcpy (name + pathlen + 1, program, len);
569 name = name + pathlen;
570 /* And add the slash before the filename */
571 *name = G_DIR_SEPARATOR;
579 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
582 /* Two adjacent colons, or a colon at the beginning or the end
583 * of `PATH' means to search the current directory.
587 startp = memcpy (name - (p - path), path, p - path);
589 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
590 !g_file_test (startp, G_FILE_TEST_IS_DIR))
593 ret = g_strdup (startp);
596 g_free ((gchar *) path_copy);
601 while (*p++ != '\0');
605 g_free ((gchar *) path_copy);
612 debug_key_matches (const gchar *key,
616 for (; length; length--, key++, token++)
618 char k = (*key == '_') ? '-' : tolower (*key );
619 char t = (*token == '_') ? '-' : tolower (*token);
629 * g_parse_debug_string:
630 * @string: a list of debug options separated by colons, spaces, or
632 * @keys: pointer to an array of #GDebugKey which associate
633 * strings with bit flags.
634 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
636 * Parses a string containing debugging options
637 * into a %guint containing bit flags. This is used
638 * within GDK and GTK+ to parse the debug options passed on the
639 * command line or through environment variables.
641 * If @string is equal to "all", all flags are set. If @string
642 * is equal to "help", all the available keys in @keys are printed
643 * out to standard error.
645 * Returns: the combined set of bit flags.
648 g_parse_debug_string (const gchar *string,
649 const GDebugKey *keys,
658 /* this function is used by gmem.c/gslice.c initialization code,
659 * so introducing malloc dependencies here would require adaptions
660 * of those code portions.
663 if (!g_ascii_strcasecmp (string, "all"))
665 for (i=0; i<nkeys; i++)
666 result |= keys[i].value;
668 else if (!g_ascii_strcasecmp (string, "help"))
670 /* using stdio directly for the reason stated above */
671 fprintf (stderr, "Supported debug values: ");
672 for (i=0; i<nkeys; i++)
673 fprintf (stderr, " %s", keys[i].key);
674 fprintf (stderr, "\n");
678 const gchar *p = string;
683 q = strpbrk (p, ":;, \t");
687 for (i = 0; i < nkeys; i++)
688 if (debug_key_matches (keys[i].key, p, q - p))
689 result |= keys[i].value;
702 * @file_name: the name of the file.
704 * Gets the name of the file without any leading directory components.
705 * It returns a pointer into the given file name string.
707 * Return value: the name of the file without any leading directory components.
709 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
710 * g_path_get_basename() allocates new memory for the returned string, unlike
711 * this function which returns a pointer into the argument.
713 G_CONST_RETURN gchar*
714 g_basename (const gchar *file_name)
716 register gchar *base;
718 g_return_val_if_fail (file_name != NULL, NULL);
720 base = strrchr (file_name, G_DIR_SEPARATOR);
724 gchar *q = strrchr (file_name, '/');
725 if (base == NULL || (q != NULL && q > base))
734 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
735 return (gchar*) file_name + 2;
736 #endif /* G_OS_WIN32 */
738 return (gchar*) file_name;
742 * g_path_get_basename:
743 * @file_name: the name of the file.
745 * Gets the last component of the filename. If @file_name ends with a
746 * directory separator it gets the component before the last slash. If
747 * @file_name consists only of directory separators (and on Windows,
748 * possibly a drive letter), a single separator is returned. If
749 * @file_name is empty, it gets ".".
751 * Return value: a newly allocated string containing the last component of
755 g_path_get_basename (const gchar *file_name)
757 register gssize base;
758 register gssize last_nonslash;
762 g_return_val_if_fail (file_name != NULL, NULL);
764 if (file_name[0] == '\0')
766 return g_strdup (".");
768 last_nonslash = strlen (file_name) - 1;
770 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
773 if (last_nonslash == -1)
774 /* string only containing slashes */
775 return g_strdup (G_DIR_SEPARATOR_S);
778 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
779 /* string only containing slashes and a drive */
780 return g_strdup (G_DIR_SEPARATOR_S);
781 #endif /* G_OS_WIN32 */
783 base = last_nonslash;
785 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
789 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
791 #endif /* G_OS_WIN32 */
793 len = last_nonslash - base;
794 retval = g_malloc (len + 1);
795 memcpy (retval, file_name + base + 1, len);
801 * g_path_is_absolute:
802 * @file_name: a file name.
804 * Returns %TRUE if the given @file_name is an absolute file name,
805 * i.e. it contains a full path from the root directory such as "/usr/local"
806 * on UNIX or "C:\windows" on Windows systems.
808 * Returns: %TRUE if @file_name is an absolute path.
811 g_path_is_absolute (const gchar *file_name)
813 g_return_val_if_fail (file_name != NULL, FALSE);
815 if (G_IS_DIR_SEPARATOR (file_name[0]))
819 /* Recognize drive letter on native Windows */
820 if (g_ascii_isalpha (file_name[0]) &&
821 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
823 #endif /* G_OS_WIN32 */
830 * @file_name: a file name.
832 * Returns a pointer into @file_name after the root component, i.e. after
833 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
834 * path it returns %NULL.
836 * Returns: a pointer into @file_name after the root component.
838 G_CONST_RETURN gchar*
839 g_path_skip_root (const gchar *file_name)
841 g_return_val_if_fail (file_name != NULL, NULL);
843 #ifdef G_PLATFORM_WIN32
844 /* Skip \\server\share or //server/share */
845 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
846 G_IS_DIR_SEPARATOR (file_name[1]) &&
848 !G_IS_DIR_SEPARATOR (file_name[2]))
852 p = strchr (file_name + 2, G_DIR_SEPARATOR);
855 gchar *q = strchr (file_name + 2, '/');
856 if (p == NULL || (q != NULL && q < p))
866 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
869 /* Possibly skip a backslash after the share name */
870 if (G_IS_DIR_SEPARATOR (file_name[0]))
873 return (gchar *)file_name;
878 /* Skip initial slashes */
879 if (G_IS_DIR_SEPARATOR (file_name[0]))
881 while (G_IS_DIR_SEPARATOR (file_name[0]))
883 return (gchar *)file_name;
888 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
889 return (gchar *)file_name + 3;
896 * g_path_get_dirname:
897 * @file_name: the name of the file.
899 * Gets the directory components of a file name. If the file name has no
900 * directory components "." is returned. The returned string should be
901 * freed when no longer needed.
903 * Returns: the directory components of the file.
906 g_path_get_dirname (const gchar *file_name)
908 register gchar *base;
911 g_return_val_if_fail (file_name != NULL, NULL);
913 base = strrchr (file_name, G_DIR_SEPARATOR);
916 gchar *q = strrchr (file_name, '/');
917 if (base == NULL || (q != NULL && q > base))
924 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
926 gchar drive_colon_dot[4];
928 drive_colon_dot[0] = file_name[0];
929 drive_colon_dot[1] = ':';
930 drive_colon_dot[2] = '.';
931 drive_colon_dot[3] = '\0';
933 return g_strdup (drive_colon_dot);
936 return g_strdup (".");
939 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
943 /* base points to the char before the last slash.
945 * In case file_name is the root of a drive (X:\) or a child of the
946 * root of a drive (X:\foo), include the slash.
948 * In case file_name is the root share of an UNC path
949 * (\\server\share), add a slash, returning \\server\share\ .
951 * In case file_name is a direct child of a share in an UNC path
952 * (\\server\share\foo), include the slash after the share name,
953 * returning \\server\share\ .
955 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
957 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
958 G_IS_DIR_SEPARATOR (file_name[1]) &&
960 !G_IS_DIR_SEPARATOR (file_name[2]) &&
961 base >= file_name + 2)
963 const gchar *p = file_name + 2;
964 while (*p && !G_IS_DIR_SEPARATOR (*p))
968 len = (guint) strlen (file_name) + 1;
969 base = g_new (gchar, len + 1);
970 strcpy (base, file_name);
971 base[len-1] = G_DIR_SEPARATOR;
975 if (G_IS_DIR_SEPARATOR (*p))
978 while (*p && !G_IS_DIR_SEPARATOR (*p))
986 len = (guint) 1 + base - file_name;
988 base = g_new (gchar, len + 1);
989 g_memmove (base, file_name, len);
998 * Gets the current directory.
999 * The returned string should be freed when no longer needed. The encoding
1000 * of the returned string is system defined. On Windows, it is always UTF-8.
1002 * Returns: the current directory.
1005 g_get_current_dir (void)
1010 wchar_t dummy[2], *wdir;
1013 len = GetCurrentDirectoryW (2, dummy);
1014 wdir = g_new (wchar_t, len);
1016 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1017 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1022 dir = g_strdup ("\\");
1028 gchar *buffer = NULL;
1030 static gulong max_len = 0;
1033 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1035 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1036 * and, if that wasn't bad enough, hangs in doing so.
1038 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1039 buffer = g_new (gchar, max_len + 1);
1041 dir = getwd (buffer);
1042 #else /* !sun || !HAVE_GETCWD */
1043 while (max_len < G_MAXULONG / 2)
1046 buffer = g_new (gchar, max_len + 1);
1048 dir = getcwd (buffer, max_len);
1050 if (dir || errno != ERANGE)
1055 #endif /* !sun || !HAVE_GETCWD */
1057 if (!dir || !*buffer)
1059 /* hm, should we g_error() out here?
1060 * this can happen if e.g. "./" has mode \0000
1062 buffer[0] = G_DIR_SEPARATOR;
1066 dir = g_strdup (buffer);
1075 * @variable: the environment variable to get, in the GLib file name encoding.
1077 * Returns the value of an environment variable. The name and value
1078 * are in the GLib file name encoding. On UNIX, this means the actual
1079 * bytes which might or might not be in some consistent character set
1080 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1081 * environment variable's value contains references to other
1082 * environment variables, they are expanded.
1084 * Return value: the value of the environment variable, or %NULL if
1085 * the environment variable is not found. The returned string may be
1086 * overwritten by the next call to g_getenv(), g_setenv() or
1089 G_CONST_RETURN gchar*
1090 g_getenv (const gchar *variable)
1094 g_return_val_if_fail (variable != NULL, NULL);
1096 return getenv (variable);
1098 #else /* G_OS_WIN32 */
1102 wchar_t dummy[2], *wname, *wvalue;
1105 g_return_val_if_fail (variable != NULL, NULL);
1106 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1108 /* On Windows NT, it is relatively typical that environment
1109 * variables contain references to other environment variables. If
1110 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1111 * environment variables would be stored in the Registry as
1112 * REG_EXPAND_SZ type values, and would then get automatically
1113 * expanded before a program sees them. But there is broken software
1114 * that stores environment variables as REG_SZ values even if they
1115 * contain references to other environment variables.)
1118 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1120 len = GetEnvironmentVariableW (wname, dummy, 2);
1130 wvalue = g_new (wchar_t, len);
1132 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1139 if (wcschr (wvalue, L'%') != NULL)
1141 wchar_t *tem = wvalue;
1143 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1147 wvalue = g_new (wchar_t, len);
1149 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1159 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1164 quark = g_quark_from_string (value);
1167 return g_quark_to_string (quark);
1169 #endif /* G_OS_WIN32 */
1172 /* _g_getenv_nomalloc
1173 * this function does a getenv() without doing any kind of allocation
1174 * through glib. it's suitable for chars <= 127 only (both, for the
1175 * variable name and the contents) and for contents < 1024 chars in
1176 * length. also, it aliases "" to a NULL return value.
1179 _g_getenv_nomalloc (const gchar *variable,
1182 const gchar *retval = getenv (variable);
1183 if (retval && retval[0])
1185 gint l = strlen (retval);
1188 strncpy (buffer, retval, l);
1198 * @variable: the environment variable to set, must not contain '='.
1199 * @value: the value for to set the variable to.
1200 * @overwrite: whether to change the variable if it already exists.
1202 * Sets an environment variable. Both the variable's name and value
1203 * should be in the GLib file name encoding. On UNIX, this means that
1204 * they can be any sequence of bytes. On Windows, they should be in
1207 * Note that on some systems, when variables are overwritten, the memory
1208 * used for the previous variables and its value isn't reclaimed.
1210 * Returns: %FALSE if the environment variable couldn't be set.
1215 g_setenv (const gchar *variable,
1226 g_return_val_if_fail (variable != NULL, FALSE);
1227 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1230 result = setenv (variable, value, overwrite);
1232 if (!overwrite && getenv (variable) != NULL)
1235 /* This results in a leak when you overwrite existing
1236 * settings. It would be fairly easy to fix this by keeping
1237 * our own parallel array or hash table.
1239 string = g_strconcat (variable, "=", value, NULL);
1240 result = putenv (string);
1244 #else /* G_OS_WIN32 */
1247 wchar_t *wname, *wvalue, *wassignment;
1250 g_return_val_if_fail (variable != NULL, FALSE);
1251 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1252 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1253 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1255 if (!overwrite && g_getenv (variable) != NULL)
1258 /* We want to (if possible) set both the environment variable copy
1259 * kept by the C runtime and the one kept by the system.
1261 * We can't use only the C runtime's putenv or _wputenv() as that
1262 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1263 * (with main() and not wmain()). In a "main()" app the C runtime
1264 * initializes the C runtime's environment table by converting the
1265 * real (wide char) environment variables to system codepage, thus
1266 * breaking those that aren't representable in the system codepage.
1268 * As the C runtime's putenv() will also set the system copy, we do
1269 * the putenv() first, then call SetEnvironmentValueW ourselves.
1272 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1273 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1274 tem = g_strconcat (variable, "=", value, NULL);
1275 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1278 _wputenv (wassignment);
1279 g_free (wassignment);
1281 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1288 #endif /* G_OS_WIN32 */
1291 #ifdef HAVE__NSGETENVIRON
1292 #define environ (*_NSGetEnviron())
1293 #elif !defined(G_OS_WIN32)
1295 /* According to the Single Unix Specification, environ is not in
1296 * any system header, although unistd.h often declares it.
1298 extern char **environ;
1303 * @variable: the environment variable to remove, must not contain '='.
1305 * Removes an environment variable from the environment.
1307 * Note that on some systems, when variables are overwritten, the memory
1308 * used for the previous variables and its value isn't reclaimed.
1309 * Furthermore, this function can't be guaranteed to operate in a
1315 g_unsetenv (const gchar *variable)
1319 #ifdef HAVE_UNSETENV
1320 g_return_if_fail (variable != NULL);
1321 g_return_if_fail (strchr (variable, '=') == NULL);
1323 unsetenv (variable);
1324 #else /* !HAVE_UNSETENV */
1328 g_return_if_fail (variable != NULL);
1329 g_return_if_fail (strchr (variable, '=') == NULL);
1331 len = strlen (variable);
1333 /* Mess directly with the environ array.
1334 * This seems to be the only portable way to do this.
1336 * Note that we remove *all* environment entries for
1337 * the variable name, not just the first.
1342 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1350 #endif /* !HAVE_UNSETENV */
1352 #else /* G_OS_WIN32 */
1354 wchar_t *wname, *wassignment;
1357 g_return_if_fail (variable != NULL);
1358 g_return_if_fail (strchr (variable, '=') == NULL);
1359 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1361 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1362 tem = g_strconcat (variable, "=", NULL);
1363 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1366 _wputenv (wassignment);
1367 g_free (wassignment);
1369 SetEnvironmentVariableW (wname, NULL);
1373 #endif /* G_OS_WIN32 */
1379 * Gets the names of all variables set in the environment.
1381 * Returns: a %NULL-terminated list of strings which must be freed
1382 * with g_strfreev().
1384 * Programs that want to be portable to Windows should typically use
1385 * this function and g_getenv() instead of using the environ array
1386 * from the C library directly. On Windows, the strings in the environ
1387 * array are in system codepage encoding, while in most of the typical
1388 * use cases for environment variables in GLib-using programs you want
1389 * the UTF-8 encoding that this function and g_getenv() provide.
1397 gchar **result, *eq;
1400 len = g_strv_length (environ);
1401 result = g_new0 (gchar *, len + 1);
1404 for (i = 0; i < len; i++)
1406 eq = strchr (environ[i], '=');
1408 result[j++] = g_strndup (environ[i], eq - environ[i]);
1415 gchar **result, *eq;
1419 p = (wchar_t *) GetEnvironmentStringsW ();
1425 q += wcslen (q) + 1;
1429 result = g_new0 (gchar *, len + 1);
1435 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1436 if (result[j] != NULL)
1438 eq = strchr (result[j], '=');
1439 if (eq && eq > result[j])
1447 q += wcslen (q) + 1;
1450 FreeEnvironmentStringsW (p);
1456 G_LOCK_DEFINE_STATIC (g_utils_global);
1458 static gchar *g_tmp_dir = NULL;
1459 static gchar *g_user_name = NULL;
1460 static gchar *g_real_name = NULL;
1461 static gchar *g_home_dir = NULL;
1462 static gchar *g_host_name = NULL;
1465 /* System codepage versions of the above, kept at file level so that they,
1466 * too, are produced only once.
1468 static gchar *g_tmp_dir_cp = NULL;
1469 static gchar *g_user_name_cp = NULL;
1470 static gchar *g_real_name_cp = NULL;
1471 static gchar *g_home_dir_cp = NULL;
1474 static gchar *g_user_data_dir = NULL;
1475 static gchar **g_system_data_dirs = NULL;
1476 static gchar *g_user_cache_dir = NULL;
1477 static gchar *g_user_config_dir = NULL;
1478 static gchar **g_system_config_dirs = NULL;
1480 static gchar **g_user_special_dirs = NULL;
1482 /* fifteen minutes of fame for everybody */
1483 #define G_USER_DIRS_EXPIRE 15 * 60
1488 get_special_folder (int csidl)
1490 wchar_t path[MAX_PATH+1];
1492 LPITEMIDLIST pidl = NULL;
1494 gchar *retval = NULL;
1496 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1499 b = SHGetPathFromIDListW (pidl, path);
1501 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1502 CoTaskMemFree (pidl);
1508 get_windows_directory_root (void)
1510 wchar_t wwindowsdir[MAX_PATH];
1512 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1514 /* Usually X:\Windows, but in terminal server environments
1515 * might be an UNC path, AFAIK.
1517 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1520 if (windowsdir == NULL)
1521 return g_strdup ("C:\\");
1523 p = (char *) g_path_skip_root (windowsdir);
1524 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1530 return g_strdup ("C:\\");
1535 /* HOLDS: g_utils_global_lock */
1537 g_get_any_init_do (void)
1539 gchar hostname[100];
1541 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1542 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1543 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1544 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1545 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1548 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1549 g_tmp_dir = get_windows_directory_root ();
1552 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1555 g_tmp_dir = g_strdup (P_tmpdir);
1556 k = strlen (g_tmp_dir);
1557 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1558 g_tmp_dir[k - 1] = '\0';
1562 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1564 g_tmp_dir = g_strdup ("/tmp");
1566 #endif /* !G_OS_WIN32 */
1569 /* We check $HOME first for Win32, though it is a last resort for Unix
1570 * where we prefer the results of getpwuid().
1572 g_home_dir = g_strdup (g_getenv ("HOME"));
1574 /* Only believe HOME if it is an absolute path and exists */
1577 if (!(g_path_is_absolute (g_home_dir) &&
1578 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1580 g_free (g_home_dir);
1585 /* In case HOME is Unix-style (it happens), convert it to
1591 while ((p = strchr (g_home_dir, '/')) != NULL)
1597 /* USERPROFILE is probably the closest equivalent to $HOME? */
1598 if (g_getenv ("USERPROFILE") != NULL)
1599 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1603 g_home_dir = get_special_folder (CSIDL_PROFILE);
1606 g_home_dir = get_windows_directory_root ();
1607 #endif /* G_OS_WIN32 */
1611 struct passwd *pw = NULL;
1612 gpointer buffer = NULL;
1616 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1618 # ifdef _SC_GETPW_R_SIZE_MAX
1619 /* This reurns the maximum length */
1620 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1624 # else /* _SC_GETPW_R_SIZE_MAX */
1626 # endif /* _SC_GETPW_R_SIZE_MAX */
1628 logname = (gchar *) g_getenv ("LOGNAME");
1633 /* we allocate 6 extra bytes to work around a bug in
1634 * Mac OS < 10.3. See #156446
1636 buffer = g_malloc (bufsize + 6);
1639 # ifdef HAVE_POSIX_GETPWUID_R
1641 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1642 if (!pw || (pw->pw_uid != getuid ())) {
1643 /* LOGNAME is lying, fall back to looking up the uid */
1644 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1647 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1649 error = error < 0 ? errno : error;
1650 # else /* HAVE_NONPOSIX_GETPWUID_R */
1651 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1652 # if defined(_AIX) || defined(__hpux)
1653 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1654 pw = error == 0 ? &pwd : NULL;
1657 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1658 if (!pw || (pw->pw_uid != getuid ())) {
1659 /* LOGNAME is lying, fall back to looking up the uid */
1660 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1663 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1665 error = pw ? 0 : errno;
1667 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1671 /* we bail out prematurely if the user id can't be found
1672 * (should be pretty rare case actually), or if the buffer
1673 * should be sufficiently big and lookups are still not
1676 if (error == 0 || error == ENOENT)
1678 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1679 (gulong) getuid ());
1682 if (bufsize > 32 * 1024)
1684 g_warning ("getpwuid_r(): failed due to: %s.",
1685 g_strerror (error));
1693 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1698 pw = getpwuid (getuid ());
1703 g_user_name = g_strdup (pw->pw_name);
1705 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1707 gchar **gecos_fields;
1710 /* split the gecos field and substitute '&' */
1711 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1712 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1713 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1714 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1715 g_strfreev (gecos_fields);
1716 g_strfreev (name_parts);
1720 g_home_dir = g_strdup (pw->pw_dir);
1725 #else /* !HAVE_PWD_H */
1729 guint len = UNLEN+1;
1730 wchar_t buffer[UNLEN+1];
1732 if (GetUserNameW (buffer, (LPDWORD) &len))
1734 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1735 g_real_name = g_strdup (g_user_name);
1738 #endif /* G_OS_WIN32 */
1740 #endif /* !HAVE_PWD_H */
1744 g_home_dir = g_strdup (g_getenv ("HOME"));
1748 /* change '\\' in %HOME% to '/' */
1749 g_strdelimit (g_home_dir, "\\",'/');
1752 g_user_name = g_strdup ("somebody");
1754 g_real_name = g_strdup ("Unknown");
1758 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1760 DWORD size = sizeof (hostname);
1761 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1763 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1767 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1768 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1769 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1772 g_tmp_dir_cp = g_strdup ("\\");
1773 if (!g_user_name_cp)
1774 g_user_name_cp = g_strdup ("somebody");
1775 if (!g_real_name_cp)
1776 g_real_name_cp = g_strdup ("Unknown");
1778 /* home_dir might be NULL, unlike tmp_dir, user_name and
1782 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1784 g_home_dir_cp = NULL;
1785 #endif /* G_OS_WIN32 */
1789 g_get_any_init (void)
1792 g_get_any_init_do ();
1796 g_get_any_init_locked (void)
1798 G_LOCK (g_utils_global);
1800 G_UNLOCK (g_utils_global);
1807 * Gets the user name of the current user. The encoding of the returned
1808 * string is system-defined. On UNIX, it might be the preferred file name
1809 * encoding, or something else, and there is no guarantee that it is even
1810 * consistent on a machine. On Windows, it is always UTF-8.
1812 * Returns: the user name of the current user.
1814 G_CONST_RETURN gchar*
1815 g_get_user_name (void)
1817 g_get_any_init_locked ();
1824 * Gets the real name of the user. This usually comes from the user's entry
1825 * in the <filename>passwd</filename> file. The encoding of the returned
1826 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1827 * If the real user name cannot be determined, the string "Unknown" is
1830 * Returns: the user's real name.
1832 G_CONST_RETURN gchar*
1833 g_get_real_name (void)
1835 g_get_any_init_locked ();
1842 * Gets the current user's home directory as defined in the
1843 * password database.
1845 * Note that in contrast to traditional UNIX tools, this function
1846 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1847 * environment variable.
1849 * One of the reasons for this decision is that applications in many
1850 * cases need special handling to deal with the case where
1851 * <envar>HOME</envar> is
1853 * <member>Not owned by the user</member>
1854 * <member>Not writeable</member>
1855 * <member>Not even readable</member>
1857 * Since applications are in general <emphasis>not</emphasis> written
1858 * to deal with these situations it was considered better to make
1859 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1860 * return the real home directory for the user. If applications
1861 * want to pay attention to <envar>HOME</envar>, they can do:
1863 * const char *homedir = g_getenv ("HOME");
1865 * homedir = g_get_home_dir (<!-- -->);
1868 * Returns: the current user's home directory
1870 G_CONST_RETURN gchar*
1871 g_get_home_dir (void)
1873 g_get_any_init_locked ();
1880 * Gets the directory to use for temporary files. This is found from
1881 * inspecting the environment variables <envar>TMPDIR</envar>,
1882 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1883 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1884 * The encoding of the returned string is system-defined. On Windows,
1885 * it is always UTF-8. The return value is never %NULL or the empty string.
1887 * Returns: the directory to use for temporary files.
1889 G_CONST_RETURN gchar*
1890 g_get_tmp_dir (void)
1892 g_get_any_init_locked ();
1899 * Return a name for the machine.
1901 * The returned name is not necessarily a fully-qualified domain name,
1902 * or even present in DNS or some other name service at all. It need
1903 * not even be unique on your local network or site, but usually it
1904 * is. Callers should not rely on the return value having any specific
1905 * properties like uniqueness for security purposes. Even if the name
1906 * of the machine is changed while an application is running, the
1907 * return value from this function does not change. The returned
1908 * string is owned by GLib and should not be modified or freed. If no
1909 * name can be determined, a default fixed string "localhost" is
1912 * Returns: the host name of the machine.
1917 g_get_host_name (void)
1919 g_get_any_init_locked ();
1923 G_LOCK_DEFINE_STATIC (g_prgname);
1924 static gchar *g_prgname = NULL;
1929 * Gets the name of the program. This name should <emphasis>not</emphasis>
1930 * be localized, contrast with g_get_application_name().
1931 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1932 * which is called by gtk_init(). The program name is found by taking
1933 * the last component of <literal>argv[0]</literal>.)
1935 * Returns: the name of the program. The returned string belongs
1936 * to GLib and must not be modified or freed.
1939 g_get_prgname (void)
1945 if (g_prgname == NULL)
1947 static gboolean beenhere = FALSE;
1951 gchar *utf8_buf = NULL;
1952 wchar_t buf[MAX_PATH+1];
1955 if (GetModuleFileNameW (GetModuleHandle (NULL),
1956 buf, G_N_ELEMENTS (buf)) > 0)
1957 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1961 g_prgname = g_path_get_basename (utf8_buf);
1968 G_UNLOCK (g_prgname);
1975 * @prgname: the name of the program.
1977 * Sets the name of the program. This name should <emphasis>not</emphasis>
1978 * be localized, contrast with g_set_application_name(). Note that for
1979 * thread-safety reasons this function can only be called once.
1982 g_set_prgname (const gchar *prgname)
1986 g_prgname = g_strdup (prgname);
1987 G_UNLOCK (g_prgname);
1990 G_LOCK_DEFINE_STATIC (g_application_name);
1991 static gchar *g_application_name = NULL;
1994 * g_get_application_name:
1996 * Gets a human-readable name for the application, as set by
1997 * g_set_application_name(). This name should be localized if
1998 * possible, and is intended for display to the user. Contrast with
1999 * g_get_prgname(), which gets a non-localized name. If
2000 * g_set_application_name() has not been called, returns the result of
2001 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2004 * Return value: human-readable application name. may return %NULL
2008 G_CONST_RETURN gchar*
2009 g_get_application_name (void)
2013 G_LOCK (g_application_name);
2014 retval = g_application_name;
2015 G_UNLOCK (g_application_name);
2018 return g_get_prgname ();
2024 * g_set_application_name:
2025 * @application_name: localized name of the application
2027 * Sets a human-readable name for the application. This name should be
2028 * localized if possible, and is intended for display to the user.
2029 * Contrast with g_set_prgname(), which sets a non-localized name.
2030 * g_set_prgname() will be called automatically by gtk_init(),
2031 * but g_set_application_name() will not.
2033 * Note that for thread safety reasons, this function can only
2036 * The application name will be used in contexts such as error messages,
2037 * or when displaying an application's name in the task list.
2042 g_set_application_name (const gchar *application_name)
2044 gboolean already_set = FALSE;
2046 G_LOCK (g_application_name);
2047 if (g_application_name)
2050 g_application_name = g_strdup (application_name);
2051 G_UNLOCK (g_application_name);
2054 g_warning ("g_set_application_name() called multiple times");
2058 * g_get_user_data_dir:
2060 * Returns a base directory in which to access application data such
2061 * as icons that is customized for a particular user.
2063 * On UNIX platforms this is determined using the mechanisms described in
2064 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2065 * XDG Base Directory Specification</ulink>.
2066 * In this case the directory retrieved will be XDG_DATA_HOME.
2068 * On Windows this is the folder to use for local (as opposed to
2069 * roaming) application data. See documentation for
2070 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2071 * what g_get_user_config_dir() returns.
2073 * Return value: a string owned by GLib that must not be modified
2077 G_CONST_RETURN gchar*
2078 g_get_user_data_dir (void)
2082 G_LOCK (g_utils_global);
2084 if (!g_user_data_dir)
2087 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2089 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2091 if (data_dir && data_dir[0])
2092 data_dir = g_strdup (data_dir);
2094 if (!data_dir || !data_dir[0])
2099 data_dir = g_build_filename (g_home_dir, ".local",
2102 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2106 g_user_data_dir = data_dir;
2109 data_dir = g_user_data_dir;
2111 G_UNLOCK (g_utils_global);
2117 g_init_user_config_dir (void)
2121 if (!g_user_config_dir)
2124 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2126 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2128 if (config_dir && config_dir[0])
2129 config_dir = g_strdup (config_dir);
2131 if (!config_dir || !config_dir[0])
2136 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2138 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2141 g_user_config_dir = config_dir;
2146 * g_get_user_config_dir:
2148 * Returns a base directory in which to store user-specific application
2149 * configuration information such as user preferences and settings.
2151 * On UNIX platforms this is determined using the mechanisms described in
2152 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2153 * XDG Base Directory Specification</ulink>.
2154 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2156 * On Windows this is the folder to use for local (as opposed to
2157 * roaming) application data. See documentation for
2158 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2159 * what g_get_user_data_dir() returns.
2161 * Return value: a string owned by GLib that must not be modified
2165 G_CONST_RETURN gchar*
2166 g_get_user_config_dir (void)
2168 G_LOCK (g_utils_global);
2170 g_init_user_config_dir ();
2172 G_UNLOCK (g_utils_global);
2174 return g_user_config_dir;
2178 * g_get_user_cache_dir:
2180 * Returns a base directory in which to store non-essential, cached
2181 * data specific to particular user.
2183 * On UNIX platforms this is determined using the mechanisms described in
2184 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2185 * XDG Base Directory Specification</ulink>.
2186 * In this case the directory retrieved will be XDG_CACHE_HOME.
2188 * On Windows is the directory that serves as a common repository for
2189 * temporary Internet files. A typical path is
2190 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2191 * See documentation for CSIDL_INTERNET_CACHE.
2193 * Return value: a string owned by GLib that must not be modified
2197 G_CONST_RETURN gchar*
2198 g_get_user_cache_dir (void)
2202 G_LOCK (g_utils_global);
2204 if (!g_user_cache_dir)
2207 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2209 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2211 if (cache_dir && cache_dir[0])
2212 cache_dir = g_strdup (cache_dir);
2214 if (!cache_dir || !cache_dir[0])
2219 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2221 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2223 g_user_cache_dir = cache_dir;
2226 cache_dir = g_user_cache_dir;
2228 G_UNLOCK (g_utils_global);
2236 find_folder (OSType type)
2238 gchar *filename = NULL;
2241 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2243 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2247 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2251 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2255 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2257 CFStringGetCString (path, filename,
2258 CFStringGetLength (path) * 3 + 1,
2259 kCFStringEncodingUTF8);
2273 load_user_special_dirs (void)
2275 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2276 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2277 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2278 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2279 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2280 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2281 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2282 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2285 #endif /* HAVE_CARBON */
2287 #if defined(G_OS_WIN32)
2289 load_user_special_dirs (void)
2291 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2295 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2297 static const GUID FOLDERID_Downloads =
2298 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2299 static const GUID FOLDERID_Public =
2300 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2304 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2305 "SHGetKnownFolderPath");
2307 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2308 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2310 if (p_SHGetKnownFolderPath == NULL)
2312 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2317 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2318 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2319 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2320 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2321 CoTaskMemFree (wcp);
2324 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2325 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2327 if (p_SHGetKnownFolderPath == NULL)
2330 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2335 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2336 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2337 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2338 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2339 CoTaskMemFree (wcp);
2342 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2343 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2345 #endif /* G_OS_WIN32 */
2347 static void g_init_user_config_dir (void);
2349 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2351 /* adapted from xdg-user-dir-lookup.c
2353 * Copyright (C) 2007 Red Hat Inc.
2355 * Permission is hereby granted, free of charge, to any person
2356 * obtaining a copy of this software and associated documentation files
2357 * (the "Software"), to deal in the Software without restriction,
2358 * including without limitation the rights to use, copy, modify, merge,
2359 * publish, distribute, sublicense, and/or sell copies of the Software,
2360 * and to permit persons to whom the Software is furnished to do so,
2361 * subject to the following conditions:
2363 * The above copyright notice and this permission notice shall be
2364 * included in all copies or substantial portions of the Software.
2366 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2367 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2368 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2369 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2370 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2371 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2372 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2376 load_user_special_dirs (void)
2383 g_init_user_config_dir ();
2384 config_file = g_build_filename (g_user_config_dir,
2388 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2390 g_free (config_file);
2394 lines = g_strsplit (data, "\n", -1);
2395 n_lines = g_strv_length (lines);
2398 for (i = 0; i < n_lines; i++)
2400 gchar *buffer = lines[i];
2403 gboolean is_relative = FALSE;
2404 GUserDirectory directory;
2406 /* Remove newline at end */
2407 len = strlen (buffer);
2408 if (len > 0 && buffer[len - 1] == '\n')
2409 buffer[len - 1] = 0;
2412 while (*p == ' ' || *p == '\t')
2415 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2417 directory = G_USER_DIRECTORY_DESKTOP;
2418 p += strlen ("XDG_DESKTOP_DIR");
2420 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2422 directory = G_USER_DIRECTORY_DOCUMENTS;
2423 p += strlen ("XDG_DOCUMENTS_DIR");
2425 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2427 directory = G_USER_DIRECTORY_DOWNLOAD;
2428 p += strlen ("XDG_DOWNLOAD_DIR");
2430 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2432 directory = G_USER_DIRECTORY_MUSIC;
2433 p += strlen ("XDG_MUSIC_DIR");
2435 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2437 directory = G_USER_DIRECTORY_PICTURES;
2438 p += strlen ("XDG_PICTURES_DIR");
2440 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2442 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2443 p += strlen ("XDG_PUBLICSHARE_DIR");
2445 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2447 directory = G_USER_DIRECTORY_TEMPLATES;
2448 p += strlen ("XDG_TEMPLATES_DIR");
2450 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2452 directory = G_USER_DIRECTORY_VIDEOS;
2453 p += strlen ("XDG_VIDEOS_DIR");
2458 while (*p == ' ' || *p == '\t')
2465 while (*p == ' ' || *p == '\t')
2472 if (strncmp (p, "$HOME", 5) == 0)
2480 d = strrchr (p, '"');
2487 /* remove trailing slashes */
2489 if (d[len - 1] == '/')
2495 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2498 g_user_special_dirs[directory] = g_strdup (d);
2502 g_free (config_file);
2505 #endif /* G_OS_UNIX && !HAVE_CARBON */
2509 * g_reload_user_special_dirs_cache:
2511 * Resets the cache used for g_get_user_special_dir(), so
2512 * that the latest on-disk version is used. Call this only
2513 * if you just changed the data on disk yourself.
2515 * Due to threadsafety issues this may cause leaking of strings
2516 * that were previously returned from g_get_user_special_dir()
2517 * that can't be freed. We ensure to only leak the data for
2518 * the directories that actually changed value though.
2523 g_reload_user_special_dirs_cache (void)
2527 G_LOCK (g_utils_global);
2529 if (g_user_special_dirs != NULL)
2531 /* save a copy of the pointer, to check if some memory can be preserved */
2532 char **old_g_user_special_dirs = g_user_special_dirs;
2535 /* recreate and reload our cache */
2536 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2537 load_user_special_dirs ();
2539 /* only leak changed directories */
2540 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2542 old_val = old_g_user_special_dirs[i];
2543 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2546 g_free (g_user_special_dirs[i]);
2547 g_user_special_dirs[i] = old_val;
2553 /* free the old array */
2554 g_free (old_g_user_special_dirs);
2557 G_UNLOCK (g_utils_global);
2561 * g_get_user_special_dir:
2562 * @directory: the logical id of special directory
2564 * Returns the full path of a special directory using its logical id.
2566 * On Unix this is done using the XDG special user directories.
2567 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2568 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2569 * user directories have not been set up.
2571 * Depending on the platform, the user might be able to change the path
2572 * of the special directory without requiring the session to restart; GLib
2573 * will not reflect any change once the special directories are loaded.
2575 * Return value: the path to the specified special directory, or %NULL
2576 * if the logical id was not found. The returned string is owned by
2577 * GLib and should not be modified or freed.
2581 G_CONST_RETURN gchar *
2582 g_get_user_special_dir (GUserDirectory directory)
2584 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2585 directory < G_USER_N_DIRECTORIES, NULL);
2587 G_LOCK (g_utils_global);
2589 if (G_UNLIKELY (g_user_special_dirs == NULL))
2591 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2593 load_user_special_dirs ();
2595 /* Special-case desktop for historical compatibility */
2596 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2600 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2601 g_build_filename (g_home_dir, "Desktop", NULL);
2605 G_UNLOCK (g_utils_global);
2607 return g_user_special_dirs[directory];
2612 #undef g_get_system_data_dirs
2615 get_module_for_address (gconstpointer address)
2617 /* Holds the g_utils_global lock */
2619 static gboolean beenhere = FALSE;
2620 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2621 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2622 HMODULE hmodule = NULL;
2629 p_GetModuleHandleExA =
2630 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2631 "GetModuleHandleExA");
2635 if (p_GetModuleHandleExA == NULL ||
2636 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2637 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2640 MEMORY_BASIC_INFORMATION mbi;
2641 VirtualQuery (address, &mbi, sizeof (mbi));
2642 hmodule = (HMODULE) mbi.AllocationBase;
2649 get_module_share_dir (gconstpointer address)
2655 hmodule = get_module_for_address (address);
2656 if (hmodule == NULL)
2659 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2660 retval = g_build_filename (filename, "share", NULL);
2666 G_CONST_RETURN gchar * G_CONST_RETURN *
2667 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2671 static GHashTable *per_module_data_dirs = NULL;
2676 if (address_of_function)
2678 G_LOCK (g_utils_global);
2679 hmodule = get_module_for_address (address_of_function);
2680 if (hmodule != NULL)
2682 if (per_module_data_dirs == NULL)
2683 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2686 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2690 G_UNLOCK (g_utils_global);
2691 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2697 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2699 /* Documents and Settings\All Users\Application Data */
2700 p = get_special_folder (CSIDL_COMMON_APPDATA);
2702 g_array_append_val (data_dirs, p);
2704 /* Documents and Settings\All Users\Documents */
2705 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2707 g_array_append_val (data_dirs, p);
2709 /* Using the above subfolders of Documents and Settings perhaps
2710 * makes sense from a Windows perspective.
2712 * But looking at the actual use cases of this function in GTK+
2713 * and GNOME software, what we really want is the "share"
2714 * subdirectory of the installation directory for the package
2715 * our caller is a part of.
2717 * The address_of_function parameter, if non-NULL, points to a
2718 * function in the calling module. Use that to determine that
2719 * module's installation folder, and use its "share" subfolder.
2721 * Additionally, also use the "share" subfolder of the installation
2722 * locations of GLib and the .exe file being run.
2724 * To guard against none of the above being what is really wanted,
2725 * callers of this function should have Win32-specific code to look
2726 * up their installation folder themselves, and handle a subfolder
2727 * "share" of it in the same way as the folders returned from this
2731 p = get_module_share_dir (address_of_function);
2733 g_array_append_val (data_dirs, p);
2735 if (glib_dll != NULL)
2737 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2738 p = g_build_filename (glib_root, "share", NULL);
2740 g_array_append_val (data_dirs, p);
2744 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2745 p = g_build_filename (exe_root, "share", NULL);
2747 g_array_append_val (data_dirs, p);
2750 retval = (gchar **) g_array_free (data_dirs, FALSE);
2752 if (address_of_function)
2754 if (hmodule != NULL)
2755 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2756 G_UNLOCK (g_utils_global);
2759 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2765 * g_get_system_data_dirs:
2767 * Returns an ordered list of base directories in which to access
2768 * system-wide application data.
2770 * On UNIX platforms this is determined using the mechanisms described in
2771 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2772 * XDG Base Directory Specification</ulink>
2773 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2775 * On Windows the first elements in the list are the Application Data
2776 * and Documents folders for All Users. (These can be determined only
2777 * on Windows 2000 or later and are not present in the list on other
2778 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2779 * CSIDL_COMMON_DOCUMENTS.
2781 * Then follows the "share" subfolder in the installation folder for
2782 * the package containing the DLL that calls this function, if it can
2785 * Finally the list contains the "share" subfolder in the installation
2786 * folder for GLib, and in the installation folder for the package the
2787 * application's .exe file belongs to.
2789 * The installation folders above are determined by looking up the
2790 * folder where the module (DLL or EXE) in question is located. If the
2791 * folder's name is "bin", its parent is used, otherwise the folder
2794 * Note that on Windows the returned list can vary depending on where
2795 * this function is called.
2797 * Return value: a %NULL-terminated array of strings owned by GLib that must
2798 * not be modified or freed.
2801 G_CONST_RETURN gchar * G_CONST_RETURN *
2802 g_get_system_data_dirs (void)
2804 gchar **data_dir_vector;
2806 G_LOCK (g_utils_global);
2808 if (!g_system_data_dirs)
2811 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2813 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2815 if (!data_dirs || !data_dirs[0])
2816 data_dirs = "/usr/local/share/:/usr/share/";
2818 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2821 g_system_data_dirs = data_dir_vector;
2824 data_dir_vector = g_system_data_dirs;
2826 G_UNLOCK (g_utils_global);
2828 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2832 * g_get_system_config_dirs:
2834 * Returns an ordered list of base directories in which to access
2835 * system-wide configuration information.
2837 * On UNIX platforms this is determined using the mechanisms described in
2838 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2839 * XDG Base Directory Specification</ulink>.
2840 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2842 * On Windows is the directory that contains application data for all users.
2843 * A typical path is C:\Documents and Settings\All Users\Application Data.
2844 * This folder is used for application data that is not user specific.
2845 * For example, an application can store a spell-check dictionary, a database
2846 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2847 * This information will not roam and is available to anyone using the computer.
2849 * Return value: a %NULL-terminated array of strings owned by GLib that must
2850 * not be modified or freed.
2853 G_CONST_RETURN gchar * G_CONST_RETURN *
2854 g_get_system_config_dirs (void)
2856 gchar *conf_dirs, **conf_dir_vector;
2858 G_LOCK (g_utils_global);
2860 if (!g_system_config_dirs)
2863 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2866 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2871 /* Return empty list */
2872 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2875 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2877 if (!conf_dirs || !conf_dirs[0])
2878 conf_dirs = "/etc/xdg";
2880 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2883 g_system_config_dirs = conf_dir_vector;
2886 conf_dir_vector = g_system_config_dirs;
2887 G_UNLOCK (g_utils_global);
2889 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2894 static GHashTable *alias_table = NULL;
2896 /* read an alias file for the locales */
2898 read_aliases (gchar *file)
2904 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2905 fp = fopen (file,"r");
2908 while (fgets (buf, 256, fp))
2914 /* Line is a comment */
2915 if ((buf[0] == '#') || (buf[0] == '\0'))
2918 /* Reads first column */
2919 for (p = buf, q = NULL; *p; p++) {
2920 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2923 while ((*q == '\t') || (*q == ' ')) {
2929 /* The line only had one column */
2930 if (!q || *q == '\0')
2933 /* Read second column */
2934 for (p = q; *p; p++) {
2935 if ((*p == '\t') || (*p == ' ')) {
2941 /* Add to alias table if necessary */
2942 if (!g_hash_table_lookup (alias_table, buf)) {
2943 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2952 unalias_lang (char *lang)
2959 read_aliases ("/usr/share/locale/locale.alias");
2962 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2967 static gboolean said_before = FALSE;
2969 g_warning ("Too many alias levels for a locale, "
2970 "may indicate a loop");
2979 /* Mask for components of locale spec. The ordering here is from
2980 * least significant to most significant
2984 COMPONENT_CODESET = 1 << 0,
2985 COMPONENT_TERRITORY = 1 << 1,
2986 COMPONENT_MODIFIER = 1 << 2
2989 /* Break an X/Open style locale specification into components
2992 explode_locale (const gchar *locale,
2998 const gchar *uscore_pos;
2999 const gchar *at_pos;
3000 const gchar *dot_pos;
3004 uscore_pos = strchr (locale, '_');
3005 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3006 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3010 mask |= COMPONENT_MODIFIER;
3011 *modifier = g_strdup (at_pos);
3014 at_pos = locale + strlen (locale);
3018 mask |= COMPONENT_CODESET;
3019 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3026 mask |= COMPONENT_TERRITORY;
3027 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3030 uscore_pos = dot_pos;
3032 *language = g_strndup (locale, uscore_pos - locale);
3038 * Compute all interesting variants for a given locale name -
3039 * by stripping off different components of the value.
3041 * For simplicity, we assume that the locale is in
3042 * X/Open format: language[_territory][.codeset][@modifier]
3044 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3045 * as well. We could just copy the code from glibc wholesale
3046 * but it is big, ugly, and complicated, so I'm reluctant
3047 * to do so when this should handle 99% of the time...
3050 _g_compute_locale_variants (const gchar *locale)
3052 GSList *retval = NULL;
3054 gchar *language = NULL;
3055 gchar *territory = NULL;
3056 gchar *codeset = NULL;
3057 gchar *modifier = NULL;
3062 g_return_val_if_fail (locale != NULL, NULL);
3064 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3066 /* Iterate through all possible combinations, from least attractive
3067 * to most attractive.
3069 for (i = 0; i <= mask; i++)
3070 if ((i & ~mask) == 0)
3072 gchar *val = g_strconcat (language,
3073 (i & COMPONENT_TERRITORY) ? territory : "",
3074 (i & COMPONENT_CODESET) ? codeset : "",
3075 (i & COMPONENT_MODIFIER) ? modifier : "",
3077 retval = g_slist_prepend (retval, val);
3081 if (mask & COMPONENT_CODESET)
3083 if (mask & COMPONENT_TERRITORY)
3085 if (mask & COMPONENT_MODIFIER)
3091 /* The following is (partly) taken from the gettext package.
3092 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3094 static const gchar *
3095 guess_category_value (const gchar *category_name)
3097 const gchar *retval;
3099 /* The highest priority value is the `LANGUAGE' environment
3100 variable. This is a GNU extension. */
3101 retval = g_getenv ("LANGUAGE");
3102 if ((retval != NULL) && (retval[0] != '\0'))
3105 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3106 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3107 systems this can be done by the `setlocale' function itself. */
3109 /* Setting of LC_ALL overwrites all other. */
3110 retval = g_getenv ("LC_ALL");
3111 if ((retval != NULL) && (retval[0] != '\0'))
3114 /* Next comes the name of the desired category. */
3115 retval = g_getenv (category_name);
3116 if ((retval != NULL) && (retval[0] != '\0'))
3119 /* Last possibility is the LANG environment variable. */
3120 retval = g_getenv ("LANG");
3121 if ((retval != NULL) && (retval[0] != '\0'))
3124 #ifdef G_PLATFORM_WIN32
3125 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3126 * LANG, which we already did above. Oh well. The main point of
3127 * calling g_win32_getlocale() is to get the thread's locale as used
3128 * by Windows and the Microsoft C runtime (in the "English_United
3129 * States" format) translated into the Unixish format.
3132 char *locale = g_win32_getlocale ();
3133 retval = g_intern_string (locale);
3142 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3144 struct _GLanguageNamesCache {
3146 gchar **language_names;
3150 language_names_cache_free (gpointer data)
3152 GLanguageNamesCache *cache = data;
3153 g_free (cache->languages);
3154 g_strfreev (cache->language_names);
3159 * g_get_language_names:
3161 * Computes a list of applicable locale names, which can be used to
3162 * e.g. construct locale-dependent filenames or search paths. The returned
3163 * list is sorted from most desirable to least desirable and always contains
3164 * the default locale "C".
3166 * For example, if LANGUAGE=de:en_US, then the returned list is
3167 * "de", "en_US", "en", "C".
3169 * This function consults the environment variables <envar>LANGUAGE</envar>,
3170 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3171 * to find the list of locales specified by the user.
3173 * Return value: a %NULL-terminated array of strings owned by GLib
3174 * that must not be modified or freed.
3178 G_CONST_RETURN gchar * G_CONST_RETURN *
3179 g_get_language_names (void)
3181 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3182 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3187 cache = g_new0 (GLanguageNamesCache, 1);
3188 g_static_private_set (&cache_private, cache, language_names_cache_free);
3191 value = guess_category_value ("LC_MESSAGES");
3195 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3202 g_free (cache->languages);
3203 g_strfreev (cache->language_names);
3204 cache->languages = g_strdup (value);
3206 alist = g_strsplit (value, ":", 0);
3208 for (a = alist; *a; a++)
3210 gchar *b = unalias_lang (*a);
3211 list = g_slist_concat (list, _g_compute_locale_variants (b));
3214 list = g_slist_append (list, g_strdup ("C"));
3216 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3217 for (l = list, i = 0; l; l = l->next, i++)
3218 languages[i] = l->data;
3219 languages[i] = NULL;
3221 g_slist_free (list);
3224 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3229 * @v: a #gpointer key
3231 * Converts a gpointer to a hash value.
3232 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3233 * when using pointers as keys in a #GHashTable.
3235 * Returns: a hash value corresponding to the key.
3238 g_direct_hash (gconstpointer v)
3240 return GPOINTER_TO_UINT (v);
3246 * @v2: a key to compare with @v1.
3248 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3249 * It can be passed to g_hash_table_new() as the @key_equal_func
3250 * parameter, when using pointers as keys in a #GHashTable.
3252 * Returns: %TRUE if the two keys match.
3255 g_direct_equal (gconstpointer v1,
3263 * @v1: a pointer to a #gint key.
3264 * @v2: a pointer to a #gint key to compare with @v1.
3266 * Compares the two #gint values being pointed to and returns
3267 * %TRUE if they are equal.
3268 * It can be passed to g_hash_table_new() as the @key_equal_func
3269 * parameter, when using pointers to integers as keys in a #GHashTable.
3271 * Returns: %TRUE if the two keys match.
3274 g_int_equal (gconstpointer v1,
3277 return *((const gint*) v1) == *((const gint*) v2);
3282 * @v: a pointer to a #gint key
3284 * Converts a pointer to a #gint to a hash value.
3285 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3286 * when using pointers to integers values as keys in a #GHashTable.
3288 * Returns: a hash value corresponding to the key.
3291 g_int_hash (gconstpointer v)
3293 return *(const gint*) v;
3298 * @v1: a pointer to a #gint64 key.
3299 * @v2: a pointer to a #gint64 key to compare with @v1.
3301 * Compares the two #gint64 values being pointed to and returns
3302 * %TRUE if they are equal.
3303 * It can be passed to g_hash_table_new() as the @key_equal_func
3304 * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3306 * Returns: %TRUE if the two keys match.
3311 g_int64_equal (gconstpointer v1,
3314 return *((const gint64*) v1) == *((const gint64*) v2);
3319 * @v: a pointer to a #gint64 key
3321 * Converts a pointer to a #gint64 to a hash value.
3322 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3323 * when using pointers to 64-bit integers values as keys in a #GHashTable.
3325 * Returns: a hash value corresponding to the key.
3330 g_int64_hash (gconstpointer v)
3332 return (guint) *(const gint64*) v;
3337 * @v1: a pointer to a #gdouble key.
3338 * @v2: a pointer to a #gdouble key to compare with @v1.
3340 * Compares the two #gdouble values being pointed to and returns
3341 * %TRUE if they are equal.
3342 * It can be passed to g_hash_table_new() as the @key_equal_func
3343 * parameter, when using pointers to doubles as keys in a #GHashTable.
3345 * Returns: %TRUE if the two keys match.
3350 g_double_equal (gconstpointer v1,
3353 return *((const gdouble*) v1) == *((const gdouble*) v2);
3358 * @v: a pointer to a #gdouble key
3360 * Converts a pointer to a #gdouble to a hash value.
3361 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3362 * when using pointers to doubles as keys in a #GHashTable.
3364 * Returns: a hash value corresponding to the key.
3369 g_double_hash (gconstpointer v)
3371 return (guint) *(const gdouble*) v;
3375 * g_nullify_pointer:
3376 * @nullify_location: the memory address of the pointer.
3378 * Set the pointer at the specified location to %NULL.
3381 g_nullify_pointer (gpointer *nullify_location)
3383 g_return_if_fail (nullify_location != NULL);
3385 *nullify_location = NULL;
3391 * Get the codeset for the current locale.
3393 * Return value: a newly allocated string containing the name
3394 * of the codeset. This string must be freed with g_free().
3397 g_get_codeset (void)
3399 const gchar *charset;
3401 g_get_charset (&charset);
3403 return g_strdup (charset);
3406 /* This is called from g_thread_init(). It's used to
3407 * initialize some static data in a threadsafe way.
3410 _g_utils_thread_init (void)
3412 g_get_language_names ();
3418 * _glib_get_locale_dir:
3420 * Return the path to the share\locale or lib\locale subfolder of the
3421 * GLib installation folder. The path is in the system codepage. We
3422 * have to use system codepage as bindtextdomain() doesn't have a
3426 _glib_get_locale_dir (void)
3428 gchar *install_dir = NULL, *locale_dir;
3429 gchar *retval = NULL;
3431 if (glib_dll != NULL)
3432 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3437 * Append "/share/locale" or "/lib/locale" depending on whether
3438 * autoconfigury detected GNU gettext or not.
3440 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3446 locale_dir = g_build_filename (install_dir, p, NULL);
3448 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3450 g_free (install_dir);
3451 g_free (locale_dir);
3457 return g_strdup ("");
3460 #undef GLIB_LOCALE_DIR
3462 #endif /* G_OS_WIN32 */
3466 * @str: The string to be translated
3468 * Returns the translated string from the glib translations.
3469 * This is an internal function and should only be used by
3470 * the internals of glib (such as libgio).
3472 * Returns: the transation of @str to the current locale
3474 G_CONST_RETURN gchar *
3475 glib_gettext (const gchar *str)
3477 static gboolean _glib_gettext_initialized = FALSE;
3479 if (!_glib_gettext_initialized)
3482 gchar *tmp = _glib_get_locale_dir ();
3483 bindtextdomain (GETTEXT_PACKAGE, tmp);
3486 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3488 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3489 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3491 _glib_gettext_initialized = TRUE;
3494 return g_dgettext (GETTEXT_PACKAGE, str);
3497 #if defined (G_OS_WIN32) && !defined (_WIN64)
3499 /* Binary compatibility versions. Not for newly compiled code. */
3501 #undef g_find_program_in_path
3504 g_find_program_in_path (const gchar *program)
3506 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3507 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3510 g_free (utf8_program);
3511 if (utf8_retval == NULL)
3513 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3514 g_free (utf8_retval);
3519 #undef g_get_current_dir
3522 g_get_current_dir (void)
3524 gchar *utf8_dir = g_get_current_dir_utf8 ();
3525 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3532 G_CONST_RETURN gchar*
3533 g_getenv (const gchar *variable)
3535 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3536 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3540 g_free (utf8_variable);
3543 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3544 quark = g_quark_from_string (value);
3547 return g_quark_to_string (quark);
3553 g_setenv (const gchar *variable,
3557 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3558 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3559 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3561 g_free (utf8_variable);
3562 g_free (utf8_value);
3570 g_unsetenv (const gchar *variable)
3572 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3574 g_unsetenv_utf8 (utf8_variable);
3576 g_free (utf8_variable);
3579 #undef g_get_user_name
3581 G_CONST_RETURN gchar*
3582 g_get_user_name (void)
3584 g_get_any_init_locked ();
3585 return g_user_name_cp;
3588 #undef g_get_real_name
3590 G_CONST_RETURN gchar*
3591 g_get_real_name (void)
3593 g_get_any_init_locked ();
3594 return g_real_name_cp;
3597 #undef g_get_home_dir
3599 G_CONST_RETURN gchar*
3600 g_get_home_dir (void)
3602 g_get_any_init_locked ();
3603 return g_home_dir_cp;
3606 #undef g_get_tmp_dir
3608 G_CONST_RETURN gchar*
3609 g_get_tmp_dir (void)
3611 g_get_any_init_locked ();
3612 return g_tmp_dir_cp;