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
61 #include "gprintfint.h"
62 #include "gthreadprivate.h"
67 #define G_PATH_LENGTH MAXPATHLEN
68 #elif defined (PATH_MAX)
69 #define G_PATH_LENGTH PATH_MAX
70 #elif defined (_PC_PATH_MAX)
71 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
73 #define G_PATH_LENGTH 2048
76 #ifdef G_PLATFORM_WIN32
77 # define STRICT /* Strict typing, please */
80 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
81 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
82 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
84 # include <lmcons.h> /* For UNLEN */
85 #endif /* G_PLATFORM_WIN32 */
90 /* older SDK (e.g. msvc 5.0) does not have these*/
91 # ifndef CSIDL_MYMUSIC
92 # define CSIDL_MYMUSIC 13
94 # ifndef CSIDL_MYVIDEO
95 # define CSIDL_MYVIDEO 14
97 # ifndef CSIDL_INTERNET_CACHE
98 # define CSIDL_INTERNET_CACHE 32
100 # ifndef CSIDL_COMMON_APPDATA
101 # define CSIDL_COMMON_APPDATA 35
103 # ifndef CSIDL_MYPICTURES
104 # define CSIDL_MYPICTURES 0x27
106 # ifndef CSIDL_COMMON_DOCUMENTS
107 # define CSIDL_COMMON_DOCUMENTS 46
109 # ifndef CSIDL_PROFILE
110 # define CSIDL_PROFILE 40
112 # include <process.h>
116 #include <CoreServices/CoreServices.h>
120 #include <langinfo.h>
123 const guint glib_major_version = GLIB_MAJOR_VERSION;
124 const guint glib_minor_version = GLIB_MINOR_VERSION;
125 const guint glib_micro_version = GLIB_MICRO_VERSION;
126 const guint glib_interface_age = GLIB_INTERFACE_AGE;
127 const guint glib_binary_age = GLIB_BINARY_AGE;
129 #ifdef G_PLATFORM_WIN32
131 static HMODULE glib_dll = NULL;
136 DllMain (HINSTANCE hinstDLL,
140 if (fdwReason == DLL_PROCESS_ATTACH)
149 _glib_get_dll_directory (void)
153 wchar_t wc_fn[MAX_PATH];
156 if (glib_dll == NULL)
160 /* This code is different from that in
161 * g_win32_get_package_installation_directory_of_module() in that
162 * here we return the actual folder where the GLib DLL is. We don't
163 * do the check for it being in a "bin" or "lib" subfolder and then
164 * returning the parent of that.
166 * In a statically built GLib, glib_dll will be NULL and we will
167 * thus look up the application's .exe file's location.
169 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
172 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
174 p = strrchr (retval, G_DIR_SEPARATOR);
188 * glib_check_version:
189 * @required_major: the required major version.
190 * @required_minor: the required minor version.
191 * @required_micro: the required micro version.
193 * Checks that the GLib library in use is compatible with the
194 * given version. Generally you would pass in the constants
195 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
196 * as the three arguments to this function; that produces
197 * a check that the library in use is compatible with
198 * the version of GLib the application or module was compiled
201 * Compatibility is defined by two things: first the version
202 * of the running library is newer than the version
203 * @required_major.required_minor.@required_micro. Second
204 * the running library must be binary compatible with the
205 * version @required_major.required_minor.@required_micro
206 * (same major version.)
208 * Return value: %NULL if the GLib library is compatible with the
209 * given version, or a string describing the version mismatch.
210 * The returned string is owned by GLib and must not be modified
216 glib_check_version (guint required_major,
217 guint required_minor,
218 guint required_micro)
220 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
221 gint required_effective_micro = 100 * required_minor + required_micro;
223 if (required_major > GLIB_MAJOR_VERSION)
224 return "GLib version too old (major mismatch)";
225 if (required_major < GLIB_MAJOR_VERSION)
226 return "GLib version too new (major mismatch)";
227 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
228 return "GLib version too new (micro mismatch)";
229 if (required_effective_micro > glib_effective_micro)
230 return "GLib version too old (micro mismatch)";
234 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
237 * @dest: the destination address to copy the bytes to.
238 * @src: the source address to copy the bytes from.
239 * @len: the number of bytes to copy.
241 * Copies a block of memory @len bytes long, from @src to @dest.
242 * The source and destination areas may overlap.
244 * In order to use this function, you must include
245 * <filename>string.h</filename> yourself, because this macro will
246 * typically simply resolve to memmove() and GLib does not include
247 * <filename>string.h</filename> for you.
250 g_memmove (gpointer dest,
254 gchar* destptr = dest;
255 const gchar* srcptr = src;
256 if (src + len < dest || dest + len < src)
258 bcopy (src, dest, len);
261 else if (dest <= src)
264 *(destptr++) = *(srcptr++);
271 *(--destptr) = *(--srcptr);
274 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
282 * @func: the function to call on normal program termination.
284 * Specifies a function to be called at normal program termination.
286 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
287 * macro that maps to a call to the atexit() function in the C
288 * library. This means that in case the code that calls g_atexit(),
289 * i.e. atexit(), is in a DLL, the function will be called when the
290 * DLL is detached from the program. This typically makes more sense
291 * than that the function is called when the GLib DLL is detached,
292 * which happened earlier when g_atexit() was a function in the GLib
295 * The behaviour of atexit() in the context of dynamically loaded
296 * modules is not formally specified and varies wildly.
298 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
299 * loaded module which is unloaded before the program terminates might
300 * well cause a crash at program exit.
302 * Some POSIX systems implement atexit() like Windows, and have each
303 * dynamically loaded module maintain an own atexit chain that is
304 * called when the module is unloaded.
306 * On other POSIX systems, before a dynamically loaded module is
307 * unloaded, the registered atexit functions (if any) residing in that
308 * module are called, regardless where the code that registered them
309 * resided. This is presumably the most robust approach.
311 * As can be seen from the above, for portability it's best to avoid
312 * calling g_atexit() (or atexit()) except in the main executable of a
316 g_atexit (GVoidFunc func)
319 const gchar *error = NULL;
321 /* keep this in sync with glib.h */
323 #ifdef G_NATIVE_ATEXIT
324 result = ATEXIT (func);
326 error = g_strerror (errno);
327 #elif defined (HAVE_ATEXIT)
328 # ifdef NeXT /* @#%@! NeXTStep */
329 result = !atexit ((void (*)(void)) func);
331 error = g_strerror (errno);
333 result = atexit ((void (*)(void)) func);
335 error = g_strerror (errno);
337 #elif defined (HAVE_ON_EXIT)
338 result = on_exit ((void (*)(int, void *)) func, NULL);
340 error = g_strerror (errno);
343 error = "no implementation";
344 #endif /* G_NATIVE_ATEXIT */
347 g_error ("Could not register atexit() function: %s", error);
350 /* Based on execvp() from GNU Libc.
351 * Some of this code is cut-and-pasted into gspawn.c
355 my_strchrnul (const gchar *str,
358 gchar *p = (gchar*)str;
359 while (*p && (*p != c))
367 static gchar *inner_find_program_in_path (const gchar *program);
370 g_find_program_in_path (const gchar *program)
372 const gchar *last_dot = strrchr (program, '.');
374 if (last_dot == NULL ||
375 strchr (last_dot, '\\') != NULL ||
376 strchr (last_dot, '/') != NULL)
378 const gint program_length = strlen (program);
379 gchar *pathext = g_build_path (";",
380 ".exe;.cmd;.bat;.com",
381 g_getenv ("PATHEXT"),
384 gchar *decorated_program;
390 gchar *q = my_strchrnul (p, ';');
392 decorated_program = g_malloc (program_length + (q-p) + 1);
393 memcpy (decorated_program, program, program_length);
394 memcpy (decorated_program+program_length, p, q-p);
395 decorated_program [program_length + (q-p)] = '\0';
397 retval = inner_find_program_in_path (decorated_program);
398 g_free (decorated_program);
406 } while (*p++ != '\0');
411 return inner_find_program_in_path (program);
417 * g_find_program_in_path:
418 * @program: a program name in the GLib file name encoding
420 * Locates the first executable named @program in the user's path, in the
421 * same way that execvp() would locate it. Returns an allocated string
422 * with the absolute path name, or %NULL if the program is not found in
423 * the path. If @program is already an absolute path, returns a copy of
424 * @program if @program exists and is executable, and %NULL otherwise.
426 * On Windows, if @program does not have a file type suffix, tries
427 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
428 * the <envar>PATHEXT</envar> environment variable.
430 * On Windows, it looks for the file in the same way as CreateProcess()
431 * would. This means first in the directory where the executing
432 * program was loaded from, then in the current directory, then in the
433 * Windows 32-bit system directory, then in the Windows directory, and
434 * finally in the directories in the <envar>PATH</envar> environment
435 * variable. If the program is found, the return value contains the
436 * full name including the type suffix.
438 * Return value: absolute path, or %NULL
442 inner_find_program_in_path (const gchar *program)
445 g_find_program_in_path (const gchar *program)
448 const gchar *path, *p;
449 gchar *name, *freeme;
451 const gchar *path_copy;
452 gchar *filename = NULL, *appdir = NULL;
453 gchar *sysdir = NULL, *windir = NULL;
455 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
461 g_return_val_if_fail (program != NULL, NULL);
463 /* If it is an absolute path, or a relative path including subdirectories,
464 * don't look in PATH.
466 if (g_path_is_absolute (program)
467 || strchr (program, G_DIR_SEPARATOR) != NULL
469 || strchr (program, '/') != NULL
473 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
474 !g_file_test (program, G_FILE_TEST_IS_DIR))
475 return g_strdup (program);
480 path = g_getenv ("PATH");
481 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
484 /* There is no `PATH' in the environment. The default
485 * search path in GNU libc is the current directory followed by
486 * the path `confstr' returns for `_CS_PATH'.
489 /* In GLib we put . last, for security, and don't use the
490 * unportable confstr(); UNIX98 does not actually specify
491 * what to search if PATH is unset. POSIX may, dunno.
494 path = "/bin:/usr/bin:.";
497 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
498 if (n > 0 && n < MAXPATHLEN)
499 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
501 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
502 if (n > 0 && n < MAXPATHLEN)
503 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
505 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
506 if (n > 0 && n < MAXPATHLEN)
507 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
511 appdir = g_path_get_dirname (filename);
515 path = g_strdup (path);
519 const gchar *tem = path;
520 path = g_strconcat (windir, ";", path, NULL);
521 g_free ((gchar *) tem);
527 const gchar *tem = path;
528 path = g_strconcat (sysdir, ";", path, NULL);
529 g_free ((gchar *) tem);
534 const gchar *tem = path;
535 path = g_strconcat (".;", path, NULL);
536 g_free ((gchar *) tem);
541 const gchar *tem = path;
542 path = g_strconcat (appdir, ";", path, NULL);
543 g_free ((gchar *) tem);
550 len = strlen (program) + 1;
551 pathlen = strlen (path);
552 freeme = name = g_malloc (pathlen + len + 1);
554 /* Copy the file name at the top, including '\0' */
555 memcpy (name + pathlen + 1, program, len);
556 name = name + pathlen;
557 /* And add the slash before the filename */
558 *name = G_DIR_SEPARATOR;
566 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
569 /* Two adjacent colons, or a colon at the beginning or the end
570 * of `PATH' means to search the current directory.
574 startp = memcpy (name - (p - path), path, p - path);
576 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
577 !g_file_test (startp, G_FILE_TEST_IS_DIR))
580 ret = g_strdup (startp);
583 g_free ((gchar *) path_copy);
588 while (*p++ != '\0');
592 g_free ((gchar *) path_copy);
599 debug_key_matches (const gchar *key,
603 for (; length; length--, key++, token++)
605 char k = (*key == '_') ? '-' : tolower (*key );
606 char t = (*token == '_') ? '-' : tolower (*token);
616 * g_parse_debug_string:
617 * @string: a list of debug options separated by colons, spaces, or
619 * @keys: pointer to an array of #GDebugKey which associate
620 * strings with bit flags.
621 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
623 * Parses a string containing debugging options
624 * into a %guint containing bit flags. This is used
625 * within GDK and GTK+ to parse the debug options passed on the
626 * command line or through environment variables.
628 * If @string is equal to "all", all flags are set. If @string
629 * is equal to "help", all the available keys in @keys are printed
630 * out to standard error.
632 * Returns: the combined set of bit flags.
635 g_parse_debug_string (const gchar *string,
636 const GDebugKey *keys,
645 /* this function is used by gmem.c/gslice.c initialization code,
646 * so introducing malloc dependencies here would require adaptions
647 * of those code portions.
650 if (!g_ascii_strcasecmp (string, "all"))
652 for (i=0; i<nkeys; i++)
653 result |= keys[i].value;
655 else if (!g_ascii_strcasecmp (string, "help"))
657 /* using stdio directly for the reason stated above */
658 fprintf (stderr, "Supported debug values: ");
659 for (i=0; i<nkeys; i++)
660 fprintf (stderr, " %s", keys[i].key);
661 fprintf (stderr, "\n");
665 const gchar *p = string;
670 q = strpbrk (p, ":;, \t");
674 for (i = 0; i < nkeys; i++)
675 if (debug_key_matches (keys[i].key, p, q - p))
676 result |= keys[i].value;
689 * @file_name: the name of the file.
691 * Gets the name of the file without any leading directory components.
692 * It returns a pointer into the given file name string.
694 * Return value: the name of the file without any leading directory components.
696 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
697 * g_path_get_basename() allocates new memory for the returned string, unlike
698 * this function which returns a pointer into the argument.
700 G_CONST_RETURN gchar*
701 g_basename (const gchar *file_name)
703 register gchar *base;
705 g_return_val_if_fail (file_name != NULL, NULL);
707 base = strrchr (file_name, G_DIR_SEPARATOR);
711 gchar *q = strrchr (file_name, '/');
712 if (base == NULL || (q != NULL && q > base))
721 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
722 return (gchar*) file_name + 2;
723 #endif /* G_OS_WIN32 */
725 return (gchar*) file_name;
729 * g_path_get_basename:
730 * @file_name: the name of the file.
732 * Gets the last component of the filename. If @file_name ends with a
733 * directory separator it gets the component before the last slash. If
734 * @file_name consists only of directory separators (and on Windows,
735 * possibly a drive letter), a single separator is returned. If
736 * @file_name is empty, it gets ".".
738 * Return value: a newly allocated string containing the last component of
742 g_path_get_basename (const gchar *file_name)
744 register gssize base;
745 register gssize last_nonslash;
749 g_return_val_if_fail (file_name != NULL, NULL);
751 if (file_name[0] == '\0')
753 return g_strdup (".");
755 last_nonslash = strlen (file_name) - 1;
757 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
760 if (last_nonslash == -1)
761 /* string only containing slashes */
762 return g_strdup (G_DIR_SEPARATOR_S);
765 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
766 /* string only containing slashes and a drive */
767 return g_strdup (G_DIR_SEPARATOR_S);
768 #endif /* G_OS_WIN32 */
770 base = last_nonslash;
772 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
776 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
778 #endif /* G_OS_WIN32 */
780 len = last_nonslash - base;
781 retval = g_malloc (len + 1);
782 memcpy (retval, file_name + base + 1, len);
788 * g_path_is_absolute:
789 * @file_name: a file name.
791 * Returns %TRUE if the given @file_name is an absolute file name,
792 * i.e. it contains a full path from the root directory such as "/usr/local"
793 * on UNIX or "C:\windows" on Windows systems.
795 * Returns: %TRUE if @file_name is an absolute path.
798 g_path_is_absolute (const gchar *file_name)
800 g_return_val_if_fail (file_name != NULL, FALSE);
802 if (G_IS_DIR_SEPARATOR (file_name[0]))
806 /* Recognize drive letter on native Windows */
807 if (g_ascii_isalpha (file_name[0]) &&
808 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
810 #endif /* G_OS_WIN32 */
817 * @file_name: a file name.
819 * Returns a pointer into @file_name after the root component, i.e. after
820 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
821 * path it returns %NULL.
823 * Returns: a pointer into @file_name after the root component.
825 G_CONST_RETURN gchar*
826 g_path_skip_root (const gchar *file_name)
828 g_return_val_if_fail (file_name != NULL, NULL);
830 #ifdef G_PLATFORM_WIN32
831 /* Skip \\server\share or //server/share */
832 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
833 G_IS_DIR_SEPARATOR (file_name[1]) &&
835 !G_IS_DIR_SEPARATOR (file_name[2]))
839 p = strchr (file_name + 2, G_DIR_SEPARATOR);
842 gchar *q = strchr (file_name + 2, '/');
843 if (p == NULL || (q != NULL && q < p))
853 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
856 /* Possibly skip a backslash after the share name */
857 if (G_IS_DIR_SEPARATOR (file_name[0]))
860 return (gchar *)file_name;
865 /* Skip initial slashes */
866 if (G_IS_DIR_SEPARATOR (file_name[0]))
868 while (G_IS_DIR_SEPARATOR (file_name[0]))
870 return (gchar *)file_name;
875 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
876 return (gchar *)file_name + 3;
883 * g_path_get_dirname:
884 * @file_name: the name of the file.
886 * Gets the directory components of a file name. If the file name has no
887 * directory components "." is returned. The returned string should be
888 * freed when no longer needed.
890 * Returns: the directory components of the file.
893 g_path_get_dirname (const gchar *file_name)
895 register gchar *base;
898 g_return_val_if_fail (file_name != NULL, NULL);
900 base = strrchr (file_name, G_DIR_SEPARATOR);
903 gchar *q = strrchr (file_name, '/');
904 if (base == NULL || (q != NULL && q > base))
911 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
913 gchar drive_colon_dot[4];
915 drive_colon_dot[0] = file_name[0];
916 drive_colon_dot[1] = ':';
917 drive_colon_dot[2] = '.';
918 drive_colon_dot[3] = '\0';
920 return g_strdup (drive_colon_dot);
923 return g_strdup (".");
926 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
930 /* base points to the char before the last slash.
932 * In case file_name is the root of a drive (X:\) or a child of the
933 * root of a drive (X:\foo), include the slash.
935 * In case file_name is the root share of an UNC path
936 * (\\server\share), add a slash, returning \\server\share\ .
938 * In case file_name is a direct child of a share in an UNC path
939 * (\\server\share\foo), include the slash after the share name,
940 * returning \\server\share\ .
942 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
944 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
945 G_IS_DIR_SEPARATOR (file_name[1]) &&
947 !G_IS_DIR_SEPARATOR (file_name[2]) &&
948 base >= file_name + 2)
950 const gchar *p = file_name + 2;
951 while (*p && !G_IS_DIR_SEPARATOR (*p))
955 len = (guint) strlen (file_name) + 1;
956 base = g_new (gchar, len + 1);
957 strcpy (base, file_name);
958 base[len-1] = G_DIR_SEPARATOR;
962 if (G_IS_DIR_SEPARATOR (*p))
965 while (*p && !G_IS_DIR_SEPARATOR (*p))
973 len = (guint) 1 + base - file_name;
975 base = g_new (gchar, len + 1);
976 g_memmove (base, file_name, len);
985 * Gets the current directory.
986 * The returned string should be freed when no longer needed. The encoding
987 * of the returned string is system defined. On Windows, it is always UTF-8.
989 * Returns: the current directory.
992 g_get_current_dir (void)
997 wchar_t dummy[2], *wdir;
1000 len = GetCurrentDirectoryW (2, dummy);
1001 wdir = g_new (wchar_t, len);
1003 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1004 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1009 dir = g_strdup ("\\");
1015 gchar *buffer = NULL;
1017 static gulong max_len = 0;
1020 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1022 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1023 * and, if that wasn't bad enough, hangs in doing so.
1025 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1026 buffer = g_new (gchar, max_len + 1);
1028 dir = getwd (buffer);
1029 #else /* !sun || !HAVE_GETCWD */
1030 while (max_len < G_MAXULONG / 2)
1033 buffer = g_new (gchar, max_len + 1);
1035 dir = getcwd (buffer, max_len);
1037 if (dir || errno != ERANGE)
1042 #endif /* !sun || !HAVE_GETCWD */
1044 if (!dir || !*buffer)
1046 /* hm, should we g_error() out here?
1047 * this can happen if e.g. "./" has mode \0000
1049 buffer[0] = G_DIR_SEPARATOR;
1053 dir = g_strdup (buffer);
1062 * @variable: the environment variable to get, in the GLib file name encoding.
1064 * Returns the value of an environment variable. The name and value
1065 * are in the GLib file name encoding. On UNIX, this means the actual
1066 * bytes which might or might not be in some consistent character set
1067 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1068 * environment variable's value contains references to other
1069 * environment variables, they are expanded.
1071 * Return value: the value of the environment variable, or %NULL if
1072 * the environment variable is not found. The returned string may be
1073 * overwritten by the next call to g_getenv(), g_setenv() or
1076 G_CONST_RETURN gchar*
1077 g_getenv (const gchar *variable)
1081 g_return_val_if_fail (variable != NULL, NULL);
1083 return getenv (variable);
1085 #else /* G_OS_WIN32 */
1089 wchar_t dummy[2], *wname, *wvalue;
1092 g_return_val_if_fail (variable != NULL, NULL);
1093 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1095 /* On Windows NT, it is relatively typical that environment
1096 * variables contain references to other environment variables. If
1097 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1098 * environment variables would be stored in the Registry as
1099 * REG_EXPAND_SZ type values, and would then get automatically
1100 * expanded before a program sees them. But there is broken software
1101 * that stores environment variables as REG_SZ values even if they
1102 * contain references to other environment variables.)
1105 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1107 len = GetEnvironmentVariableW (wname, dummy, 2);
1117 wvalue = g_new (wchar_t, len);
1119 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1126 if (wcschr (wvalue, L'%') != NULL)
1128 wchar_t *tem = wvalue;
1130 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1134 wvalue = g_new (wchar_t, len);
1136 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1146 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1151 quark = g_quark_from_string (value);
1154 return g_quark_to_string (quark);
1156 #endif /* G_OS_WIN32 */
1159 /* _g_getenv_nomalloc
1160 * this function does a getenv() without doing any kind of allocation
1161 * through glib. it's suitable for chars <= 127 only (both, for the
1162 * variable name and the contents) and for contents < 1024 chars in
1163 * length. also, it aliases "" to a NULL return value.
1166 _g_getenv_nomalloc (const gchar *variable,
1169 const gchar *retval = getenv (variable);
1170 if (retval && retval[0])
1172 gint l = strlen (retval);
1175 strncpy (buffer, retval, l);
1185 * @variable: the environment variable to set, must not contain '='.
1186 * @value: the value for to set the variable to.
1187 * @overwrite: whether to change the variable if it already exists.
1189 * Sets an environment variable. Both the variable's name and value
1190 * should be in the GLib file name encoding. On UNIX, this means that
1191 * they can be any sequence of bytes. On Windows, they should be in
1194 * Note that on some systems, when variables are overwritten, the memory
1195 * used for the previous variables and its value isn't reclaimed.
1197 * Returns: %FALSE if the environment variable couldn't be set.
1202 g_setenv (const gchar *variable,
1213 g_return_val_if_fail (variable != NULL, FALSE);
1214 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1217 result = setenv (variable, value, overwrite);
1219 if (!overwrite && getenv (variable) != NULL)
1222 /* This results in a leak when you overwrite existing
1223 * settings. It would be fairly easy to fix this by keeping
1224 * our own parallel array or hash table.
1226 string = g_strconcat (variable, "=", value, NULL);
1227 result = putenv (string);
1231 #else /* G_OS_WIN32 */
1234 wchar_t *wname, *wvalue, *wassignment;
1237 g_return_val_if_fail (variable != NULL, FALSE);
1238 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1239 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1240 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1242 if (!overwrite && g_getenv (variable) != NULL)
1245 /* We want to (if possible) set both the environment variable copy
1246 * kept by the C runtime and the one kept by the system.
1248 * We can't use only the C runtime's putenv or _wputenv() as that
1249 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1250 * (with main() and not wmain()). In a "main()" app the C runtime
1251 * initializes the C runtime's environment table by converting the
1252 * real (wide char) environment variables to system codepage, thus
1253 * breaking those that aren't representable in the system codepage.
1255 * As the C runtime's putenv() will also set the system copy, we do
1256 * the putenv() first, then call SetEnvironmentValueW ourselves.
1259 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1260 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1261 tem = g_strconcat (variable, "=", value, NULL);
1262 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1265 _wputenv (wassignment);
1266 g_free (wassignment);
1268 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1275 #endif /* G_OS_WIN32 */
1278 #ifdef HAVE__NSGETENVIRON
1279 #define environ (*_NSGetEnviron())
1280 #elif !defined(G_OS_WIN32)
1282 /* According to the Single Unix Specification, environ is not in
1283 * any system header, although unistd.h often declares it.
1285 extern char **environ;
1290 * @variable: the environment variable to remove, must not contain '='.
1292 * Removes an environment variable from the environment.
1294 * Note that on some systems, when variables are overwritten, the memory
1295 * used for the previous variables and its value isn't reclaimed.
1296 * Furthermore, this function can't be guaranteed to operate in a
1302 g_unsetenv (const gchar *variable)
1306 #ifdef HAVE_UNSETENV
1307 g_return_if_fail (variable != NULL);
1308 g_return_if_fail (strchr (variable, '=') == NULL);
1310 unsetenv (variable);
1311 #else /* !HAVE_UNSETENV */
1315 g_return_if_fail (variable != NULL);
1316 g_return_if_fail (strchr (variable, '=') == NULL);
1318 len = strlen (variable);
1320 /* Mess directly with the environ array.
1321 * This seems to be the only portable way to do this.
1323 * Note that we remove *all* environment entries for
1324 * the variable name, not just the first.
1329 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1337 #endif /* !HAVE_UNSETENV */
1339 #else /* G_OS_WIN32 */
1341 wchar_t *wname, *wassignment;
1344 g_return_if_fail (variable != NULL);
1345 g_return_if_fail (strchr (variable, '=') == NULL);
1346 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1348 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1349 tem = g_strconcat (variable, "=", NULL);
1350 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1353 _wputenv (wassignment);
1354 g_free (wassignment);
1356 SetEnvironmentVariableW (wname, NULL);
1360 #endif /* G_OS_WIN32 */
1366 * Gets the names of all variables set in the environment.
1368 * Returns: a %NULL-terminated list of strings which must be freed
1369 * with g_strfreev().
1371 * Programs that want to be portable to Windows should typically use
1372 * this function and g_getenv() instead of using the environ array
1373 * from the C library directly. On Windows, the strings in the environ
1374 * array are in system codepage encoding, while in most of the typical
1375 * use cases for environment variables in GLib-using programs you want
1376 * the UTF-8 encoding that this function and g_getenv() provide.
1384 gchar **result, *eq;
1387 len = g_strv_length (environ);
1388 result = g_new0 (gchar *, len + 1);
1391 for (i = 0; i < len; i++)
1393 eq = strchr (environ[i], '=');
1395 result[j++] = g_strndup (environ[i], eq - environ[i]);
1402 gchar **result, *eq;
1406 p = (wchar_t *) GetEnvironmentStringsW ();
1412 q += wcslen (q) + 1;
1416 result = g_new0 (gchar *, len + 1);
1422 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1423 if (result[j] != NULL)
1425 eq = strchr (result[j], '=');
1426 if (eq && eq > result[j])
1434 q += wcslen (q) + 1;
1437 FreeEnvironmentStringsW (p);
1443 G_LOCK_DEFINE_STATIC (g_utils_global);
1445 static gchar *g_tmp_dir = NULL;
1446 static gchar *g_user_name = NULL;
1447 static gchar *g_real_name = NULL;
1448 static gchar *g_home_dir = NULL;
1449 static gchar *g_host_name = NULL;
1452 /* System codepage versions of the above, kept at file level so that they,
1453 * too, are produced only once.
1455 static gchar *g_tmp_dir_cp = NULL;
1456 static gchar *g_user_name_cp = NULL;
1457 static gchar *g_real_name_cp = NULL;
1458 static gchar *g_home_dir_cp = NULL;
1461 static gchar *g_user_data_dir = NULL;
1462 static gchar **g_system_data_dirs = NULL;
1463 static gchar *g_user_cache_dir = NULL;
1464 static gchar *g_user_config_dir = NULL;
1465 static gchar **g_system_config_dirs = NULL;
1467 static gchar **g_user_special_dirs = NULL;
1469 /* fifteen minutes of fame for everybody */
1470 #define G_USER_DIRS_EXPIRE 15 * 60
1475 get_special_folder (int csidl)
1477 wchar_t path[MAX_PATH+1];
1479 LPITEMIDLIST pidl = NULL;
1481 gchar *retval = NULL;
1483 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1486 b = SHGetPathFromIDListW (pidl, path);
1488 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1489 CoTaskMemFree (pidl);
1495 get_windows_directory_root (void)
1497 wchar_t wwindowsdir[MAX_PATH];
1499 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1501 /* Usually X:\Windows, but in terminal server environments
1502 * might be an UNC path, AFAIK.
1504 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1507 if (windowsdir == NULL)
1508 return g_strdup ("C:\\");
1510 p = (char *) g_path_skip_root (windowsdir);
1511 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1517 return g_strdup ("C:\\");
1522 /* HOLDS: g_utils_global_lock */
1524 g_get_any_init_do (void)
1526 gchar hostname[100];
1528 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1530 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1532 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1536 g_tmp_dir = get_windows_directory_root ();
1542 g_tmp_dir = g_strdup (P_tmpdir);
1543 k = strlen (g_tmp_dir);
1544 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1545 g_tmp_dir[k - 1] = '\0';
1551 g_tmp_dir = g_strdup ("/tmp");
1553 #endif /* !G_OS_WIN32 */
1556 /* We check $HOME first for Win32, though it is a last resort for Unix
1557 * where we prefer the results of getpwuid().
1559 g_home_dir = g_strdup (g_getenv ("HOME"));
1561 /* Only believe HOME if it is an absolute path and exists */
1564 if (!(g_path_is_absolute (g_home_dir) &&
1565 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1567 g_free (g_home_dir);
1572 /* In case HOME is Unix-style (it happens), convert it to
1578 while ((p = strchr (g_home_dir, '/')) != NULL)
1584 /* USERPROFILE is probably the closest equivalent to $HOME? */
1585 if (g_getenv ("USERPROFILE") != NULL)
1586 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1590 g_home_dir = get_special_folder (CSIDL_PROFILE);
1593 g_home_dir = get_windows_directory_root ();
1594 #endif /* G_OS_WIN32 */
1598 struct passwd *pw = NULL;
1599 gpointer buffer = NULL;
1603 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1605 # ifdef _SC_GETPW_R_SIZE_MAX
1606 /* This reurns the maximum length */
1607 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1611 # else /* _SC_GETPW_R_SIZE_MAX */
1613 # endif /* _SC_GETPW_R_SIZE_MAX */
1615 logname = (gchar *) g_getenv ("LOGNAME");
1620 /* we allocate 6 extra bytes to work around a bug in
1621 * Mac OS < 10.3. See #156446
1623 buffer = g_malloc (bufsize + 6);
1626 # ifdef HAVE_POSIX_GETPWUID_R
1628 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1629 if (!pw || (pw->pw_uid != getuid ())) {
1630 /* LOGNAME is lying, fall back to looking up the uid */
1631 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1634 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1636 error = error < 0 ? errno : error;
1637 # else /* HAVE_NONPOSIX_GETPWUID_R */
1638 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1639 # if defined(_AIX) || defined(__hpux)
1640 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1641 pw = error == 0 ? &pwd : NULL;
1644 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1645 if (!pw || (pw->pw_uid != getuid ())) {
1646 /* LOGNAME is lying, fall back to looking up the uid */
1647 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1650 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1652 error = pw ? 0 : errno;
1654 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1658 /* we bail out prematurely if the user id can't be found
1659 * (should be pretty rare case actually), or if the buffer
1660 * should be sufficiently big and lookups are still not
1663 if (error == 0 || error == ENOENT)
1665 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1666 (gulong) getuid ());
1669 if (bufsize > 32 * 1024)
1671 g_warning ("getpwuid_r(): failed due to: %s.",
1672 g_strerror (error));
1680 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1685 pw = getpwuid (getuid ());
1690 g_user_name = g_strdup (pw->pw_name);
1692 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1694 gchar **gecos_fields;
1697 /* split the gecos field and substitute '&' */
1698 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1699 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1700 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1701 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1702 g_strfreev (gecos_fields);
1703 g_strfreev (name_parts);
1707 g_home_dir = g_strdup (pw->pw_dir);
1712 #else /* !HAVE_PWD_H */
1716 guint len = UNLEN+1;
1717 wchar_t buffer[UNLEN+1];
1719 if (GetUserNameW (buffer, (LPDWORD) &len))
1721 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1722 g_real_name = g_strdup (g_user_name);
1725 #endif /* G_OS_WIN32 */
1727 #endif /* !HAVE_PWD_H */
1731 g_home_dir = g_strdup (g_getenv ("HOME"));
1735 /* change '\\' in %HOME% to '/' */
1736 g_strdelimit (g_home_dir, "\\",'/');
1739 g_user_name = g_strdup ("somebody");
1741 g_real_name = g_strdup ("Unknown");
1745 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1747 DWORD size = sizeof (hostname);
1748 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1750 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1754 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1755 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1756 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1759 g_tmp_dir_cp = g_strdup ("\\");
1760 if (!g_user_name_cp)
1761 g_user_name_cp = g_strdup ("somebody");
1762 if (!g_real_name_cp)
1763 g_real_name_cp = g_strdup ("Unknown");
1765 /* home_dir might be NULL, unlike tmp_dir, user_name and
1769 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1771 g_home_dir_cp = NULL;
1772 #endif /* G_OS_WIN32 */
1776 g_get_any_init (void)
1779 g_get_any_init_do ();
1783 g_get_any_init_locked (void)
1785 G_LOCK (g_utils_global);
1787 G_UNLOCK (g_utils_global);
1794 * Gets the user name of the current user. The encoding of the returned
1795 * string is system-defined. On UNIX, it might be the preferred file name
1796 * encoding, or something else, and there is no guarantee that it is even
1797 * consistent on a machine. On Windows, it is always UTF-8.
1799 * Returns: the user name of the current user.
1801 G_CONST_RETURN gchar*
1802 g_get_user_name (void)
1804 g_get_any_init_locked ();
1811 * Gets the real name of the user. This usually comes from the user's entry
1812 * in the <filename>passwd</filename> file. The encoding of the returned
1813 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1814 * If the real user name cannot be determined, the string "Unknown" is
1817 * Returns: the user's real name.
1819 G_CONST_RETURN gchar*
1820 g_get_real_name (void)
1822 g_get_any_init_locked ();
1829 * Gets the current user's home directory as defined in the
1830 * password database.
1832 * Note that in contrast to traditional UNIX tools, this function
1833 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1834 * environment variable.
1836 * One of the reasons for this decision is that applications in many
1837 * cases need special handling to deal with the case where
1838 * <envar>HOME</envar> is
1840 * <member>Not owned by the user</member>
1841 * <member>Not writeable</member>
1842 * <member>Not even readable</member>
1844 * Since applications are in general <emphasis>not</emphasis> written
1845 * to deal with these situations it was considered better to make
1846 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1847 * return the real home directory for the user. If applications
1848 * want to pay attention to <envar>HOME</envar>, they can do:
1850 * const char *homedir = g_getenv ("HOME");
1852 * homedir = g_get_home_dir (<!-- -->);
1855 * Returns: the current user's home directory
1857 G_CONST_RETURN gchar*
1858 g_get_home_dir (void)
1860 g_get_any_init_locked ();
1867 * Gets the directory to use for temporary files. This is found from
1868 * inspecting the environment variables <envar>TMPDIR</envar>,
1869 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1870 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1871 * The encoding of the returned string is system-defined. On Windows,
1872 * it is always UTF-8. The return value is never %NULL.
1874 * Returns: the directory to use for temporary files.
1876 G_CONST_RETURN gchar*
1877 g_get_tmp_dir (void)
1879 g_get_any_init_locked ();
1886 * Return a name for the machine.
1888 * The returned name is not necessarily a fully-qualified domain name,
1889 * or even present in DNS or some other name service at all. It need
1890 * not even be unique on your local network or site, but usually it
1891 * is. Callers should not rely on the return value having any specific
1892 * properties like uniqueness for security purposes. Even if the name
1893 * of the machine is changed while an application is running, the
1894 * return value from this function does not change. The returned
1895 * string is owned by GLib and should not be modified or freed. If no
1896 * name can be determined, a default fixed string "localhost" is
1899 * Returns: the host name of the machine.
1904 g_get_host_name (void)
1906 g_get_any_init_locked ();
1910 G_LOCK_DEFINE_STATIC (g_prgname);
1911 static gchar *g_prgname = NULL;
1916 * Gets the name of the program. This name should <emphasis>not</emphasis>
1917 * be localized, contrast with g_get_application_name().
1918 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1919 * which is called by gtk_init(). The program name is found by taking
1920 * the last component of <literal>argv[0]</literal>.)
1922 * Returns: the name of the program. The returned string belongs
1923 * to GLib and must not be modified or freed.
1926 g_get_prgname (void)
1932 if (g_prgname == NULL)
1934 static gboolean beenhere = FALSE;
1938 gchar *utf8_buf = NULL;
1939 wchar_t buf[MAX_PATH+1];
1942 if (GetModuleFileNameW (GetModuleHandle (NULL),
1943 buf, G_N_ELEMENTS (buf)) > 0)
1944 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1948 g_prgname = g_path_get_basename (utf8_buf);
1955 G_UNLOCK (g_prgname);
1962 * @prgname: the name of the program.
1964 * Sets the name of the program. This name should <emphasis>not</emphasis>
1965 * be localized, contrast with g_set_application_name(). Note that for
1966 * thread-safety reasons this function can only be called once.
1969 g_set_prgname (const gchar *prgname)
1973 g_prgname = g_strdup (prgname);
1974 G_UNLOCK (g_prgname);
1977 G_LOCK_DEFINE_STATIC (g_application_name);
1978 static gchar *g_application_name = NULL;
1981 * g_get_application_name:
1983 * Gets a human-readable name for the application, as set by
1984 * g_set_application_name(). This name should be localized if
1985 * possible, and is intended for display to the user. Contrast with
1986 * g_get_prgname(), which gets a non-localized name. If
1987 * g_set_application_name() has not been called, returns the result of
1988 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1991 * Return value: human-readable application name. may return %NULL
1995 G_CONST_RETURN gchar*
1996 g_get_application_name (void)
2000 G_LOCK (g_application_name);
2001 retval = g_application_name;
2002 G_UNLOCK (g_application_name);
2005 return g_get_prgname ();
2011 * g_set_application_name:
2012 * @application_name: localized name of the application
2014 * Sets a human-readable name for the application. This name should be
2015 * localized if possible, and is intended for display to the user.
2016 * Contrast with g_set_prgname(), which sets a non-localized name.
2017 * g_set_prgname() will be called automatically by gtk_init(),
2018 * but g_set_application_name() will not.
2020 * Note that for thread safety reasons, this function can only
2023 * The application name will be used in contexts such as error messages,
2024 * or when displaying an application's name in the task list.
2029 g_set_application_name (const gchar *application_name)
2031 gboolean already_set = FALSE;
2033 G_LOCK (g_application_name);
2034 if (g_application_name)
2037 g_application_name = g_strdup (application_name);
2038 G_UNLOCK (g_application_name);
2041 g_warning ("g_set_application_name() called multiple times");
2045 * g_get_user_data_dir:
2047 * Returns a base directory in which to access application data such
2048 * as icons that is customized for a particular user.
2050 * On UNIX platforms this is determined using the mechanisms described in
2051 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2052 * XDG Base Directory Specification</ulink>.
2053 * In this case the directory retrieved will be XDG_DATA_HOME.
2055 * On Windows is the virtual folder that represents the My Documents
2056 * desktop item. See documentation for CSIDL_PERSONAL.
2058 * Return value: a string owned by GLib that must not be modified
2062 G_CONST_RETURN gchar*
2063 g_get_user_data_dir (void)
2067 G_LOCK (g_utils_global);
2069 if (!g_user_data_dir)
2072 data_dir = get_special_folder (CSIDL_PERSONAL);
2074 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2076 if (data_dir && data_dir[0])
2077 data_dir = g_strdup (data_dir);
2079 if (!data_dir || !data_dir[0])
2084 data_dir = g_build_filename (g_home_dir, ".local",
2087 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2091 g_user_data_dir = data_dir;
2094 data_dir = g_user_data_dir;
2096 G_UNLOCK (g_utils_global);
2102 g_init_user_config_dir (void)
2106 if (!g_user_config_dir)
2109 config_dir = get_special_folder (CSIDL_APPDATA);
2111 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2113 if (config_dir && config_dir[0])
2114 config_dir = g_strdup (config_dir);
2116 if (!config_dir || !config_dir[0])
2121 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2123 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2126 g_user_config_dir = config_dir;
2131 * g_get_user_config_dir:
2133 * Returns a base directory in which to store user-specific application
2134 * configuration information such as user preferences and settings.
2136 * On UNIX platforms this is determined using the mechanisms described in
2137 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2138 * XDG Base Directory Specification</ulink>.
2139 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2141 * On Windows is the directory that serves as a common repository for
2142 * application-specific data. A typical path is
2143 * C:\Documents and Settings\username\Application. See documentation for
2146 * Return value: a string owned by GLib that must not be modified
2150 G_CONST_RETURN gchar*
2151 g_get_user_config_dir (void)
2153 G_LOCK (g_utils_global);
2155 g_init_user_config_dir ();
2157 G_UNLOCK (g_utils_global);
2159 return g_user_config_dir;
2163 * g_get_user_cache_dir:
2165 * Returns a base directory in which to store non-essential, cached
2166 * data specific to particular user.
2168 * On UNIX platforms this is determined using the mechanisms described in
2169 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2170 * XDG Base Directory Specification</ulink>.
2171 * In this case the directory retrieved will be XDG_CACHE_HOME.
2173 * On Windows is the directory that serves as a common repository for
2174 * temporary Internet files. A typical path is
2175 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2176 * See documentation for CSIDL_INTERNET_CACHE.
2178 * Return value: a string owned by GLib that must not be modified
2182 G_CONST_RETURN gchar*
2183 g_get_user_cache_dir (void)
2187 G_LOCK (g_utils_global);
2189 if (!g_user_cache_dir)
2192 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2194 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2196 if (cache_dir && cache_dir[0])
2197 cache_dir = g_strdup (cache_dir);
2199 if (!cache_dir || !cache_dir[0])
2204 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2206 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2208 g_user_cache_dir = cache_dir;
2211 cache_dir = g_user_cache_dir;
2213 G_UNLOCK (g_utils_global);
2221 find_folder (OSType type)
2223 gchar *filename = NULL;
2226 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2228 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2232 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2236 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2240 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2242 CFStringGetCString (path, filename,
2243 CFStringGetLength (path) * 3 + 1,
2244 kCFStringEncodingUTF8);
2258 load_user_special_dirs (void)
2260 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2261 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2262 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2263 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2264 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2265 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2266 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2267 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2270 #endif /* HAVE_CARBON */
2272 #if defined(G_OS_WIN32)
2274 load_user_special_dirs (void)
2276 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2280 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2281 static const GUID FOLDERID_Downloads =
2282 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2283 static const GUID FOLDERID_Public =
2284 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2287 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (LoadLibrary ("shell32.dll"),
2288 "SHGetKnownFolderPath");
2290 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2291 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2293 if (p_SHGetKnownFolderPath == NULL)
2295 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2300 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2301 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2302 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2303 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2304 CoTaskMemFree (wcp);
2307 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2308 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2310 if (p_SHGetKnownFolderPath == NULL)
2313 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2318 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2319 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2320 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2321 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2322 CoTaskMemFree (wcp);
2325 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2326 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2328 #endif /* G_OS_WIN32 */
2330 static void g_init_user_config_dir (void);
2332 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2334 /* adapted from xdg-user-dir-lookup.c
2336 * Copyright (C) 2007 Red Hat Inc.
2338 * Permission is hereby granted, free of charge, to any person
2339 * obtaining a copy of this software and associated documentation files
2340 * (the "Software"), to deal in the Software without restriction,
2341 * including without limitation the rights to use, copy, modify, merge,
2342 * publish, distribute, sublicense, and/or sell copies of the Software,
2343 * and to permit persons to whom the Software is furnished to do so,
2344 * subject to the following conditions:
2346 * The above copyright notice and this permission notice shall be
2347 * included in all copies or substantial portions of the Software.
2349 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2350 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2351 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2352 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2353 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2354 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2355 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2359 load_user_special_dirs (void)
2366 g_init_user_config_dir ();
2367 config_file = g_build_filename (g_user_config_dir,
2371 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2373 g_free (config_file);
2377 lines = g_strsplit (data, "\n", -1);
2378 n_lines = g_strv_length (lines);
2381 for (i = 0; i < n_lines; i++)
2383 gchar *buffer = lines[i];
2386 gboolean is_relative = FALSE;
2387 GUserDirectory directory;
2389 /* Remove newline at end */
2390 len = strlen (buffer);
2391 if (len > 0 && buffer[len - 1] == '\n')
2392 buffer[len - 1] = 0;
2395 while (*p == ' ' || *p == '\t')
2398 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2400 directory = G_USER_DIRECTORY_DESKTOP;
2401 p += strlen ("XDG_DESKTOP_DIR");
2403 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2405 directory = G_USER_DIRECTORY_DOCUMENTS;
2406 p += strlen ("XDG_DOCUMENTS_DIR");
2408 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2410 directory = G_USER_DIRECTORY_DOWNLOAD;
2411 p += strlen ("XDG_DOWNLOAD_DIR");
2413 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2415 directory = G_USER_DIRECTORY_MUSIC;
2416 p += strlen ("XDG_MUSIC_DIR");
2418 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2420 directory = G_USER_DIRECTORY_PICTURES;
2421 p += strlen ("XDG_PICTURES_DIR");
2423 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2425 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2426 p += strlen ("XDG_PUBLICSHARE_DIR");
2428 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2430 directory = G_USER_DIRECTORY_TEMPLATES;
2431 p += strlen ("XDG_TEMPLATES_DIR");
2433 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2435 directory = G_USER_DIRECTORY_VIDEOS;
2436 p += strlen ("XDG_VIDEOS_DIR");
2441 while (*p == ' ' || *p == '\t')
2448 while (*p == ' ' || *p == '\t')
2455 if (strncmp (p, "$HOME", 5) == 0)
2463 d = strrchr (p, '"');
2470 /* remove trailing slashes */
2472 if (d[len - 1] == '/')
2478 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2481 g_user_special_dirs[directory] = g_strdup (d);
2485 g_free (config_file);
2488 #endif /* G_OS_UNIX && !HAVE_CARBON */
2492 * g_reload_user_special_dirs_cache:
2494 * Resets the cache used for g_get_user_special_dir(), so
2495 * that the latest on-disk version is used. Call this only
2496 * if you just changed the data on disk yourself.
2498 * Due to threadsafety issues this may cause leaking of strings
2499 * that were previously returned from g_get_user_special_dir()
2500 * that can't be freed. We ensure to only leak the data for
2501 * the directories that actually changed value though.
2506 g_reload_user_special_dirs_cache (void)
2510 G_LOCK (g_utils_global);
2512 if (g_user_special_dirs != NULL)
2514 /* save a copy of the pointer, to check if some memory can be preserved */
2515 char **old_g_user_special_dirs = g_user_special_dirs;
2518 /* recreate and reload our cache */
2519 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2520 load_user_special_dirs ();
2522 /* only leak changed directories */
2523 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2525 old_val = old_g_user_special_dirs[i];
2526 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2529 g_free (g_user_special_dirs[i]);
2530 g_user_special_dirs[i] = old_val;
2536 /* free the old array */
2537 g_free (old_g_user_special_dirs);
2540 G_UNLOCK (g_utils_global);
2544 * g_get_user_special_dir:
2545 * @directory: the logical id of special directory
2547 * Returns the full path of a special directory using its logical id.
2549 * On Unix this is done using the XDG special user directories.
2550 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2551 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2552 * user directories have not been set up.
2554 * Depending on the platform, the user might be able to change the path
2555 * of the special directory without requiring the session to restart; GLib
2556 * will not reflect any change once the special directories are loaded.
2558 * Return value: the path to the specified special directory, or %NULL
2559 * if the logical id was not found. The returned string is owned by
2560 * GLib and should not be modified or freed.
2564 G_CONST_RETURN gchar *
2565 g_get_user_special_dir (GUserDirectory directory)
2567 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2568 directory < G_USER_N_DIRECTORIES, NULL);
2570 G_LOCK (g_utils_global);
2572 if (G_UNLIKELY (g_user_special_dirs == NULL))
2574 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2576 load_user_special_dirs ();
2578 /* Special-case desktop for historical compatibility */
2579 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2583 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2584 g_build_filename (g_home_dir, "Desktop", NULL);
2588 G_UNLOCK (g_utils_global);
2590 return g_user_special_dirs[directory];
2595 #undef g_get_system_data_dirs
2598 get_module_for_address (gconstpointer address)
2600 /* Holds the g_utils_global lock */
2602 static gboolean beenhere = FALSE;
2603 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2604 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2605 HMODULE hmodule = NULL;
2612 p_GetModuleHandleExA =
2613 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2614 "GetModuleHandleExA");
2618 if (p_GetModuleHandleExA == NULL ||
2619 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2620 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2623 MEMORY_BASIC_INFORMATION mbi;
2624 VirtualQuery (address, &mbi, sizeof (mbi));
2625 hmodule = (HMODULE) mbi.AllocationBase;
2632 get_module_share_dir (gconstpointer address)
2638 hmodule = get_module_for_address (address);
2639 if (hmodule == NULL)
2642 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2643 retval = g_build_filename (filename, "share", NULL);
2649 G_CONST_RETURN gchar * G_CONST_RETURN *
2650 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2654 static GHashTable *per_module_data_dirs = NULL;
2659 if (address_of_function)
2661 G_LOCK (g_utils_global);
2662 hmodule = get_module_for_address (address_of_function);
2663 if (hmodule != NULL)
2665 if (per_module_data_dirs == NULL)
2666 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2669 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2673 G_UNLOCK (g_utils_global);
2674 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2680 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2682 /* Documents and Settings\All Users\Application Data */
2683 p = get_special_folder (CSIDL_COMMON_APPDATA);
2685 g_array_append_val (data_dirs, p);
2687 /* Documents and Settings\All Users\Documents */
2688 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2690 g_array_append_val (data_dirs, p);
2692 /* Using the above subfolders of Documents and Settings perhaps
2693 * makes sense from a Windows perspective.
2695 * But looking at the actual use cases of this function in GTK+
2696 * and GNOME software, what we really want is the "share"
2697 * subdirectory of the installation directory for the package
2698 * our caller is a part of.
2700 * The address_of_function parameter, if non-NULL, points to a
2701 * function in the calling module. Use that to determine that
2702 * module's installation folder, and use its "share" subfolder.
2704 * Additionally, also use the "share" subfolder of the installation
2705 * locations of GLib and the .exe file being run.
2707 * To guard against none of the above being what is really wanted,
2708 * callers of this function should have Win32-specific code to look
2709 * up their installation folder themselves, and handle a subfolder
2710 * "share" of it in the same way as the folders returned from this
2714 p = get_module_share_dir (address_of_function);
2716 g_array_append_val (data_dirs, p);
2718 if (glib_dll != NULL)
2720 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2721 p = g_build_filename (glib_root, "share", NULL);
2723 g_array_append_val (data_dirs, p);
2727 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2728 p = g_build_filename (exe_root, "share", NULL);
2730 g_array_append_val (data_dirs, p);
2733 retval = (gchar **) g_array_free (data_dirs, FALSE);
2735 if (address_of_function)
2737 if (hmodule != NULL)
2738 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2739 G_UNLOCK (g_utils_global);
2742 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2748 * g_get_system_data_dirs:
2750 * Returns an ordered list of base directories in which to access
2751 * system-wide application data.
2753 * On UNIX platforms this is determined using the mechanisms described in
2754 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2755 * XDG Base Directory Specification</ulink>
2757 * On Windows the first elements in the list are the Application Data
2758 * and Documents folders for All Users. (These can be determined only
2759 * on Windows 2000 or later and are not present in the list on other
2760 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2761 * CSIDL_COMMON_DOCUMENTS.
2763 * Then follows the "share" subfolder in the installation folder for
2764 * the package containing the DLL that calls this function, if it can
2767 * Finally the list contains the "share" subfolder in the installation
2768 * folder for GLib, and in the installation folder for the package the
2769 * application's .exe file belongs to.
2771 * The installation folders above are determined by looking up the
2772 * folder where the module (DLL or EXE) in question is located. If the
2773 * folder's name is "bin", its parent is used, otherwise the folder
2776 * Note that on Windows the returned list can vary depending on where
2777 * this function is called.
2779 * Return value: a %NULL-terminated array of strings owned by GLib that must
2780 * not be modified or freed.
2783 G_CONST_RETURN gchar * G_CONST_RETURN *
2784 g_get_system_data_dirs (void)
2786 gchar **data_dir_vector;
2788 G_LOCK (g_utils_global);
2790 if (!g_system_data_dirs)
2793 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2795 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2797 if (!data_dirs || !data_dirs[0])
2798 data_dirs = "/usr/local/share/:/usr/share/";
2800 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2803 g_system_data_dirs = data_dir_vector;
2806 data_dir_vector = g_system_data_dirs;
2808 G_UNLOCK (g_utils_global);
2810 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2814 * g_get_system_config_dirs:
2816 * Returns an ordered list of base directories in which to access
2817 * system-wide configuration information.
2819 * On UNIX platforms this is determined using the mechanisms described in
2820 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2821 * XDG Base Directory Specification</ulink>
2823 * Return value: a %NULL-terminated array of strings owned by GLib that must
2824 * not be modified or freed.
2827 G_CONST_RETURN gchar * G_CONST_RETURN *
2828 g_get_system_config_dirs (void)
2830 gchar *conf_dirs, **conf_dir_vector;
2832 G_LOCK (g_utils_global);
2834 if (!g_system_config_dirs)
2837 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2840 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2845 /* Return empty list */
2846 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2849 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2851 if (!conf_dirs || !conf_dirs[0])
2852 conf_dirs = "/etc/xdg";
2854 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2857 g_system_config_dirs = conf_dir_vector;
2860 conf_dir_vector = g_system_config_dirs;
2861 G_UNLOCK (g_utils_global);
2863 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2868 static GHashTable *alias_table = NULL;
2870 /* read an alias file for the locales */
2872 read_aliases (gchar *file)
2878 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2879 fp = fopen (file,"r");
2882 while (fgets (buf, 256, fp))
2888 /* Line is a comment */
2889 if ((buf[0] == '#') || (buf[0] == '\0'))
2892 /* Reads first column */
2893 for (p = buf, q = NULL; *p; p++) {
2894 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2897 while ((*q == '\t') || (*q == ' ')) {
2903 /* The line only had one column */
2904 if (!q || *q == '\0')
2907 /* Read second column */
2908 for (p = q; *p; p++) {
2909 if ((*p == '\t') || (*p == ' ')) {
2915 /* Add to alias table if necessary */
2916 if (!g_hash_table_lookup (alias_table, buf)) {
2917 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2926 unalias_lang (char *lang)
2933 read_aliases ("/usr/share/locale/locale.alias");
2936 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2941 static gboolean said_before = FALSE;
2943 g_warning ("Too many alias levels for a locale, "
2944 "may indicate a loop");
2953 /* Mask for components of locale spec. The ordering here is from
2954 * least significant to most significant
2958 COMPONENT_CODESET = 1 << 0,
2959 COMPONENT_TERRITORY = 1 << 1,
2960 COMPONENT_MODIFIER = 1 << 2
2963 /* Break an X/Open style locale specification into components
2966 explode_locale (const gchar *locale,
2972 const gchar *uscore_pos;
2973 const gchar *at_pos;
2974 const gchar *dot_pos;
2978 uscore_pos = strchr (locale, '_');
2979 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2980 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2984 mask |= COMPONENT_MODIFIER;
2985 *modifier = g_strdup (at_pos);
2988 at_pos = locale + strlen (locale);
2992 mask |= COMPONENT_CODESET;
2993 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3000 mask |= COMPONENT_TERRITORY;
3001 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3004 uscore_pos = dot_pos;
3006 *language = g_strndup (locale, uscore_pos - locale);
3012 * Compute all interesting variants for a given locale name -
3013 * by stripping off different components of the value.
3015 * For simplicity, we assume that the locale is in
3016 * X/Open format: language[_territory][.codeset][@modifier]
3018 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3019 * as well. We could just copy the code from glibc wholesale
3020 * but it is big, ugly, and complicated, so I'm reluctant
3021 * to do so when this should handle 99% of the time...
3024 _g_compute_locale_variants (const gchar *locale)
3026 GSList *retval = NULL;
3028 gchar *language = NULL;
3029 gchar *territory = NULL;
3030 gchar *codeset = NULL;
3031 gchar *modifier = NULL;
3036 g_return_val_if_fail (locale != NULL, NULL);
3038 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3040 /* Iterate through all possible combinations, from least attractive
3041 * to most attractive.
3043 for (i = 0; i <= mask; i++)
3044 if ((i & ~mask) == 0)
3046 gchar *val = g_strconcat (language,
3047 (i & COMPONENT_TERRITORY) ? territory : "",
3048 (i & COMPONENT_CODESET) ? codeset : "",
3049 (i & COMPONENT_MODIFIER) ? modifier : "",
3051 retval = g_slist_prepend (retval, val);
3055 if (mask & COMPONENT_CODESET)
3057 if (mask & COMPONENT_TERRITORY)
3059 if (mask & COMPONENT_MODIFIER)
3065 /* The following is (partly) taken from the gettext package.
3066 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3068 static const gchar *
3069 guess_category_value (const gchar *category_name)
3071 const gchar *retval;
3073 /* The highest priority value is the `LANGUAGE' environment
3074 variable. This is a GNU extension. */
3075 retval = g_getenv ("LANGUAGE");
3076 if ((retval != NULL) && (retval[0] != '\0'))
3079 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3080 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3081 systems this can be done by the `setlocale' function itself. */
3083 /* Setting of LC_ALL overwrites all other. */
3084 retval = g_getenv ("LC_ALL");
3085 if ((retval != NULL) && (retval[0] != '\0'))
3088 /* Next comes the name of the desired category. */
3089 retval = g_getenv (category_name);
3090 if ((retval != NULL) && (retval[0] != '\0'))
3093 /* Last possibility is the LANG environment variable. */
3094 retval = g_getenv ("LANG");
3095 if ((retval != NULL) && (retval[0] != '\0'))
3098 #ifdef G_PLATFORM_WIN32
3099 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3100 * LANG, which we already did above. Oh well. The main point of
3101 * calling g_win32_getlocale() is to get the thread's locale as used
3102 * by Windows and the Microsoft C runtime (in the "English_United
3103 * States" format) translated into the Unixish format.
3105 retval = g_win32_getlocale ();
3106 if ((retval != NULL) && (retval[0] != '\0'))
3113 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3115 struct _GLanguageNamesCache {
3117 gchar **language_names;
3121 language_names_cache_free (gpointer data)
3123 GLanguageNamesCache *cache = data;
3124 g_free (cache->languages);
3125 g_strfreev (cache->language_names);
3130 * g_get_language_names:
3132 * Computes a list of applicable locale names, which can be used to
3133 * e.g. construct locale-dependent filenames or search paths. The returned
3134 * list is sorted from most desirable to least desirable and always contains
3135 * the default locale "C".
3137 * For example, if LANGUAGE=de:en_US, then the returned list is
3138 * "de", "en_US", "en", "C".
3140 * This function consults the environment variables <envar>LANGUAGE</envar>,
3141 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3142 * to find the list of locales specified by the user.
3144 * Return value: a %NULL-terminated array of strings owned by GLib
3145 * that must not be modified or freed.
3149 G_CONST_RETURN gchar * G_CONST_RETURN *
3150 g_get_language_names (void)
3152 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
3153 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
3158 cache = g_new0 (GLanguageNamesCache, 1);
3159 g_static_private_set (&cache_private, cache, language_names_cache_free);
3162 value = guess_category_value ("LC_MESSAGES");
3166 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3173 g_free (cache->languages);
3174 g_strfreev (cache->language_names);
3175 cache->languages = g_strdup (value);
3177 alist = g_strsplit (value, ":", 0);
3179 for (a = alist; *a; a++)
3181 gchar *b = unalias_lang (*a);
3182 list = g_slist_concat (list, _g_compute_locale_variants (b));
3185 list = g_slist_append (list, g_strdup ("C"));
3187 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3188 for (l = list, i = 0; l; l = l->next, i++)
3189 languages[i] = l->data;
3190 languages[i] = NULL;
3192 g_slist_free (list);
3195 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3200 * @v: a #gpointer key
3202 * Converts a gpointer to a hash value.
3203 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3204 * when using pointers as keys in a #GHashTable.
3206 * Returns: a hash value corresponding to the key.
3209 g_direct_hash (gconstpointer v)
3211 return GPOINTER_TO_UINT (v);
3217 * @v2: a key to compare with @v1.
3219 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3220 * It can be passed to g_hash_table_new() as the @key_equal_func
3221 * parameter, when using pointers as keys in a #GHashTable.
3223 * Returns: %TRUE if the two keys match.
3226 g_direct_equal (gconstpointer v1,
3234 * @v1: a pointer to a #gint key.
3235 * @v2: a pointer to a #gint key to compare with @v1.
3237 * Compares the two #gint values being pointed to and returns
3238 * %TRUE if they are equal.
3239 * It can be passed to g_hash_table_new() as the @key_equal_func
3240 * parameter, when using pointers to integers as keys in a #GHashTable.
3242 * Returns: %TRUE if the two keys match.
3245 g_int_equal (gconstpointer v1,
3248 return *((const gint*) v1) == *((const gint*) v2);
3253 * @v: a pointer to a #gint key
3255 * Converts a pointer to a #gint to a hash value.
3256 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3257 * when using pointers to integers values as keys in a #GHashTable.
3259 * Returns: a hash value corresponding to the key.
3262 g_int_hash (gconstpointer v)
3264 return *(const gint*) v;
3269 * @v1: a pointer to a #gint64 key.
3270 * @v2: a pointer to a #gint64 key to compare with @v1.
3272 * Compares the two #gint64 values being pointed to and returns
3273 * %TRUE if they are equal.
3274 * It can be passed to g_hash_table_new() as the @key_equal_func
3275 * parameter, when using pointers to 64-bit integers as keys in a #GHashTable.
3277 * Returns: %TRUE if the two keys match.
3282 g_int64_equal (gconstpointer v1,
3285 return *((const gint64*) v1) == *((const gint64*) v2);
3290 * @v: a pointer to a #gint64 key
3292 * Converts a pointer to a #gint64 to a hash value.
3293 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3294 * when using pointers to 64-bit integers values as keys in a #GHashTable.
3296 * Returns: a hash value corresponding to the key.
3301 g_int64_hash (gconstpointer v)
3303 return (guint) *(const gint64*) v;
3308 * @v1: a pointer to a #gdouble key.
3309 * @v2: a pointer to a #gdouble key to compare with @v1.
3311 * Compares the two #gdouble values being pointed to and returns
3312 * %TRUE if they are equal.
3313 * It can be passed to g_hash_table_new() as the @key_equal_func
3314 * parameter, when using pointers to doubles as keys in a #GHashTable.
3316 * Returns: %TRUE if the two keys match.
3321 g_double_equal (gconstpointer v1,
3324 return *((const gdouble*) v1) == *((const gdouble*) v2);
3329 * @v: a pointer to a #gdouble key
3331 * Converts a pointer to a #gdouble to a hash value.
3332 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3333 * when using pointers to doubles as keys in a #GHashTable.
3335 * Returns: a hash value corresponding to the key.
3340 g_double_hash (gconstpointer v)
3342 return (guint) *(const gdouble*) v;
3346 * g_nullify_pointer:
3347 * @nullify_location: the memory address of the pointer.
3349 * Set the pointer at the specified location to %NULL.
3352 g_nullify_pointer (gpointer *nullify_location)
3354 g_return_if_fail (nullify_location != NULL);
3356 *nullify_location = NULL;
3362 * Get the codeset for the current locale.
3364 * Return value: a newly allocated string containing the name
3365 * of the codeset. This string must be freed with g_free().
3368 g_get_codeset (void)
3370 const gchar *charset;
3372 g_get_charset (&charset);
3374 return g_strdup (charset);
3377 /* This is called from g_thread_init(). It's used to
3378 * initialize some static data in a threadsafe way.
3381 _g_utils_thread_init (void)
3383 g_get_language_names ();
3389 * _glib_get_locale_dir:
3391 * Return the path to the share\locale or lib\locale subfolder of the
3392 * GLib installation folder. The path is in the system codepage. We
3393 * have to use system codepage as bindtextdomain() doesn't have a
3397 _glib_get_locale_dir (void)
3399 gchar *install_dir = NULL, *locale_dir;
3400 gchar *retval = NULL;
3402 if (glib_dll != NULL)
3403 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3408 * Append "/share/locale" or "/lib/locale" depending on whether
3409 * autoconfigury detected GNU gettext or not.
3411 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3417 locale_dir = g_build_filename (install_dir, p, NULL);
3419 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3421 g_free (install_dir);
3422 g_free (locale_dir);
3428 return g_strdup ("");
3431 #undef GLIB_LOCALE_DIR
3433 #endif /* G_OS_WIN32 */
3437 * @str: The string to be translated
3439 * Returns the translated string from the glib translations.
3440 * This is an internal function and should only be used by
3441 * the internals of glib (such as libgio).
3443 * Returns: the transation of @str to the current locale
3445 G_CONST_RETURN gchar *
3446 glib_gettext (const gchar *str)
3448 static gboolean _glib_gettext_initialized = FALSE;
3450 if (!_glib_gettext_initialized)
3453 gchar *tmp = _glib_get_locale_dir ();
3454 bindtextdomain (GETTEXT_PACKAGE, tmp);
3457 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3459 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3460 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3462 _glib_gettext_initialized = TRUE;
3465 return g_dgettext (GETTEXT_PACKAGE, str);
3468 #if defined (G_OS_WIN32) && !defined (_WIN64)
3470 /* Binary compatibility versions. Not for newly compiled code. */
3472 #undef g_find_program_in_path
3475 g_find_program_in_path (const gchar *program)
3477 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3478 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3481 g_free (utf8_program);
3482 if (utf8_retval == NULL)
3484 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3485 g_free (utf8_retval);
3490 #undef g_get_current_dir
3493 g_get_current_dir (void)
3495 gchar *utf8_dir = g_get_current_dir_utf8 ();
3496 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3503 G_CONST_RETURN gchar*
3504 g_getenv (const gchar *variable)
3506 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3507 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3511 g_free (utf8_variable);
3514 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3515 quark = g_quark_from_string (value);
3518 return g_quark_to_string (quark);
3524 g_setenv (const gchar *variable,
3528 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3529 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3530 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3532 g_free (utf8_variable);
3533 g_free (utf8_value);
3541 g_unsetenv (const gchar *variable)
3543 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3545 g_unsetenv_utf8 (utf8_variable);
3547 g_free (utf8_variable);
3550 #undef g_get_user_name
3552 G_CONST_RETURN gchar*
3553 g_get_user_name (void)
3555 g_get_any_init_locked ();
3556 return g_user_name_cp;
3559 #undef g_get_real_name
3561 G_CONST_RETURN gchar*
3562 g_get_real_name (void)
3564 g_get_any_init_locked ();
3565 return g_real_name_cp;
3568 #undef g_get_home_dir
3570 G_CONST_RETURN gchar*
3571 g_get_home_dir (void)
3573 g_get_any_init_locked ();
3574 return g_home_dir_cp;
3577 #undef g_get_tmp_dir
3579 G_CONST_RETURN gchar*
3580 g_get_tmp_dir (void)
3582 g_get_any_init_locked ();
3583 return g_tmp_dir_cp;
3588 #define __G_UTILS_C__
3589 #include "galiasdef.c"