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.
42 #include <ctype.h> /* For tolower() */
44 #include <sys/types.h>
49 #include <sys/types.h>
50 #ifdef HAVE_SYS_PARAM_H
51 #include <sys/param.h>
53 #ifdef HAVE_CRT_EXTERNS_H
54 #include <crt_externs.h> /* for _NSGetEnviron */
57 /* implement gutils's inline functions
59 #define G_IMPLEMENT_INLINES 1
62 #include "gprintfint.h"
63 #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_COMMON_DOCUMENTS
104 # define CSIDL_COMMON_DOCUMENTS 46
106 # ifndef CSIDL_PROFILE
107 # define CSIDL_PROFILE 40
109 # include <process.h>
113 #include <CoreServices/CoreServices.h>
117 #include <langinfo.h>
120 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
124 const guint glib_major_version = GLIB_MAJOR_VERSION;
125 const guint glib_minor_version = GLIB_MINOR_VERSION;
126 const guint glib_micro_version = GLIB_MICRO_VERSION;
127 const guint glib_interface_age = GLIB_INTERFACE_AGE;
128 const guint glib_binary_age = GLIB_BINARY_AGE;
130 #ifdef G_PLATFORM_WIN32
132 G_WIN32_DLLMAIN_FOR_DLL_NAME (static, dll_name)
137 * glib_check_version:
138 * @required_major: the required major version.
139 * @required_minor: the required minor version.
140 * @required_micro: the required micro version.
142 * Checks that the GLib library in use is compatible with the
143 * given version. Generally you would pass in the constants
144 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
145 * as the three arguments to this function; that produces
146 * a check that the library in use is compatible with
147 * the version of GLib the application or module was compiled
150 * Compatibility is defined by two things: first the version
151 * of the running library is newer than the version
152 * @required_major.required_minor.@required_micro. Second
153 * the running library must be binary compatible with the
154 * version @required_major.required_minor.@required_micro
155 * (same major version.)
157 * Return value: %NULL if the GLib library is compatible with the
158 * given version, or a string describing the version mismatch.
159 * The returned string is owned by GLib and must not be modified
165 glib_check_version (guint required_major,
166 guint required_minor,
167 guint required_micro)
169 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
170 gint required_effective_micro = 100 * required_minor + required_micro;
172 if (required_major > GLIB_MAJOR_VERSION)
173 return "GLib version too old (major mismatch)";
174 if (required_major < GLIB_MAJOR_VERSION)
175 return "GLib version too new (major mismatch)";
176 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
177 return "GLib version too new (micro mismatch)";
178 if (required_effective_micro > glib_effective_micro)
179 return "GLib version too old (micro mismatch)";
183 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
186 * @dest: the destination address to copy the bytes to.
187 * @src: the source address to copy the bytes from.
188 * @len: the number of bytes to copy.
190 * Copies a block of memory @len bytes long, from @src to @dest.
191 * The source and destination areas may overlap.
193 * In order to use this function, you must include
194 * <filename>string.h</filename> yourself, because this macro will
195 * typically simply resolve to memmove() and GLib does not include
196 * <filename>string.h</filename> for you.
199 g_memmove (gpointer dest,
203 gchar* destptr = dest;
204 const gchar* srcptr = src;
205 if (src + len < dest || dest + len < src)
207 bcopy (src, dest, len);
210 else if (dest <= src)
213 *(destptr++) = *(srcptr++);
220 *(--destptr) = *(--srcptr);
223 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
231 * @func: the function to call on normal program termination.
233 * Specifies a function to be called at normal program termination.
235 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
236 * macro that maps to a call to the atexit() function in the C
237 * library. This means that in case the code that calls g_atexit(),
238 * i.e. atexit(), is in a DLL, the function will be called when the
239 * DLL is detached from the program. This typically makes more sense
240 * than that the function is called when the GLib DLL is detached,
241 * which happened earlier when g_atexit() was a function in the GLib
244 * The behaviour of atexit() in the context of dynamically loaded
245 * modules is not formally specified and varies wildly.
247 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
248 * loaded module which is unloaded before the program terminates might
249 * well cause a crash at program exit.
251 * Some POSIX systems implement atexit() like Windows, and have each
252 * dynamically loaded module maintain an own atexit chain that is
253 * called when the module is unloaded.
255 * On other POSIX systems, before a dynamically loaded module is
256 * unloaded, the registered atexit functions (if any) residing in that
257 * module are called, regardless where the code that registered them
258 * resided. This is presumably the most robust approach.
260 * As can be seen from the above, for portability it's best to avoid
261 * calling g_atexit() (or atexit()) except in the main executable of a
265 g_atexit (GVoidFunc func)
268 const gchar *error = NULL;
270 /* keep this in sync with glib.h */
272 #ifdef G_NATIVE_ATEXIT
273 result = ATEXIT (func);
275 error = g_strerror (errno);
276 #elif defined (HAVE_ATEXIT)
277 # ifdef NeXT /* @#%@! NeXTStep */
278 result = !atexit ((void (*)(void)) func);
280 error = g_strerror (errno);
282 result = atexit ((void (*)(void)) func);
284 error = g_strerror (errno);
286 #elif defined (HAVE_ON_EXIT)
287 result = on_exit ((void (*)(int, void *)) func, NULL);
289 error = g_strerror (errno);
292 error = "no implementation";
293 #endif /* G_NATIVE_ATEXIT */
296 g_error ("Could not register atexit() function: %s", error);
299 /* Based on execvp() from GNU Libc.
300 * Some of this code is cut-and-pasted into gspawn.c
304 my_strchrnul (const gchar *str,
307 gchar *p = (gchar*)str;
308 while (*p && (*p != c))
316 static gchar *inner_find_program_in_path (const gchar *program);
319 g_find_program_in_path (const gchar *program)
321 const gchar *last_dot = strrchr (program, '.');
323 if (last_dot == NULL ||
324 strchr (last_dot, '\\') != NULL ||
325 strchr (last_dot, '/') != NULL)
327 const gint program_length = strlen (program);
328 gchar *pathext = g_build_path (";",
329 ".exe;.cmd;.bat;.com",
330 g_getenv ("PATHEXT"),
333 gchar *decorated_program;
339 gchar *q = my_strchrnul (p, ';');
341 decorated_program = g_malloc (program_length + (q-p) + 1);
342 memcpy (decorated_program, program, program_length);
343 memcpy (decorated_program+program_length, p, q-p);
344 decorated_program [program_length + (q-p)] = '\0';
346 retval = inner_find_program_in_path (decorated_program);
347 g_free (decorated_program);
355 } while (*p++ != '\0');
360 return inner_find_program_in_path (program);
366 * g_find_program_in_path:
367 * @program: a program name in the GLib file name encoding
369 * Locates the first executable named @program in the user's path, in the
370 * same way that execvp() would locate it. Returns an allocated string
371 * with the absolute path name, or %NULL if the program is not found in
372 * the path. If @program is already an absolute path, returns a copy of
373 * @program if @program exists and is executable, and %NULL otherwise.
375 * On Windows, if @program does not have a file type suffix, tries
376 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
377 * the <envar>PATHEXT</envar> environment variable.
379 * On Windows, it looks for the file in the same way as CreateProcess()
380 * would. This means first in the directory where the executing
381 * program was loaded from, then in the current directory, then in the
382 * Windows 32-bit system directory, then in the Windows directory, and
383 * finally in the directories in the <envar>PATH</envar> environment
384 * variable. If the program is found, the return value contains the
385 * full name including the type suffix.
387 * Return value: absolute path, or %NULL
391 inner_find_program_in_path (const gchar *program)
394 g_find_program_in_path (const gchar *program)
397 const gchar *path, *p;
398 gchar *name, *freeme;
400 const gchar *path_copy;
401 gchar *filename = NULL, *appdir = NULL;
402 gchar *sysdir = NULL, *windir = NULL;
404 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
410 g_return_val_if_fail (program != NULL, NULL);
412 /* If it is an absolute path, or a relative path including subdirectories,
413 * don't look in PATH.
415 if (g_path_is_absolute (program)
416 || strchr (program, G_DIR_SEPARATOR) != NULL
418 || strchr (program, '/') != NULL
422 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
423 !g_file_test (program, G_FILE_TEST_IS_DIR))
424 return g_strdup (program);
429 path = g_getenv ("PATH");
430 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
433 /* There is no `PATH' in the environment. The default
434 * search path in GNU libc is the current directory followed by
435 * the path `confstr' returns for `_CS_PATH'.
438 /* In GLib we put . last, for security, and don't use the
439 * unportable confstr(); UNIX98 does not actually specify
440 * what to search if PATH is unset. POSIX may, dunno.
443 path = "/bin:/usr/bin:.";
446 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
447 if (n > 0 && n < MAXPATHLEN)
448 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
450 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
451 if (n > 0 && n < MAXPATHLEN)
452 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
454 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
455 if (n > 0 && n < MAXPATHLEN)
456 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
460 appdir = g_path_get_dirname (filename);
464 path = g_strdup (path);
468 const gchar *tem = path;
469 path = g_strconcat (windir, ";", path, NULL);
470 g_free ((gchar *) tem);
476 const gchar *tem = path;
477 path = g_strconcat (sysdir, ";", path, NULL);
478 g_free ((gchar *) tem);
483 const gchar *tem = path;
484 path = g_strconcat (".;", path, NULL);
485 g_free ((gchar *) tem);
490 const gchar *tem = path;
491 path = g_strconcat (appdir, ";", path, NULL);
492 g_free ((gchar *) tem);
499 len = strlen (program) + 1;
500 pathlen = strlen (path);
501 freeme = name = g_malloc (pathlen + len + 1);
503 /* Copy the file name at the top, including '\0' */
504 memcpy (name + pathlen + 1, program, len);
505 name = name + pathlen;
506 /* And add the slash before the filename */
507 *name = G_DIR_SEPARATOR;
515 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
518 /* Two adjacent colons, or a colon at the beginning or the end
519 * of `PATH' means to search the current directory.
523 startp = memcpy (name - (p - path), path, p - path);
525 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
526 !g_file_test (startp, G_FILE_TEST_IS_DIR))
529 ret = g_strdup (startp);
532 g_free ((gchar *) path_copy);
537 while (*p++ != '\0');
541 g_free ((gchar *) path_copy);
548 debug_key_matches (const gchar *key,
552 for (; length; length--, key++, token++)
554 char k = (*key == '_') ? '-' : tolower (*key );
555 char t = (*token == '_') ? '-' : tolower (*token);
565 * g_parse_debug_string:
566 * @string: a list of debug options separated by colons, spaces, or
567 * commas; or the string "all" to set all flags.
568 * @keys: pointer to an array of #GDebugKey which associate
569 * strings with bit flags.
570 * @nkeys: the number of #GDebugKey<!-- -->s in the array.
572 * Parses a string containing debugging options
573 * into a %guint containing bit flags. This is used
574 * within GDK and GTK+ to parse the debug options passed on the
575 * command line or through environment variables.
577 * Returns: the combined set of bit flags.
580 g_parse_debug_string (const gchar *string,
581 const GDebugKey *keys,
587 g_return_val_if_fail (string != NULL, 0);
589 /* this function is used by gmem.c/gslice.c initialization code,
590 * so introducing malloc dependencies here would require adaptions
591 * of those code portions.
594 if (!g_ascii_strcasecmp (string, "all"))
596 for (i=0; i<nkeys; i++)
597 result |= keys[i].value;
601 const gchar *p = string;
606 q = strpbrk (p, ":;, \t");
610 for (i = 0; i < nkeys; i++)
611 if (debug_key_matches (keys[i].key, p, q - p))
612 result |= keys[i].value;
625 * @file_name: the name of the file.
627 * Gets the name of the file without any leading directory components.
628 * It returns a pointer into the given file name string.
630 * Return value: the name of the file without any leading directory components.
632 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
633 * g_path_get_basename() allocates new memory for the returned string, unlike
634 * this function which returns a pointer into the argument.
636 G_CONST_RETURN gchar*
637 g_basename (const gchar *file_name)
639 register gchar *base;
641 g_return_val_if_fail (file_name != NULL, NULL);
643 base = strrchr (file_name, G_DIR_SEPARATOR);
647 gchar *q = strrchr (file_name, '/');
648 if (base == NULL || (q != NULL && q > base))
657 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
658 return (gchar*) file_name + 2;
659 #endif /* G_OS_WIN32 */
661 return (gchar*) file_name;
665 * g_path_get_basename:
666 * @file_name: the name of the file.
668 * Gets the last component of the filename. If @file_name ends with a
669 * directory separator it gets the component before the last slash. If
670 * @file_name consists only of directory separators (and on Windows,
671 * possibly a drive letter), a single separator is returned. If
672 * @file_name is empty, it gets ".".
674 * Return value: a newly allocated string containing the last component of
678 g_path_get_basename (const gchar *file_name)
680 register gssize base;
681 register gssize last_nonslash;
685 g_return_val_if_fail (file_name != NULL, NULL);
687 if (file_name[0] == '\0')
689 return g_strdup (".");
691 last_nonslash = strlen (file_name) - 1;
693 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
696 if (last_nonslash == -1)
697 /* string only containing slashes */
698 return g_strdup (G_DIR_SEPARATOR_S);
701 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
702 /* string only containing slashes and a drive */
703 return g_strdup (G_DIR_SEPARATOR_S);
704 #endif /* G_OS_WIN32 */
706 base = last_nonslash;
708 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
712 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
714 #endif /* G_OS_WIN32 */
716 len = last_nonslash - base;
717 retval = g_malloc (len + 1);
718 memcpy (retval, file_name + base + 1, len);
724 * g_path_is_absolute:
725 * @file_name: a file name.
727 * Returns %TRUE if the given @file_name is an absolute file name,
728 * i.e. it contains a full path from the root directory such as "/usr/local"
729 * on UNIX or "C:\windows" on Windows systems.
731 * Returns: %TRUE if @file_name is an absolute path.
734 g_path_is_absolute (const gchar *file_name)
736 g_return_val_if_fail (file_name != NULL, FALSE);
738 if (G_IS_DIR_SEPARATOR (file_name[0]))
742 /* Recognize drive letter on native Windows */
743 if (g_ascii_isalpha (file_name[0]) &&
744 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
746 #endif /* G_OS_WIN32 */
753 * @file_name: a file name.
755 * Returns a pointer into @file_name after the root component, i.e. after
756 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
757 * path it returns %NULL.
759 * Returns: a pointer into @file_name after the root component.
761 G_CONST_RETURN gchar*
762 g_path_skip_root (const gchar *file_name)
764 g_return_val_if_fail (file_name != NULL, NULL);
766 #ifdef G_PLATFORM_WIN32
767 /* Skip \\server\share or //server/share */
768 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
769 G_IS_DIR_SEPARATOR (file_name[1]) &&
771 !G_IS_DIR_SEPARATOR (file_name[2]))
775 p = strchr (file_name + 2, G_DIR_SEPARATOR);
778 gchar *q = strchr (file_name + 2, '/');
779 if (p == NULL || (q != NULL && q < p))
789 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
792 /* Possibly skip a backslash after the share name */
793 if (G_IS_DIR_SEPARATOR (file_name[0]))
796 return (gchar *)file_name;
801 /* Skip initial slashes */
802 if (G_IS_DIR_SEPARATOR (file_name[0]))
804 while (G_IS_DIR_SEPARATOR (file_name[0]))
806 return (gchar *)file_name;
811 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
812 return (gchar *)file_name + 3;
819 * g_path_get_dirname:
820 * @file_name: the name of the file.
822 * Gets the directory components of a file name. If the file name has no
823 * directory components "." is returned. The returned string should be
824 * freed when no longer needed.
826 * Returns: the directory components of the file.
829 g_path_get_dirname (const gchar *file_name)
831 register gchar *base;
834 g_return_val_if_fail (file_name != NULL, NULL);
836 base = strrchr (file_name, G_DIR_SEPARATOR);
839 gchar *q = strrchr (file_name, '/');
840 if (base == NULL || (q != NULL && q > base))
847 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
849 gchar drive_colon_dot[4];
851 drive_colon_dot[0] = file_name[0];
852 drive_colon_dot[1] = ':';
853 drive_colon_dot[2] = '.';
854 drive_colon_dot[3] = '\0';
856 return g_strdup (drive_colon_dot);
859 return g_strdup (".");
862 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
866 /* base points to the char before the last slash.
868 * In case file_name is the root of a drive (X:\) or a child of the
869 * root of a drive (X:\foo), include the slash.
871 * In case file_name is the root share of an UNC path
872 * (\\server\share), add a slash, returning \\server\share\ .
874 * In case file_name is a direct child of a share in an UNC path
875 * (\\server\share\foo), include the slash after the share name,
876 * returning \\server\share\ .
878 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
880 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
881 G_IS_DIR_SEPARATOR (file_name[1]) &&
883 !G_IS_DIR_SEPARATOR (file_name[2]) &&
884 base >= file_name + 2)
886 const gchar *p = file_name + 2;
887 while (*p && !G_IS_DIR_SEPARATOR (*p))
891 len = (guint) strlen (file_name) + 1;
892 base = g_new (gchar, len + 1);
893 strcpy (base, file_name);
894 base[len-1] = G_DIR_SEPARATOR;
898 if (G_IS_DIR_SEPARATOR (*p))
901 while (*p && !G_IS_DIR_SEPARATOR (*p))
909 len = (guint) 1 + base - file_name;
911 base = g_new (gchar, len + 1);
912 g_memmove (base, file_name, len);
921 * Gets the current directory.
922 * The returned string should be freed when no longer needed. The encoding
923 * of the returned string is system defined. On Windows, it is always UTF-8.
925 * Returns: the current directory.
928 g_get_current_dir (void)
933 wchar_t dummy[2], *wdir;
936 len = GetCurrentDirectoryW (2, dummy);
937 wdir = g_new (wchar_t, len);
939 if (GetCurrentDirectoryW (len, wdir) == len - 1)
940 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
945 dir = g_strdup ("\\");
951 gchar *buffer = NULL;
953 static gulong max_len = 0;
956 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
958 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
959 * and, if that wasn't bad enough, hangs in doing so.
961 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
962 buffer = g_new (gchar, max_len + 1);
964 dir = getwd (buffer);
965 #else /* !sun || !HAVE_GETCWD */
966 while (max_len < G_MAXULONG / 2)
969 buffer = g_new (gchar, max_len + 1);
971 dir = getcwd (buffer, max_len);
973 if (dir || errno != ERANGE)
978 #endif /* !sun || !HAVE_GETCWD */
980 if (!dir || !*buffer)
982 /* hm, should we g_error() out here?
983 * this can happen if e.g. "./" has mode \0000
985 buffer[0] = G_DIR_SEPARATOR;
989 dir = g_strdup (buffer);
998 * @variable: the environment variable to get, in the GLib file name encoding.
1000 * Returns the value of an environment variable. The name and value
1001 * are in the GLib file name encoding. On UNIX, this means the actual
1002 * bytes which might or might not be in some consistent character set
1003 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1004 * environment variable's value contains references to other
1005 * environment variables, they are expanded.
1007 * Return value: the value of the environment variable, or %NULL if
1008 * the environment variable is not found. The returned string may be
1009 * overwritten by the next call to g_getenv(), g_setenv() or
1012 G_CONST_RETURN gchar*
1013 g_getenv (const gchar *variable)
1017 g_return_val_if_fail (variable != NULL, NULL);
1019 return getenv (variable);
1021 #else /* G_OS_WIN32 */
1025 wchar_t dummy[2], *wname, *wvalue;
1028 g_return_val_if_fail (variable != NULL, NULL);
1029 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1031 /* On Windows NT, it is relatively typical that environment
1032 * variables contain references to other environment variables. If
1033 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1034 * environment variables would be stored in the Registry as
1035 * REG_EXPAND_SZ type values, and would then get automatically
1036 * expanded before a program sees them. But there is broken software
1037 * that stores environment variables as REG_SZ values even if they
1038 * contain references to other environment variables.)
1041 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1043 len = GetEnvironmentVariableW (wname, dummy, 2);
1053 wvalue = g_new (wchar_t, len);
1055 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1062 if (wcschr (wvalue, L'%') != NULL)
1064 wchar_t *tem = wvalue;
1066 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1070 wvalue = g_new (wchar_t, len);
1072 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1082 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1087 quark = g_quark_from_string (value);
1090 return g_quark_to_string (quark);
1092 #endif /* G_OS_WIN32 */
1095 /* _g_getenv_nomalloc
1096 * this function does a getenv() without doing any kind of allocation
1097 * through glib. it's suitable for chars <= 127 only (both, for the
1098 * variable name and the contents) and for contents < 1024 chars in
1099 * length. also, it aliases "" to a NULL return value.
1102 _g_getenv_nomalloc (const gchar *variable,
1105 const gchar *retval = getenv (variable);
1106 if (retval && retval[0])
1108 gint l = strlen (retval);
1111 strncpy (buffer, retval, l);
1121 * @variable: the environment variable to set, must not contain '='.
1122 * @value: the value for to set the variable to.
1123 * @overwrite: whether to change the variable if it already exists.
1125 * Sets an environment variable. Both the variable's name and value
1126 * should be in the GLib file name encoding. On UNIX, this means that
1127 * they can be any sequence of bytes. On Windows, they should be in
1130 * Note that on some systems, when variables are overwritten, the memory
1131 * used for the previous variables and its value isn't reclaimed.
1133 * Returns: %FALSE if the environment variable couldn't be set.
1138 g_setenv (const gchar *variable,
1149 g_return_val_if_fail (variable != NULL, FALSE);
1150 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1153 result = setenv (variable, value, overwrite);
1155 if (!overwrite && getenv (variable) != NULL)
1158 /* This results in a leak when you overwrite existing
1159 * settings. It would be fairly easy to fix this by keeping
1160 * our own parallel array or hash table.
1162 string = g_strconcat (variable, "=", value, NULL);
1163 result = putenv (string);
1167 #else /* G_OS_WIN32 */
1170 wchar_t *wname, *wvalue, *wassignment;
1173 g_return_val_if_fail (variable != NULL, FALSE);
1174 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1175 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1176 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1178 if (!overwrite && g_getenv (variable) != NULL)
1181 /* We want to (if possible) set both the environment variable copy
1182 * kept by the C runtime and the one kept by the system.
1184 * We can't use only the C runtime's putenv or _wputenv() as that
1185 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1186 * (with main() and not wmain()). In a "main()" app the C runtime
1187 * initializes the C runtime's environment table by converting the
1188 * real (wide char) environment variables to system codepage, thus
1189 * breaking those that aren't representable in the system codepage.
1191 * As the C runtime's putenv() will also set the system copy, we do
1192 * the putenv() first, then call SetEnvironmentValueW ourselves.
1195 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1196 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1197 tem = g_strconcat (variable, "=", value, NULL);
1198 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1201 _wputenv (wassignment);
1202 g_free (wassignment);
1204 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1211 #endif /* G_OS_WIN32 */
1214 #ifdef HAVE__NSGETENVIRON
1215 #define environ (*_NSGetEnviron())
1216 #elif !defined(G_OS_WIN32)
1218 /* According to the Single Unix Specification, environ is not in
1219 * any system header, although unistd.h often declares it.
1221 extern char **environ;
1226 * @variable: the environment variable to remove, must not contain '='.
1228 * Removes an environment variable from the environment.
1230 * Note that on some systems, when variables are overwritten, the memory
1231 * used for the previous variables and its value isn't reclaimed.
1232 * Furthermore, this function can't be guaranteed to operate in a
1238 g_unsetenv (const gchar *variable)
1242 #ifdef HAVE_UNSETENV
1243 g_return_if_fail (variable != NULL);
1244 g_return_if_fail (strchr (variable, '=') == NULL);
1246 unsetenv (variable);
1247 #else /* !HAVE_UNSETENV */
1251 g_return_if_fail (variable != NULL);
1252 g_return_if_fail (strchr (variable, '=') == NULL);
1254 len = strlen (variable);
1256 /* Mess directly with the environ array.
1257 * This seems to be the only portable way to do this.
1259 * Note that we remove *all* environment entries for
1260 * the variable name, not just the first.
1265 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1273 #endif /* !HAVE_UNSETENV */
1275 #else /* G_OS_WIN32 */
1277 wchar_t *wname, *wassignment;
1280 g_return_if_fail (variable != NULL);
1281 g_return_if_fail (strchr (variable, '=') == NULL);
1282 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1284 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1285 tem = g_strconcat (variable, "=", NULL);
1286 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1289 _wputenv (wassignment);
1290 g_free (wassignment);
1292 SetEnvironmentVariableW (wname, NULL);
1296 #endif /* G_OS_WIN32 */
1302 * Gets the names of all variables set in the environment.
1304 * Returns: a %NULL-terminated list of strings which must be freed
1305 * with g_strfreev().
1307 * Programs that want to be portable to Windows should typically use
1308 * this function and g_getenv() instead of using the environ array
1309 * from the C library directly. On Windows, the strings in the environ
1310 * array are in system codepage encoding, while in most of the typical
1311 * use cases for environment variables in GLib-using programs you want
1312 * the UTF-8 encoding that this function and g_getenv() provide.
1320 gchar **result, *eq;
1323 len = g_strv_length (environ);
1324 result = g_new0 (gchar *, len + 1);
1327 for (i = 0; i < len; i++)
1329 eq = strchr (environ[i], '=');
1331 result[j++] = g_strndup (environ[i], eq - environ[i]);
1338 gchar **result, *eq;
1342 p = (wchar_t *) GetEnvironmentStringsW ();
1348 q += wcslen (q) + 1;
1352 result = g_new0 (gchar *, len + 1);
1358 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1359 if (result[j] != NULL)
1361 eq = strchr (result[j], '=');
1362 if (eq && eq > result[j])
1370 q += wcslen (q) + 1;
1373 FreeEnvironmentStringsW (p);
1379 G_LOCK_DEFINE_STATIC (g_utils_global);
1381 static gchar *g_tmp_dir = NULL;
1382 static gchar *g_user_name = NULL;
1383 static gchar *g_real_name = NULL;
1384 static gchar *g_home_dir = NULL;
1385 static gchar *g_host_name = NULL;
1388 /* System codepage versions of the above, kept at file level so that they,
1389 * too, are produced only once.
1391 static gchar *g_tmp_dir_cp = NULL;
1392 static gchar *g_user_name_cp = NULL;
1393 static gchar *g_real_name_cp = NULL;
1394 static gchar *g_home_dir_cp = NULL;
1397 static gchar *g_user_data_dir = NULL;
1398 static gchar **g_system_data_dirs = NULL;
1399 static gchar *g_user_cache_dir = NULL;
1400 static gchar *g_user_config_dir = NULL;
1401 static gchar **g_system_config_dirs = NULL;
1403 static gchar **g_user_special_dirs = NULL;
1405 /* fifteen minutes of fame for everybody */
1406 #define G_USER_DIRS_EXPIRE 15 * 60
1411 get_special_folder (int csidl)
1413 wchar_t path[MAX_PATH+1];
1415 LPITEMIDLIST pidl = NULL;
1417 gchar *retval = NULL;
1419 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1422 b = SHGetPathFromIDListW (pidl, path);
1424 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1425 CoTaskMemFree (pidl);
1431 get_windows_directory_root (void)
1433 wchar_t wwindowsdir[MAX_PATH];
1435 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1437 /* Usually X:\Windows, but in terminal server environments
1438 * might be an UNC path, AFAIK.
1440 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1443 if (windowsdir == NULL)
1444 return g_strdup ("C:\\");
1446 p = (char *) g_path_skip_root (windowsdir);
1447 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1453 return g_strdup ("C:\\");
1458 /* HOLDS: g_utils_global_lock */
1460 g_get_any_init_do (void)
1462 gchar hostname[100];
1464 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1466 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1468 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1472 g_tmp_dir = get_windows_directory_root ();
1478 g_tmp_dir = g_strdup (P_tmpdir);
1479 k = strlen (g_tmp_dir);
1480 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1481 g_tmp_dir[k - 1] = '\0';
1487 g_tmp_dir = g_strdup ("/tmp");
1489 #endif /* !G_OS_WIN32 */
1492 /* We check $HOME first for Win32, though it is a last resort for Unix
1493 * where we prefer the results of getpwuid().
1495 g_home_dir = g_strdup (g_getenv ("HOME"));
1497 /* Only believe HOME if it is an absolute path and exists */
1500 if (!(g_path_is_absolute (g_home_dir) &&
1501 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1503 g_free (g_home_dir);
1508 /* In case HOME is Unix-style (it happens), convert it to
1514 while ((p = strchr (g_home_dir, '/')) != NULL)
1520 /* USERPROFILE is probably the closest equivalent to $HOME? */
1521 if (g_getenv ("USERPROFILE") != NULL)
1522 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1526 g_home_dir = get_special_folder (CSIDL_PROFILE);
1529 g_home_dir = get_windows_directory_root ();
1530 #endif /* G_OS_WIN32 */
1534 struct passwd *pw = NULL;
1535 gpointer buffer = NULL;
1539 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1541 # ifdef _SC_GETPW_R_SIZE_MAX
1542 /* This reurns the maximum length */
1543 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1547 # else /* _SC_GETPW_R_SIZE_MAX */
1549 # endif /* _SC_GETPW_R_SIZE_MAX */
1551 logname = (gchar *) g_getenv ("LOGNAME");
1556 /* we allocate 6 extra bytes to work around a bug in
1557 * Mac OS < 10.3. See #156446
1559 buffer = g_malloc (bufsize + 6);
1562 # ifdef HAVE_POSIX_GETPWUID_R
1564 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1565 if (!pw || (pw->pw_uid != getuid ())) {
1566 /* LOGNAME is lying, fall back to looking up the uid */
1567 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1570 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1572 error = error < 0 ? errno : error;
1573 # else /* HAVE_NONPOSIX_GETPWUID_R */
1574 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1575 # if defined(_AIX) || defined(__hpux)
1576 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1577 pw = error == 0 ? &pwd : NULL;
1580 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1581 if (!pw || (pw->pw_uid != getuid ())) {
1582 /* LOGNAME is lying, fall back to looking up the uid */
1583 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1586 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1588 error = pw ? 0 : errno;
1590 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1594 /* we bail out prematurely if the user id can't be found
1595 * (should be pretty rare case actually), or if the buffer
1596 * should be sufficiently big and lookups are still not
1599 if (error == 0 || error == ENOENT)
1601 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1602 (gulong) getuid ());
1605 if (bufsize > 32 * 1024)
1607 g_warning ("getpwuid_r(): failed due to: %s.",
1608 g_strerror (error));
1616 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1621 pw = getpwuid (getuid ());
1626 g_user_name = g_strdup (pw->pw_name);
1628 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1630 gchar **gecos_fields;
1633 /* split the gecos field and substitute '&' */
1634 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1635 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1636 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1637 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1638 g_strfreev (gecos_fields);
1639 g_strfreev (name_parts);
1643 g_home_dir = g_strdup (pw->pw_dir);
1648 #else /* !HAVE_PWD_H */
1652 guint len = UNLEN+1;
1653 wchar_t buffer[UNLEN+1];
1655 if (GetUserNameW (buffer, (LPDWORD) &len))
1657 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1658 g_real_name = g_strdup (g_user_name);
1661 #endif /* G_OS_WIN32 */
1663 #endif /* !HAVE_PWD_H */
1667 g_home_dir = g_strdup (g_getenv ("HOME"));
1671 /* change '\\' in %HOME% to '/' */
1672 g_strdelimit (g_home_dir, "\\",'/');
1675 g_user_name = g_strdup ("somebody");
1677 g_real_name = g_strdup ("Unknown");
1681 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1683 DWORD size = sizeof (hostname);
1684 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1686 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1690 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1691 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1692 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1695 g_tmp_dir_cp = g_strdup ("\\");
1696 if (!g_user_name_cp)
1697 g_user_name_cp = g_strdup ("somebody");
1698 if (!g_real_name_cp)
1699 g_real_name_cp = g_strdup ("Unknown");
1701 /* home_dir might be NULL, unlike tmp_dir, user_name and
1705 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1707 g_home_dir_cp = NULL;
1708 #endif /* G_OS_WIN32 */
1712 g_get_any_init (void)
1715 g_get_any_init_do ();
1719 g_get_any_init_locked (void)
1721 G_LOCK (g_utils_global);
1723 G_UNLOCK (g_utils_global);
1730 * Gets the user name of the current user. The encoding of the returned
1731 * string is system-defined. On UNIX, it might be the preferred file name
1732 * encoding, or something else, and there is no guarantee that it is even
1733 * consistent on a machine. On Windows, it is always UTF-8.
1735 * Returns: the user name of the current user.
1737 G_CONST_RETURN gchar*
1738 g_get_user_name (void)
1740 g_get_any_init_locked ();
1747 * Gets the real name of the user. This usually comes from the user's entry
1748 * in the <filename>passwd</filename> file. The encoding of the returned
1749 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1750 * If the real user name cannot be determined, the string "Unknown" is
1753 * Returns: the user's real name.
1755 G_CONST_RETURN gchar*
1756 g_get_real_name (void)
1758 g_get_any_init_locked ();
1765 * Gets the current user's home directory as defined in the
1766 * password database.
1768 * Note that in contrast to traditional UNIX tools, this function
1769 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1770 * environment variable.
1772 * One of the reasons for this decision is that applications in many
1773 * cases need special handling to deal with the case where
1774 * <envar>HOME</envar> is
1776 * <member>Not owned by the user</member>
1777 * <member>Not writeable</member>
1778 * <member>Not even readable</member>
1780 * Since applications are in general <emphasis>not</emphasis> written
1781 * to deal with these situations it was considered better to make
1782 * g_get_homedir() not pay attention to <envar>HOME</envar> and to
1783 * return the real home directory for the user. If applications
1784 * want to pay attention to <envar>HOME</envar>, they can do:
1786 * const char *homedir = g_getenv ("HOME");
1788 * homedir = g_get_homedir (<!-- -->);
1791 * Returns: the current user's home directory
1793 G_CONST_RETURN gchar*
1794 g_get_home_dir (void)
1796 g_get_any_init_locked ();
1803 * Gets the directory to use for temporary files. This is found from
1804 * inspecting the environment variables <envar>TMPDIR</envar>,
1805 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1806 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1807 * The encoding of the returned string is system-defined. On Windows,
1808 * it is always UTF-8. The return value is never %NULL.
1810 * Returns: the directory to use for temporary files.
1812 G_CONST_RETURN gchar*
1813 g_get_tmp_dir (void)
1815 g_get_any_init_locked ();
1822 * Return a name for the machine.
1824 * The returned name is not necessarily a fully-qualified domain name,
1825 * or even present in DNS or some other name service at all. It need
1826 * not even be unique on your local network or site, but usually it
1827 * is. Callers should not rely on the return value having any specific
1828 * properties like uniqueness for security purposes. Even if the name
1829 * of the machine is changed while an application is running, the
1830 * return value from this function does not change. The returned
1831 * string is owned by GLib and should not be modified or freed. If no
1832 * name can be determined, a default fixed string "localhost" is
1835 * Returns: the host name of the machine.
1840 g_get_host_name (void)
1842 g_get_any_init_locked ();
1846 G_LOCK_DEFINE_STATIC (g_prgname);
1847 static gchar *g_prgname = NULL;
1852 * Gets the name of the program. This name should <emphasis>not</emphasis>
1853 * be localized, contrast with g_get_application_name().
1854 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1855 * which is called by gtk_init(). The program name is found by taking
1856 * the last component of <literal>argv[0]</literal>.)
1858 * Returns: the name of the program. The returned string belongs
1859 * to GLib and must not be modified or freed.
1862 g_get_prgname (void)
1868 if (g_prgname == NULL)
1870 static gboolean beenhere = FALSE;
1874 gchar *utf8_buf = NULL;
1875 wchar_t buf[MAX_PATH+1];
1878 if (GetModuleFileNameW (GetModuleHandle (NULL),
1879 buf, G_N_ELEMENTS (buf)) > 0)
1880 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1884 g_prgname = g_path_get_basename (utf8_buf);
1891 G_UNLOCK (g_prgname);
1898 * @prgname: the name of the program.
1900 * Sets the name of the program. This name should <emphasis>not</emphasis>
1901 * be localized, contrast with g_set_application_name(). Note that for
1902 * thread-safety reasons this function can only be called once.
1905 g_set_prgname (const gchar *prgname)
1909 g_prgname = g_strdup (prgname);
1910 G_UNLOCK (g_prgname);
1913 G_LOCK_DEFINE_STATIC (g_application_name);
1914 static gchar *g_application_name = NULL;
1917 * g_get_application_name:
1919 * Gets a human-readable name for the application, as set by
1920 * g_set_application_name(). This name should be localized if
1921 * possible, and is intended for display to the user. Contrast with
1922 * g_get_prgname(), which gets a non-localized name. If
1923 * g_set_application_name() has not been called, returns the result of
1924 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1927 * Return value: human-readable application name. may return %NULL
1931 G_CONST_RETURN gchar*
1932 g_get_application_name (void)
1936 G_LOCK (g_application_name);
1937 retval = g_application_name;
1938 G_UNLOCK (g_application_name);
1941 return g_get_prgname ();
1947 * g_set_application_name:
1948 * @application_name: localized name of the application
1950 * Sets a human-readable name for the application. This name should be
1951 * localized if possible, and is intended for display to the user.
1952 * Contrast with g_set_prgname(), which sets a non-localized name.
1953 * g_set_prgname() will be called automatically by gtk_init(),
1954 * but g_set_application_name() will not.
1956 * Note that for thread safety reasons, this function can only
1959 * The application name will be used in contexts such as error messages,
1960 * or when displaying an application's name in the task list.
1965 g_set_application_name (const gchar *application_name)
1967 gboolean already_set = FALSE;
1969 G_LOCK (g_application_name);
1970 if (g_application_name)
1973 g_application_name = g_strdup (application_name);
1974 G_UNLOCK (g_application_name);
1977 g_warning ("g_set_application() name called multiple times");
1981 * g_get_user_data_dir:
1983 * Returns a base directory in which to access application data such
1984 * as icons that is customized for a particular user.
1986 * On UNIX platforms this is determined using the mechanisms described in
1987 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1988 * XDG Base Directory Specification</ulink>
1990 * Return value: a string owned by GLib that must not be modified
1994 G_CONST_RETURN gchar*
1995 g_get_user_data_dir (void)
1999 G_LOCK (g_utils_global);
2001 if (!g_user_data_dir)
2004 data_dir = get_special_folder (CSIDL_PERSONAL);
2006 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2008 if (data_dir && data_dir[0])
2009 data_dir = g_strdup (data_dir);
2011 if (!data_dir || !data_dir[0])
2016 data_dir = g_build_filename (g_home_dir, ".local",
2019 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2023 g_user_data_dir = data_dir;
2026 data_dir = g_user_data_dir;
2028 G_UNLOCK (g_utils_global);
2034 g_init_user_config_dir (void)
2038 if (!g_user_config_dir)
2041 config_dir = get_special_folder (CSIDL_APPDATA);
2043 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2045 if (config_dir && config_dir[0])
2046 config_dir = g_strdup (config_dir);
2048 if (!config_dir || !config_dir[0])
2053 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2055 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2058 g_user_config_dir = config_dir;
2063 * g_get_user_config_dir:
2065 * Returns a base directory in which to store user-specific application
2066 * configuration information such as user preferences and settings.
2068 * On UNIX platforms this is determined using the mechanisms described in
2069 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2070 * XDG Base Directory Specification</ulink>
2072 * Return value: a string owned by GLib that must not be modified
2076 G_CONST_RETURN gchar*
2077 g_get_user_config_dir (void)
2079 G_LOCK (g_utils_global);
2081 g_init_user_config_dir ();
2083 G_UNLOCK (g_utils_global);
2085 return g_user_config_dir;
2089 * g_get_user_cache_dir:
2091 * Returns a base directory in which to store non-essential, cached
2092 * data specific to particular user.
2094 * On UNIX platforms this is determined using the mechanisms described in
2095 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2096 * XDG Base Directory Specification</ulink>
2098 * Return value: a string owned by GLib that must not be modified
2102 G_CONST_RETURN gchar*
2103 g_get_user_cache_dir (void)
2107 G_LOCK (g_utils_global);
2109 if (!g_user_cache_dir)
2112 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2114 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2116 if (cache_dir && cache_dir[0])
2117 cache_dir = g_strdup (cache_dir);
2119 if (!cache_dir || !cache_dir[0])
2124 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2126 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2128 g_user_cache_dir = cache_dir;
2131 cache_dir = g_user_cache_dir;
2133 G_UNLOCK (g_utils_global);
2141 find_folder (OSType type)
2143 gchar *filename = NULL;
2146 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2148 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2152 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2156 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2160 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2162 CFStringGetCString (path, filename,
2163 CFStringGetLength (path) * 3 + 1,
2164 kCFStringEncodingUTF8);
2178 load_user_special_dirs (void)
2180 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2181 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2182 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2183 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2184 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2185 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2186 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2187 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2190 #endif /* HAVE_CARBON */
2192 #if defined(G_OS_WIN32)
2194 load_user_special_dirs (void)
2196 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2197 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2198 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY); /* XXX correct ? */
2199 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2200 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2201 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS); /* XXX correct ? */
2202 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2203 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2205 #endif /* G_OS_WIN32 */
2207 static void g_init_user_config_dir (void);
2209 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2211 /* adapted from xdg-user-dir-lookup.c
2213 * Copyright (C) 2007 Red Hat Inc.
2215 * Permission is hereby granted, free of charge, to any person
2216 * obtaining a copy of this software and associated documentation files
2217 * (the "Software"), to deal in the Software without restriction,
2218 * including without limitation the rights to use, copy, modify, merge,
2219 * publish, distribute, sublicense, and/or sell copies of the Software,
2220 * and to permit persons to whom the Software is furnished to do so,
2221 * subject to the following conditions:
2223 * The above copyright notice and this permission notice shall be
2224 * included in all copies or substantial portions of the Software.
2226 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2227 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2228 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2229 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2230 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2231 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2232 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2236 load_user_special_dirs (void)
2243 g_init_user_config_dir ();
2244 config_file = g_build_filename (g_user_config_dir,
2248 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2250 g_free (config_file);
2254 lines = g_strsplit (data, "\n", -1);
2255 n_lines = g_strv_length (lines);
2258 for (i = 0; i < n_lines; i++)
2260 gchar *buffer = lines[i];
2263 gboolean is_relative = FALSE;
2264 GUserDirectory directory;
2266 /* Remove newline at end */
2267 len = strlen (buffer);
2268 if (len > 0 && buffer[len - 1] == '\n')
2269 buffer[len - 1] = 0;
2272 while (*p == ' ' || *p == '\t')
2275 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2277 directory = G_USER_DIRECTORY_DESKTOP;
2278 p += strlen ("XDG_DESKTOP_DIR");
2280 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2282 directory = G_USER_DIRECTORY_DOCUMENTS;
2283 p += strlen ("XDG_DOCUMENTS_DIR");
2285 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2287 directory = G_USER_DIRECTORY_DOWNLOAD;
2288 p += strlen ("XDG_DOWNLOAD_DIR");
2290 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2292 directory = G_USER_DIRECTORY_MUSIC;
2293 p += strlen ("XDG_MUSIC_DIR");
2295 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2297 directory = G_USER_DIRECTORY_PICTURES;
2298 p += strlen ("XDG_PICTURES_DIR");
2300 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2302 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2303 p += strlen ("XDG_PUBLICSHARE_DIR");
2305 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2307 directory = G_USER_DIRECTORY_TEMPLATES;
2308 p += strlen ("XDG_TEMPLATES_DIR");
2310 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2312 directory = G_USER_DIRECTORY_VIDEOS;
2313 p += strlen ("XDG_VIDEOS_DIR");
2318 while (*p == ' ' || *p == '\t')
2325 while (*p == ' ' || *p == '\t')
2332 if (strncmp (p, "$HOME", 5) == 0)
2340 d = strrchr (p, '"');
2347 /* remove trailing slashes */
2349 if (d[len - 1] == '/')
2355 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2358 g_user_special_dirs[directory] = g_strdup (d);
2362 g_free (config_file);
2365 #endif /* G_OS_UNIX && !HAVE_CARBON */
2368 * g_get_user_special_dir:
2369 * @directory: the logical id of special directory
2371 * Returns the full path of a special directory using its logical id.
2373 * On Unix this is done using the XDG special user directories.
2375 * Depending on the platform, the user might be able to change the path
2376 * of the special directory without requiring the session to restart; GLib
2377 * will not reflect any change once the special directories are loaded.
2379 * Return value: the path to the specified special directory, or %NULL
2380 * if the logical id was not found. The returned string is owned by
2381 * GLib and should not be modified or freed.
2385 G_CONST_RETURN gchar *
2386 g_get_user_special_dir (GUserDirectory directory)
2388 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2389 directory < G_USER_N_DIRECTORIES, NULL);
2391 G_LOCK (g_utils_global);
2393 if (G_UNLIKELY (g_user_special_dirs == NULL))
2395 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2397 load_user_special_dirs ();
2399 /* Special-case desktop for historical compatibility */
2400 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2404 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2405 g_build_filename (g_home_dir, "Desktop", NULL);
2409 G_UNLOCK (g_utils_global);
2411 return g_user_special_dirs[directory];
2416 #undef g_get_system_data_dirs
2419 get_module_for_address (gconstpointer address)
2421 /* Holds the g_utils_global lock */
2423 static gboolean beenhere = FALSE;
2424 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2425 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2433 p_GetModuleHandleExA =
2434 (t_GetModuleHandleExA) GetProcAddress (LoadLibrary ("kernel32.dll"),
2435 "GetModuleHandleExA");
2439 if (p_GetModuleHandleExA == NULL ||
2440 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2441 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2444 MEMORY_BASIC_INFORMATION mbi;
2445 VirtualQuery (address, &mbi, sizeof (mbi));
2446 hmodule = (HMODULE) mbi.AllocationBase;
2453 get_module_share_dir (gconstpointer address)
2456 gchar *filename = NULL;
2458 wchar_t wfilename[MAX_PATH];
2460 hmodule = get_module_for_address (address);
2461 if (hmodule == NULL)
2464 if (GetModuleFileNameW (hmodule, wfilename, G_N_ELEMENTS (wfilename)))
2465 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
2467 if (filename == NULL)
2470 if ((p = strrchr (filename, G_DIR_SEPARATOR)) != NULL)
2473 p = strrchr (filename, G_DIR_SEPARATOR);
2474 if (p && (g_ascii_strcasecmp (p + 1, "bin") == 0))
2477 retval = g_build_filename (filename, "share", NULL);
2483 G_CONST_RETURN gchar * G_CONST_RETURN *
2484 g_win32_get_system_data_dirs_for_module (gconstpointer address)
2488 static GHashTable *per_module_data_dirs = NULL;
2494 G_LOCK (g_utils_global);
2495 hmodule = get_module_for_address (address);
2496 if (hmodule != NULL)
2498 if (per_module_data_dirs == NULL)
2499 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2502 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2506 G_UNLOCK (g_utils_global);
2507 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2513 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2515 /* Documents and Settings\All Users\Application Data */
2516 p = get_special_folder (CSIDL_COMMON_APPDATA);
2518 g_array_append_val (data_dirs, p);
2520 /* Documents and Settings\All Users\Documents */
2521 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2523 g_array_append_val (data_dirs, p);
2525 /* Using the above subfolders of Documents and Settings perhaps
2526 * makes sense from a Windows perspective.
2528 * But looking at the actual use cases of this function in GTK+
2529 * and GNOME software, what we really want is the "share"
2530 * subdirectory of the installation directory for the package
2531 * our caller is a part of.
2533 * The address parameter, if non-NULL, points to a function in the
2534 * calling module. Use that to determine that module's installation
2535 * folder, and use its "share" subfolder.
2537 * Additionally, also use the "share" subfolder of the installation
2538 * locations of GLib and the .exe file being run.
2540 * To guard against none of the above being what is really wanted,
2541 * callers of this function should have Win32-specific code to look
2542 * up their installation folder themselves, and handle a subfolder
2543 * "share" of it in the same way as the folders returned from this
2547 p = get_module_share_dir (address);
2549 g_array_append_val (data_dirs, p);
2551 p = g_win32_get_package_installation_subdirectory (NULL, dll_name, "share");
2553 g_array_append_val (data_dirs, p);
2555 p = g_win32_get_package_installation_subdirectory (NULL, NULL, "share");
2557 g_array_append_val (data_dirs, p);
2559 retval = (gchar **) g_array_free (data_dirs, FALSE);
2563 if (hmodule != NULL)
2564 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2565 G_UNLOCK (g_utils_global);
2568 return (G_CONST_RETURN gchar * G_CONST_RETURN *) retval;
2574 * g_get_system_data_dirs:
2576 * Returns an ordered list of base directories in which to access
2577 * system-wide application data.
2579 * On UNIX platforms this is determined using the mechanisms described in
2580 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2581 * XDG Base Directory Specification</ulink>
2583 * On Windows the first elements in the list are the Application Data
2584 * and Documents folders for All Users. (These can be determined only
2585 * on Windows 2000 or later and are not present in the list on other
2586 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2587 * CSIDL_COMMON_DOCUMENTS.
2589 * Then follows the "share" subfolder in the installation folder for
2590 * the package containing the DLL that calls this function, if it can
2593 * Finally the list contains the "share" subfolder in the installation
2594 * folder for GLib, and in the installation folder for the package the
2595 * application's .exe file belongs to.
2597 * The installation folders above are determined by looking up the
2598 * folder where the module (DLL or EXE) in question is located. If the
2599 * folder's name is "bin", its parent is used, otherwise the folder
2602 * Note that on Windows the returned list can vary depending on where
2603 * this function is called.
2605 * Return value: a %NULL-terminated array of strings owned by GLib that must
2606 * not be modified or freed.
2609 G_CONST_RETURN gchar * G_CONST_RETURN *
2610 g_get_system_data_dirs (void)
2612 gchar **data_dir_vector;
2614 G_LOCK (g_utils_global);
2616 if (!g_system_data_dirs)
2619 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2621 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2623 if (!data_dirs || !data_dirs[0])
2624 data_dirs = "/usr/local/share/:/usr/share/";
2626 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2629 g_system_data_dirs = data_dir_vector;
2632 data_dir_vector = g_system_data_dirs;
2634 G_UNLOCK (g_utils_global);
2636 return (G_CONST_RETURN gchar * G_CONST_RETURN *) data_dir_vector;
2640 * g_get_system_config_dirs:
2642 * Returns an ordered list of base directories in which to access
2643 * system-wide configuration information.
2645 * On UNIX platforms this is determined using the mechanisms described in
2646 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2647 * XDG Base Directory Specification</ulink>
2649 * Return value: a %NULL-terminated array of strings owned by GLib that must
2650 * not be modified or freed.
2653 G_CONST_RETURN gchar * G_CONST_RETURN *
2654 g_get_system_config_dirs (void)
2656 gchar *conf_dirs, **conf_dir_vector;
2658 G_LOCK (g_utils_global);
2660 if (!g_system_config_dirs)
2663 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2666 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2671 /* Return empty list */
2672 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2675 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2677 if (!conf_dirs || !conf_dirs[0])
2678 conf_dirs = "/etc/xdg";
2680 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2683 g_system_config_dirs = conf_dir_vector;
2686 conf_dir_vector = g_system_config_dirs;
2687 G_UNLOCK (g_utils_global);
2689 return (G_CONST_RETURN gchar * G_CONST_RETURN *) conf_dir_vector;
2694 static GHashTable *alias_table = NULL;
2696 /* read an alias file for the locales */
2698 read_aliases (gchar *file)
2704 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2705 fp = fopen (file,"r");
2708 while (fgets (buf, 256, fp))
2714 /* Line is a comment */
2715 if ((buf[0] == '#') || (buf[0] == '\0'))
2718 /* Reads first column */
2719 for (p = buf, q = NULL; *p; p++) {
2720 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2723 while ((*q == '\t') || (*q == ' ')) {
2729 /* The line only had one column */
2730 if (!q || *q == '\0')
2733 /* Read second column */
2734 for (p = q; *p; p++) {
2735 if ((*p == '\t') || (*p == ' ')) {
2741 /* Add to alias table if necessary */
2742 if (!g_hash_table_lookup (alias_table, buf)) {
2743 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2752 unalias_lang (char *lang)
2759 read_aliases ("/usr/share/locale/locale.alias");
2762 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2767 static gboolean said_before = FALSE;
2769 g_warning ("Too many alias levels for a locale, "
2770 "may indicate a loop");
2779 /* Mask for components of locale spec. The ordering here is from
2780 * least significant to most significant
2784 COMPONENT_CODESET = 1 << 0,
2785 COMPONENT_TERRITORY = 1 << 1,
2786 COMPONENT_MODIFIER = 1 << 2
2789 /* Break an X/Open style locale specification into components
2792 explode_locale (const gchar *locale,
2798 const gchar *uscore_pos;
2799 const gchar *at_pos;
2800 const gchar *dot_pos;
2804 uscore_pos = strchr (locale, '_');
2805 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2806 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2810 mask |= COMPONENT_MODIFIER;
2811 *modifier = g_strdup (at_pos);
2814 at_pos = locale + strlen (locale);
2818 mask |= COMPONENT_CODESET;
2819 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2826 mask |= COMPONENT_TERRITORY;
2827 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2830 uscore_pos = dot_pos;
2832 *language = g_strndup (locale, uscore_pos - locale);
2838 * Compute all interesting variants for a given locale name -
2839 * by stripping off different components of the value.
2841 * For simplicity, we assume that the locale is in
2842 * X/Open format: language[_territory][.codeset][@modifier]
2844 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2845 * as well. We could just copy the code from glibc wholesale
2846 * but it is big, ugly, and complicated, so I'm reluctant
2847 * to do so when this should handle 99% of the time...
2850 _g_compute_locale_variants (const gchar *locale)
2852 GSList *retval = NULL;
2854 gchar *language = NULL;
2855 gchar *territory = NULL;
2856 gchar *codeset = NULL;
2857 gchar *modifier = NULL;
2862 g_return_val_if_fail (locale != NULL, NULL);
2864 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2866 /* Iterate through all possible combinations, from least attractive
2867 * to most attractive.
2869 for (i = 0; i <= mask; i++)
2870 if ((i & ~mask) == 0)
2872 gchar *val = g_strconcat (language,
2873 (i & COMPONENT_TERRITORY) ? territory : "",
2874 (i & COMPONENT_CODESET) ? codeset : "",
2875 (i & COMPONENT_MODIFIER) ? modifier : "",
2877 retval = g_slist_prepend (retval, val);
2881 if (mask & COMPONENT_CODESET)
2883 if (mask & COMPONENT_TERRITORY)
2885 if (mask & COMPONENT_MODIFIER)
2891 /* The following is (partly) taken from the gettext package.
2892 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2894 static const gchar *
2895 guess_category_value (const gchar *category_name)
2897 const gchar *retval;
2899 /* The highest priority value is the `LANGUAGE' environment
2900 variable. This is a GNU extension. */
2901 retval = g_getenv ("LANGUAGE");
2902 if ((retval != NULL) && (retval[0] != '\0'))
2905 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2906 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2907 systems this can be done by the `setlocale' function itself. */
2909 /* Setting of LC_ALL overwrites all other. */
2910 retval = g_getenv ("LC_ALL");
2911 if ((retval != NULL) && (retval[0] != '\0'))
2914 /* Next comes the name of the desired category. */
2915 retval = g_getenv (category_name);
2916 if ((retval != NULL) && (retval[0] != '\0'))
2919 /* Last possibility is the LANG environment variable. */
2920 retval = g_getenv ("LANG");
2921 if ((retval != NULL) && (retval[0] != '\0'))
2924 #ifdef G_PLATFORM_WIN32
2925 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2926 * LANG, which we already did above. Oh well. The main point of
2927 * calling g_win32_getlocale() is to get the thread's locale as used
2928 * by Windows and the Microsoft C runtime (in the "English_United
2929 * States" format) translated into the Unixish format.
2931 retval = g_win32_getlocale ();
2932 if ((retval != NULL) && (retval[0] != '\0'))
2939 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2941 struct _GLanguageNamesCache {
2943 gchar **language_names;
2947 language_names_cache_free (gpointer data)
2949 GLanguageNamesCache *cache = data;
2950 g_free (cache->languages);
2951 g_strfreev (cache->language_names);
2956 * g_get_language_names:
2958 * Computes a list of applicable locale names, which can be used to
2959 * e.g. construct locale-dependent filenames or search paths. The returned
2960 * list is sorted from most desirable to least desirable and always contains
2961 * the default locale "C".
2963 * For example, if LANGUAGE=de:en_US, then the returned list is
2964 * "de", "en_US", "en", "C".
2966 * This function consults the environment variables <envar>LANGUAGE</envar>,
2967 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2968 * to find the list of locales specified by the user.
2970 * Return value: a %NULL-terminated array of strings owned by GLib
2971 * that must not be modified or freed.
2975 G_CONST_RETURN gchar * G_CONST_RETURN *
2976 g_get_language_names (void)
2978 static GStaticPrivate cache_private = G_STATIC_PRIVATE_INIT;
2979 GLanguageNamesCache *cache = g_static_private_get (&cache_private);
2984 cache = g_new0 (GLanguageNamesCache, 1);
2985 g_static_private_set (&cache_private, cache, language_names_cache_free);
2988 value = guess_category_value ("LC_MESSAGES");
2992 if (!(cache->languages && strcmp (cache->languages, value) == 0))
2999 g_free (cache->languages);
3000 g_strfreev (cache->language_names);
3001 cache->languages = g_strdup (value);
3003 alist = g_strsplit (value, ":", 0);
3005 for (a = alist; *a; a++)
3007 gchar *b = unalias_lang (*a);
3008 list = g_slist_concat (list, _g_compute_locale_variants (b));
3011 list = g_slist_append (list, g_strdup ("C"));
3013 cache->language_names = languages = g_new (gchar *, g_slist_length (list) + 1);
3014 for (l = list, i = 0; l; l = l->next, i++)
3015 languages[i] = l->data;
3016 languages[i] = NULL;
3018 g_slist_free (list);
3021 return (G_CONST_RETURN gchar * G_CONST_RETURN *) cache->language_names;
3026 * @v: a #gpointer key
3028 * Converts a gpointer to a hash value.
3029 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3030 * when using pointers as keys in a #GHashTable.
3032 * Returns: a hash value corresponding to the key.
3035 g_direct_hash (gconstpointer v)
3037 return GPOINTER_TO_UINT (v);
3043 * @v2: a key to compare with @v1.
3045 * Compares two #gpointer arguments and returns %TRUE if they are equal.
3046 * It can be passed to g_hash_table_new() as the @key_equal_func
3047 * parameter, when using pointers as keys in a #GHashTable.
3049 * Returns: %TRUE if the two keys match.
3052 g_direct_equal (gconstpointer v1,
3060 * @v1: a pointer to a #gint key.
3061 * @v2: a pointer to a #gint key to compare with @v1.
3063 * Compares the two #gint values being pointed to and returns
3064 * %TRUE if they are equal.
3065 * It can be passed to g_hash_table_new() as the @key_equal_func
3066 * parameter, when using pointers to integers as keys in a #GHashTable.
3068 * Returns: %TRUE if the two keys match.
3071 g_int_equal (gconstpointer v1,
3074 return *((const gint*) v1) == *((const gint*) v2);
3079 * @v: a pointer to a #gint key
3081 * Converts a pointer to a #gint to a hash value.
3082 * It can be passed to g_hash_table_new() as the @hash_func parameter,
3083 * when using pointers to integers values as keys in a #GHashTable.
3085 * Returns: a hash value corresponding to the key.
3088 g_int_hash (gconstpointer v)
3090 return *(const gint*) v;
3094 * g_nullify_pointer:
3095 * @nullify_location: the memory address of the pointer.
3097 * Set the pointer at the specified location to %NULL.
3100 g_nullify_pointer (gpointer *nullify_location)
3102 g_return_if_fail (nullify_location != NULL);
3104 *nullify_location = NULL;
3110 * Get the codeset for the current locale.
3112 * Return value: a newly allocated string containing the name
3113 * of the codeset. This string must be freed with g_free().
3116 g_get_codeset (void)
3118 const gchar *charset;
3120 g_get_charset (&charset);
3122 return g_strdup (charset);
3125 /* This is called from g_thread_init(). It's used to
3126 * initialize some static data in a threadsafe way.
3129 _g_utils_thread_init (void)
3131 g_get_language_names ();
3137 * _glib_get_locale_dir:
3139 * Return the path to the share\locale or lib\locale subfolder of the
3140 * GLib installation folder. The path is in the system codepage. We
3141 * have to use system codepage as bindtextdomain() doesn't have a
3145 _glib_get_locale_dir (void)
3147 gchar *install_dir, *locale_dir;
3148 gchar *retval = NULL;
3150 install_dir = g_win32_get_package_installation_directory (GETTEXT_PACKAGE, dll_name);
3155 * Append "/share/locale" or "/lib/locale" depending on whether
3156 * autoconfigury detected GNU gettext or not.
3158 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3164 locale_dir = g_build_filename (install_dir, p, NULL);
3166 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3168 g_free (install_dir);
3169 g_free (locale_dir);
3175 return g_strdup ("");
3178 #undef GLIB_LOCALE_DIR
3180 #endif /* G_OS_WIN32 */
3184 * str: The string to be translated
3186 * Returns the translated string from the glib translations.
3187 * This is an internal function and should only be used by
3188 * the internals of glib (such as libgio).
3190 G_CONST_RETURN gchar *
3191 glib_gettext (const gchar *str)
3193 static gboolean _glib_gettext_initialized = FALSE;
3195 if (!_glib_gettext_initialized)
3198 gchar *tmp = _glib_get_locale_dir ();
3199 bindtextdomain (GETTEXT_PACKAGE, tmp);
3202 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3204 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3205 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3207 _glib_gettext_initialized = TRUE;
3210 return dgettext (GETTEXT_PACKAGE, str);
3215 /* Binary compatibility versions. Not for newly compiled code. */
3217 #undef g_find_program_in_path
3220 g_find_program_in_path (const gchar *program)
3222 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3223 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3226 g_free (utf8_program);
3227 if (utf8_retval == NULL)
3229 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3230 g_free (utf8_retval);
3235 #undef g_get_current_dir
3238 g_get_current_dir (void)
3240 gchar *utf8_dir = g_get_current_dir_utf8 ();
3241 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3248 G_CONST_RETURN gchar*
3249 g_getenv (const gchar *variable)
3251 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3252 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3256 g_free (utf8_variable);
3259 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3260 quark = g_quark_from_string (value);
3263 return g_quark_to_string (quark);
3269 g_setenv (const gchar *variable,
3273 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3274 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3275 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3277 g_free (utf8_variable);
3278 g_free (utf8_value);
3286 g_unsetenv (const gchar *variable)
3288 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3290 g_unsetenv_utf8 (utf8_variable);
3292 g_free (utf8_variable);
3295 #undef g_get_user_name
3297 G_CONST_RETURN gchar*
3298 g_get_user_name (void)
3300 g_get_any_init_locked ();
3301 return g_user_name_cp;
3304 #undef g_get_real_name
3306 G_CONST_RETURN gchar*
3307 g_get_real_name (void)
3309 g_get_any_init_locked ();
3310 return g_real_name_cp;
3313 #undef g_get_home_dir
3315 G_CONST_RETURN gchar*
3316 g_get_home_dir (void)
3318 g_get_any_init_locked ();
3319 return g_home_dir_cp;
3322 #undef g_get_tmp_dir
3324 G_CONST_RETURN gchar*
3325 g_get_tmp_dir (void)
3327 g_get_any_init_locked ();
3328 return g_tmp_dir_cp;
3333 #define __G_UTILS_C__
3334 #include "galiasdef.c"