1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
33 * @Title: Version Information
34 * @Short_description: Variables and functions to check the GLib version
36 * GLib provides version information, primarily useful in configure
37 * checks for builds that have a configure script. Applications will
38 * not typically use the features described here.
44 * The major version number of the GLib library.
46 * Like #glib_major_version, but from the headers used at
47 * application compile time, rather than from the library
48 * linked against at application run time.
54 * The minor version number of the GLib library.
56 * Like #gtk_minor_version, but from the headers used at
57 * application compile time, rather than from the library
58 * linked against at application run time.
64 * The micro version number of the GLib library.
66 * Like #gtk_micro_version, but from the headers used at
67 * application compile time, rather than from the library
68 * linked against at application run time.
81 #include <ctype.h> /* For tolower() */
83 #include <sys/types.h>
88 #include <sys/types.h>
89 #ifdef HAVE_SYS_PARAM_H
90 #include <sys/param.h>
92 #ifdef HAVE_CRT_EXTERNS_H
93 #include <crt_externs.h> /* for _NSGetEnviron */
96 /* implement gutils's inline functions
98 #define G_IMPLEMENT_INLINES 1
102 #include "glib-init.h"
103 #include "genviron.h"
104 #include "gfileutils.h"
107 #include "gprintfint.h"
109 #include "gthreadprivate.h"
110 #include "gtestutils.h"
111 #include "gunicode.h"
112 #include "gstrfuncs.h"
114 #include "glibintl.h"
116 #ifdef G_PLATFORM_WIN32
118 #include "gconvert.h"
125 * @title: Miscellaneous Utility Functions
126 * @short_description: a selection of portable utility functions
128 * These are portable utility functions.
132 #define G_PATH_LENGTH MAXPATHLEN
133 #elif defined (PATH_MAX)
134 #define G_PATH_LENGTH PATH_MAX
135 #elif defined (_PC_PATH_MAX)
136 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
138 #define G_PATH_LENGTH 2048
141 #ifdef G_PLATFORM_WIN32
142 # include <windows.h>
143 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
144 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
145 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
147 # include <lmcons.h> /* For UNLEN */
148 #endif /* G_PLATFORM_WIN32 */
153 /* older SDK (e.g. msvc 5.0) does not have these*/
154 # ifndef CSIDL_MYMUSIC
155 # define CSIDL_MYMUSIC 13
157 # ifndef CSIDL_MYVIDEO
158 # define CSIDL_MYVIDEO 14
160 # ifndef CSIDL_INTERNET_CACHE
161 # define CSIDL_INTERNET_CACHE 32
163 # ifndef CSIDL_COMMON_APPDATA
164 # define CSIDL_COMMON_APPDATA 35
166 # ifndef CSIDL_MYPICTURES
167 # define CSIDL_MYPICTURES 0x27
169 # ifndef CSIDL_COMMON_DOCUMENTS
170 # define CSIDL_COMMON_DOCUMENTS 46
172 # ifndef CSIDL_PROFILE
173 # define CSIDL_PROFILE 40
175 # include <process.h>
179 #include <CoreServices/CoreServices.h>
183 #include <langinfo.h>
186 const guint glib_major_version = GLIB_MAJOR_VERSION;
187 const guint glib_minor_version = GLIB_MINOR_VERSION;
188 const guint glib_micro_version = GLIB_MICRO_VERSION;
189 const guint glib_interface_age = GLIB_INTERFACE_AGE;
190 const guint glib_binary_age = GLIB_BINARY_AGE;
192 #ifdef G_PLATFORM_WIN32
195 _glib_get_dll_directory (void)
199 wchar_t wc_fn[MAX_PATH];
202 if (glib_dll == NULL)
206 /* This code is different from that in
207 * g_win32_get_package_installation_directory_of_module() in that
208 * here we return the actual folder where the GLib DLL is. We don't
209 * do the check for it being in a "bin" or "lib" subfolder and then
210 * returning the parent of that.
212 * In a statically built GLib, glib_dll will be NULL and we will
213 * thus look up the application's .exe file's location.
215 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
218 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
220 p = strrchr (retval, G_DIR_SEPARATOR);
234 * glib_check_version:
235 * @required_major: the required major version.
236 * @required_minor: the required minor version.
237 * @required_micro: the required micro version.
239 * Checks that the GLib library in use is compatible with the
240 * given version. Generally you would pass in the constants
241 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
242 * as the three arguments to this function; that produces
243 * a check that the library in use is compatible with
244 * the version of GLib the application or module was compiled
247 * Compatibility is defined by two things: first the version
248 * of the running library is newer than the version
249 * @required_major.required_minor.@required_micro. Second
250 * the running library must be binary compatible with the
251 * version @required_major.required_minor.@required_micro
252 * (same major version.)
254 * Return value: %NULL if the GLib library is compatible with the
255 * given version, or a string describing the version mismatch.
256 * The returned string is owned by GLib and must not be modified
262 glib_check_version (guint required_major,
263 guint required_minor,
264 guint required_micro)
266 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
267 gint required_effective_micro = 100 * required_minor + required_micro;
269 if (required_major > GLIB_MAJOR_VERSION)
270 return "GLib version too old (major mismatch)";
271 if (required_major < GLIB_MAJOR_VERSION)
272 return "GLib version too new (major mismatch)";
273 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
274 return "GLib version too new (micro mismatch)";
275 if (required_effective_micro > glib_effective_micro)
276 return "GLib version too old (micro mismatch)";
280 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
283 * @dest: the destination address to copy the bytes to.
284 * @src: the source address to copy the bytes from.
285 * @len: the number of bytes to copy.
287 * Copies a block of memory @len bytes long, from @src to @dest.
288 * The source and destination areas may overlap.
290 * In order to use this function, you must include
291 * <filename>string.h</filename> yourself, because this macro will
292 * typically simply resolve to memmove() and GLib does not include
293 * <filename>string.h</filename> for you.
296 g_memmove (gpointer dest,
300 gchar* destptr = dest;
301 const gchar* srcptr = src;
302 if (src + len < dest || dest + len < src)
304 bcopy (src, dest, len);
307 else if (dest <= src)
310 *(destptr++) = *(srcptr++);
317 *(--destptr) = *(--srcptr);
320 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
328 * @func: (scope async): the function to call on normal program termination.
330 * Specifies a function to be called at normal program termination.
332 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
333 * macro that maps to a call to the atexit() function in the C
334 * library. This means that in case the code that calls g_atexit(),
335 * i.e. atexit(), is in a DLL, the function will be called when the
336 * DLL is detached from the program. This typically makes more sense
337 * than that the function is called when the GLib DLL is detached,
338 * which happened earlier when g_atexit() was a function in the GLib
341 * The behaviour of atexit() in the context of dynamically loaded
342 * modules is not formally specified and varies wildly.
344 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
345 * loaded module which is unloaded before the program terminates might
346 * well cause a crash at program exit.
348 * Some POSIX systems implement atexit() like Windows, and have each
349 * dynamically loaded module maintain an own atexit chain that is
350 * called when the module is unloaded.
352 * On other POSIX systems, before a dynamically loaded module is
353 * unloaded, the registered atexit functions (if any) residing in that
354 * module are called, regardless where the code that registered them
355 * resided. This is presumably the most robust approach.
357 * As can be seen from the above, for portability it's best to avoid
358 * calling g_atexit() (or atexit()) except in the main executable of a
362 g_atexit (GVoidFunc func)
365 const gchar *error = NULL;
367 /* keep this in sync with glib.h */
369 #ifdef G_NATIVE_ATEXIT
370 result = ATEXIT (func);
372 error = g_strerror (errno);
373 #elif defined (HAVE_ATEXIT)
374 # ifdef NeXT /* @#%@! NeXTStep */
375 result = !atexit ((void (*)(void)) func);
377 error = g_strerror (errno);
379 result = atexit ((void (*)(void)) func);
381 error = g_strerror (errno);
383 #elif defined (HAVE_ON_EXIT)
384 result = on_exit ((void (*)(int, void *)) func, NULL);
386 error = g_strerror (errno);
389 error = "no implementation";
390 #endif /* G_NATIVE_ATEXIT */
393 g_error ("Could not register atexit() function: %s", error);
396 /* Based on execvp() from GNU Libc.
397 * Some of this code is cut-and-pasted into gspawn.c
401 my_strchrnul (const gchar *str,
404 gchar *p = (gchar*)str;
405 while (*p && (*p != c))
413 static gchar *inner_find_program_in_path (const gchar *program);
416 g_find_program_in_path (const gchar *program)
418 const gchar *last_dot = strrchr (program, '.');
420 if (last_dot == NULL ||
421 strchr (last_dot, '\\') != NULL ||
422 strchr (last_dot, '/') != NULL)
424 const gint program_length = strlen (program);
425 gchar *pathext = g_build_path (";",
426 ".exe;.cmd;.bat;.com",
427 g_getenv ("PATHEXT"),
430 gchar *decorated_program;
436 gchar *q = my_strchrnul (p, ';');
438 decorated_program = g_malloc (program_length + (q-p) + 1);
439 memcpy (decorated_program, program, program_length);
440 memcpy (decorated_program+program_length, p, q-p);
441 decorated_program [program_length + (q-p)] = '\0';
443 retval = inner_find_program_in_path (decorated_program);
444 g_free (decorated_program);
452 } while (*p++ != '\0');
457 return inner_find_program_in_path (program);
463 * g_find_program_in_path:
464 * @program: a program name in the GLib file name encoding
466 * Locates the first executable named @program in the user's path, in the
467 * same way that execvp() would locate it. Returns an allocated string
468 * with the absolute path name, or %NULL if the program is not found in
469 * the path. If @program is already an absolute path, returns a copy of
470 * @program if @program exists and is executable, and %NULL otherwise.
472 * On Windows, if @program does not have a file type suffix, tries
473 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
474 * the <envar>PATHEXT</envar> environment variable.
476 * On Windows, it looks for the file in the same way as CreateProcess()
477 * would. This means first in the directory where the executing
478 * program was loaded from, then in the current directory, then in the
479 * Windows 32-bit system directory, then in the Windows directory, and
480 * finally in the directories in the <envar>PATH</envar> environment
481 * variable. If the program is found, the return value contains the
482 * full name including the type suffix.
484 * Return value: absolute path, or %NULL
488 inner_find_program_in_path (const gchar *program)
491 g_find_program_in_path (const gchar *program)
494 const gchar *path, *p;
495 gchar *name, *freeme;
497 const gchar *path_copy;
498 gchar *filename = NULL, *appdir = NULL;
499 gchar *sysdir = NULL, *windir = NULL;
501 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
507 g_return_val_if_fail (program != NULL, NULL);
509 /* If it is an absolute path, or a relative path including subdirectories,
510 * don't look in PATH.
512 if (g_path_is_absolute (program)
513 || strchr (program, G_DIR_SEPARATOR) != NULL
515 || strchr (program, '/') != NULL
519 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
520 !g_file_test (program, G_FILE_TEST_IS_DIR))
521 return g_strdup (program);
526 path = g_getenv ("PATH");
527 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
530 /* There is no `PATH' in the environment. The default
531 * search path in GNU libc is the current directory followed by
532 * the path `confstr' returns for `_CS_PATH'.
535 /* In GLib we put . last, for security, and don't use the
536 * unportable confstr(); UNIX98 does not actually specify
537 * what to search if PATH is unset. POSIX may, dunno.
540 path = "/bin:/usr/bin:.";
543 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
544 if (n > 0 && n < MAXPATHLEN)
545 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
547 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
548 if (n > 0 && n < MAXPATHLEN)
549 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
551 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
552 if (n > 0 && n < MAXPATHLEN)
553 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
557 appdir = g_path_get_dirname (filename);
561 path = g_strdup (path);
565 const gchar *tem = path;
566 path = g_strconcat (windir, ";", path, NULL);
567 g_free ((gchar *) tem);
573 const gchar *tem = path;
574 path = g_strconcat (sysdir, ";", path, NULL);
575 g_free ((gchar *) tem);
580 const gchar *tem = path;
581 path = g_strconcat (".;", path, NULL);
582 g_free ((gchar *) tem);
587 const gchar *tem = path;
588 path = g_strconcat (appdir, ";", path, NULL);
589 g_free ((gchar *) tem);
596 len = strlen (program) + 1;
597 pathlen = strlen (path);
598 freeme = name = g_malloc (pathlen + len + 1);
600 /* Copy the file name at the top, including '\0' */
601 memcpy (name + pathlen + 1, program, len);
602 name = name + pathlen;
603 /* And add the slash before the filename */
604 *name = G_DIR_SEPARATOR;
612 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
615 /* Two adjacent colons, or a colon at the beginning or the end
616 * of `PATH' means to search the current directory.
620 startp = memcpy (name - (p - path), path, p - path);
622 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
623 !g_file_test (startp, G_FILE_TEST_IS_DIR))
626 ret = g_strdup (startp);
629 g_free ((gchar *) path_copy);
634 while (*p++ != '\0');
638 g_free ((gchar *) path_copy);
646 * @file_name: the name of the file.
648 * Gets the name of the file without any leading directory components.
649 * It returns a pointer into the given file name string.
651 * Return value: the name of the file without any leading directory components.
653 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
654 * g_path_get_basename() allocates new memory for the returned string, unlike
655 * this function which returns a pointer into the argument.
658 g_basename (const gchar *file_name)
660 register gchar *base;
662 g_return_val_if_fail (file_name != NULL, NULL);
664 base = strrchr (file_name, G_DIR_SEPARATOR);
668 gchar *q = strrchr (file_name, '/');
669 if (base == NULL || (q != NULL && q > base))
678 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
679 return (gchar*) file_name + 2;
680 #endif /* G_OS_WIN32 */
682 return (gchar*) file_name;
686 * g_path_get_basename:
687 * @file_name: the name of the file.
689 * Gets the last component of the filename. If @file_name ends with a
690 * directory separator it gets the component before the last slash. If
691 * @file_name consists only of directory separators (and on Windows,
692 * possibly a drive letter), a single separator is returned. If
693 * @file_name is empty, it gets ".".
695 * Return value: a newly allocated string containing the last component of
699 g_path_get_basename (const gchar *file_name)
701 register gssize base;
702 register gssize last_nonslash;
706 g_return_val_if_fail (file_name != NULL, NULL);
708 if (file_name[0] == '\0')
710 return g_strdup (".");
712 last_nonslash = strlen (file_name) - 1;
714 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
717 if (last_nonslash == -1)
718 /* string only containing slashes */
719 return g_strdup (G_DIR_SEPARATOR_S);
722 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
723 /* string only containing slashes and a drive */
724 return g_strdup (G_DIR_SEPARATOR_S);
725 #endif /* G_OS_WIN32 */
727 base = last_nonslash;
729 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
733 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
735 #endif /* G_OS_WIN32 */
737 len = last_nonslash - base;
738 retval = g_malloc (len + 1);
739 memcpy (retval, file_name + base + 1, len);
745 * g_path_is_absolute:
746 * @file_name: a file name.
748 * Returns %TRUE if the given @file_name is an absolute file name.
749 * Note that this is a somewhat vague concept on Windows.
751 * On POSIX systems, an absolute file name is well-defined. It always
752 * starts from the single root directory. For example "/usr/local".
754 * On Windows, the concepts of current drive and drive-specific
755 * current directory introduce vagueness. This function interprets as
756 * an absolute file name one that either begins with a directory
757 * separator such as "\Users\tml" or begins with the root on a drive,
758 * for example "C:\Windows". The first case also includes UNC paths
759 * such as "\\myserver\docs\foo". In all cases, either slashes or
760 * backslashes are accepted.
762 * Note that a file name relative to the current drive root does not
763 * truly specify a file uniquely over time and across processes, as
764 * the current drive is a per-process value and can be changed.
766 * File names relative the current directory on some specific drive,
767 * such as "D:foo/bar", are not interpreted as absolute by this
768 * function, but they obviously are not relative to the normal current
769 * directory as returned by getcwd() or g_get_current_dir()
770 * either. Such paths should be avoided, or need to be handled using
771 * Windows-specific code.
773 * Returns: %TRUE if @file_name is absolute.
776 g_path_is_absolute (const gchar *file_name)
778 g_return_val_if_fail (file_name != NULL, FALSE);
780 if (G_IS_DIR_SEPARATOR (file_name[0]))
784 /* Recognize drive letter on native Windows */
785 if (g_ascii_isalpha (file_name[0]) &&
786 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
788 #endif /* G_OS_WIN32 */
795 * @file_name: a file name.
797 * Returns a pointer into @file_name after the root component, i.e. after
798 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
799 * path it returns %NULL.
801 * Returns: a pointer into @file_name after the root component.
804 g_path_skip_root (const gchar *file_name)
806 g_return_val_if_fail (file_name != NULL, NULL);
808 #ifdef G_PLATFORM_WIN32
809 /* Skip \\server\share or //server/share */
810 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
811 G_IS_DIR_SEPARATOR (file_name[1]) &&
813 !G_IS_DIR_SEPARATOR (file_name[2]))
817 p = strchr (file_name + 2, G_DIR_SEPARATOR);
820 gchar *q = strchr (file_name + 2, '/');
821 if (p == NULL || (q != NULL && q < p))
831 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
834 /* Possibly skip a backslash after the share name */
835 if (G_IS_DIR_SEPARATOR (file_name[0]))
838 return (gchar *)file_name;
843 /* Skip initial slashes */
844 if (G_IS_DIR_SEPARATOR (file_name[0]))
846 while (G_IS_DIR_SEPARATOR (file_name[0]))
848 return (gchar *)file_name;
853 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
854 return (gchar *)file_name + 3;
862 * @mask: a #gulong containing flags
863 * @nth_bit: the index of the bit to start the search from
865 * Find the position of the first bit set in @mask, searching
866 * from (but not including) @nth_bit upwards. Bits are numbered
867 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
868 * usually). To start searching from the 0th bit, set @nth_bit to -1.
870 * Returns: the index of the first bit set which is higher than @nth_bit
875 * @mask: a #gulong containing flags
876 * @nth_bit: the index of the bit to start the search from
878 * Find the position of the first bit set in @mask, searching
879 * from (but not including) @nth_bit downwards. Bits are numbered
880 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
881 * usually). To start searching from the last bit, set @nth_bit to
882 * -1 or GLIB_SIZEOF_LONG * 8.
884 * Returns: the index of the first bit set which is lower than @nth_bit
891 * Gets the number of bits used to hold @number,
892 * e.g. if @number is 4, 3 bits are needed.
894 * Returns: the number of bits used to hold @number
899 * @file_name: the name of the file
901 * Gets the directory components of a file name.
902 * If the file name has no directory components "." is returned.
903 * The returned string should be freed when no longer needed.
905 * Returns: the directory components of the file
907 * Deprecated: use g_path_get_dirname() instead
911 * g_path_get_dirname:
912 * @file_name: the name of the file.
914 * Gets the directory components of a file name. If the file name has no
915 * directory components "." is returned. The returned string should be
916 * freed when no longer needed.
918 * Returns: the directory components of the file.
921 g_path_get_dirname (const gchar *file_name)
923 register gchar *base;
926 g_return_val_if_fail (file_name != NULL, NULL);
928 base = strrchr (file_name, G_DIR_SEPARATOR);
931 gchar *q = strrchr (file_name, '/');
932 if (base == NULL || (q != NULL && q > base))
939 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
941 gchar drive_colon_dot[4];
943 drive_colon_dot[0] = file_name[0];
944 drive_colon_dot[1] = ':';
945 drive_colon_dot[2] = '.';
946 drive_colon_dot[3] = '\0';
948 return g_strdup (drive_colon_dot);
951 return g_strdup (".");
954 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
958 /* base points to the char before the last slash.
960 * In case file_name is the root of a drive (X:\) or a child of the
961 * root of a drive (X:\foo), include the slash.
963 * In case file_name is the root share of an UNC path
964 * (\\server\share), add a slash, returning \\server\share\ .
966 * In case file_name is a direct child of a share in an UNC path
967 * (\\server\share\foo), include the slash after the share name,
968 * returning \\server\share\ .
970 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
972 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
973 G_IS_DIR_SEPARATOR (file_name[1]) &&
975 !G_IS_DIR_SEPARATOR (file_name[2]) &&
976 base >= file_name + 2)
978 const gchar *p = file_name + 2;
979 while (*p && !G_IS_DIR_SEPARATOR (*p))
983 len = (guint) strlen (file_name) + 1;
984 base = g_new (gchar, len + 1);
985 strcpy (base, file_name);
986 base[len-1] = G_DIR_SEPARATOR;
990 if (G_IS_DIR_SEPARATOR (*p))
993 while (*p && !G_IS_DIR_SEPARATOR (*p))
1001 len = (guint) 1 + base - file_name;
1003 base = g_new (gchar, len + 1);
1004 g_memmove (base, file_name, len);
1011 * g_get_current_dir:
1013 * Gets the current directory.
1014 * The returned string should be freed when no longer needed. The encoding
1015 * of the returned string is system defined. On Windows, it is always UTF-8.
1017 * Returns: the current directory.
1020 g_get_current_dir (void)
1025 wchar_t dummy[2], *wdir;
1028 len = GetCurrentDirectoryW (2, dummy);
1029 wdir = g_new (wchar_t, len);
1031 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1032 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1037 dir = g_strdup ("\\");
1043 gchar *buffer = NULL;
1045 static gulong max_len = 0;
1048 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1050 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1051 * and, if that wasn't bad enough, hangs in doing so.
1053 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1054 buffer = g_new (gchar, max_len + 1);
1056 dir = getwd (buffer);
1057 #else /* !sun || !HAVE_GETCWD */
1058 while (max_len < G_MAXULONG / 2)
1061 buffer = g_new (gchar, max_len + 1);
1063 dir = getcwd (buffer, max_len);
1065 if (dir || errno != ERANGE)
1070 #endif /* !sun || !HAVE_GETCWD */
1072 if (!dir || !*buffer)
1074 /* hm, should we g_error() out here?
1075 * this can happen if e.g. "./" has mode \0000
1077 buffer[0] = G_DIR_SEPARATOR;
1081 dir = g_strdup (buffer);
1088 G_LOCK_DEFINE_STATIC (g_utils_global);
1090 static gchar *g_tmp_dir = NULL;
1091 static gchar *g_user_name = NULL;
1092 static gchar *g_real_name = NULL;
1093 static gchar *g_home_dir = NULL;
1094 static gchar *g_host_name = NULL;
1097 /* System codepage versions of the above, kept at file level so that they,
1098 * too, are produced only once.
1100 static gchar *g_tmp_dir_cp = NULL;
1101 static gchar *g_user_name_cp = NULL;
1102 static gchar *g_real_name_cp = NULL;
1103 static gchar *g_home_dir_cp = NULL;
1106 static gchar *g_user_data_dir = NULL;
1107 static gchar **g_system_data_dirs = NULL;
1108 static gchar *g_user_cache_dir = NULL;
1109 static gchar *g_user_config_dir = NULL;
1110 static gchar **g_system_config_dirs = NULL;
1112 static gchar **g_user_special_dirs = NULL;
1114 /* fifteen minutes of fame for everybody */
1115 #define G_USER_DIRS_EXPIRE 15 * 60
1120 get_special_folder (int csidl)
1122 wchar_t path[MAX_PATH+1];
1124 LPITEMIDLIST pidl = NULL;
1126 gchar *retval = NULL;
1128 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1131 b = SHGetPathFromIDListW (pidl, path);
1133 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1134 CoTaskMemFree (pidl);
1140 get_windows_directory_root (void)
1142 wchar_t wwindowsdir[MAX_PATH];
1144 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1146 /* Usually X:\Windows, but in terminal server environments
1147 * might be an UNC path, AFAIK.
1149 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1152 if (windowsdir == NULL)
1153 return g_strdup ("C:\\");
1155 p = (char *) g_path_skip_root (windowsdir);
1156 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1162 return g_strdup ("C:\\");
1167 /* HOLDS: g_utils_global_lock */
1169 g_get_any_init_do (void)
1171 gchar hostname[100];
1173 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1174 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1175 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1176 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1177 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1180 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1181 g_tmp_dir = get_windows_directory_root ();
1184 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1187 g_tmp_dir = g_strdup (P_tmpdir);
1188 k = strlen (g_tmp_dir);
1189 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1190 g_tmp_dir[k - 1] = '\0';
1194 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1196 g_tmp_dir = g_strdup ("/tmp");
1198 #endif /* !G_OS_WIN32 */
1201 /* We check $HOME first for Win32, though it is a last resort for Unix
1202 * where we prefer the results of getpwuid().
1204 g_home_dir = g_strdup (g_getenv ("HOME"));
1206 /* Only believe HOME if it is an absolute path and exists */
1209 if (!(g_path_is_absolute (g_home_dir) &&
1210 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1212 g_free (g_home_dir);
1217 /* In case HOME is Unix-style (it happens), convert it to
1223 while ((p = strchr (g_home_dir, '/')) != NULL)
1229 /* USERPROFILE is probably the closest equivalent to $HOME? */
1230 if (g_getenv ("USERPROFILE") != NULL)
1231 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1235 g_home_dir = get_special_folder (CSIDL_PROFILE);
1238 g_home_dir = get_windows_directory_root ();
1239 #endif /* G_OS_WIN32 */
1243 struct passwd *pw = NULL;
1244 gpointer buffer = NULL;
1248 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1250 # ifdef _SC_GETPW_R_SIZE_MAX
1251 /* This reurns the maximum length */
1252 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1256 # else /* _SC_GETPW_R_SIZE_MAX */
1258 # endif /* _SC_GETPW_R_SIZE_MAX */
1260 logname = (gchar *) g_getenv ("LOGNAME");
1265 /* we allocate 6 extra bytes to work around a bug in
1266 * Mac OS < 10.3. See #156446
1268 buffer = g_malloc (bufsize + 6);
1271 # ifdef HAVE_POSIX_GETPWUID_R
1273 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1274 if (!pw || (pw->pw_uid != getuid ())) {
1275 /* LOGNAME is lying, fall back to looking up the uid */
1276 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1279 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1281 error = error < 0 ? errno : error;
1282 # else /* HAVE_NONPOSIX_GETPWUID_R */
1283 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1284 # if defined(_AIX) || defined(__hpux)
1285 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1286 pw = error == 0 ? &pwd : NULL;
1289 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1290 if (!pw || (pw->pw_uid != getuid ())) {
1291 /* LOGNAME is lying, fall back to looking up the uid */
1292 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1295 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1297 error = pw ? 0 : errno;
1299 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1303 /* we bail out prematurely if the user id can't be found
1304 * (should be pretty rare case actually), or if the buffer
1305 * should be sufficiently big and lookups are still not
1308 if (error == 0 || error == ENOENT)
1310 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1311 (gulong) getuid ());
1314 if (bufsize > 32 * 1024)
1316 g_warning ("getpwuid_r(): failed due to: %s.",
1317 g_strerror (error));
1325 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1330 pw = getpwuid (getuid ());
1335 g_user_name = g_strdup (pw->pw_name);
1337 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1339 gchar **gecos_fields;
1342 /* split the gecos field and substitute '&' */
1343 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1344 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1345 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1346 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1347 g_strfreev (gecos_fields);
1348 g_strfreev (name_parts);
1352 g_home_dir = g_strdup (pw->pw_dir);
1357 #else /* !HAVE_PWD_H */
1361 guint len = UNLEN+1;
1362 wchar_t buffer[UNLEN+1];
1364 if (GetUserNameW (buffer, (LPDWORD) &len))
1366 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1367 g_real_name = g_strdup (g_user_name);
1370 #endif /* G_OS_WIN32 */
1372 #endif /* !HAVE_PWD_H */
1376 g_home_dir = g_strdup (g_getenv ("HOME"));
1380 /* change '\\' in %HOME% to '/' */
1381 g_strdelimit (g_home_dir, "\\",'/');
1384 g_user_name = g_strdup ("somebody");
1386 g_real_name = g_strdup ("Unknown");
1390 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1392 DWORD size = sizeof (hostname);
1393 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1395 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1399 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1400 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1401 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1404 g_tmp_dir_cp = g_strdup ("\\");
1405 if (!g_user_name_cp)
1406 g_user_name_cp = g_strdup ("somebody");
1407 if (!g_real_name_cp)
1408 g_real_name_cp = g_strdup ("Unknown");
1410 /* home_dir might be NULL, unlike tmp_dir, user_name and
1414 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1416 g_home_dir_cp = NULL;
1417 #endif /* G_OS_WIN32 */
1421 g_get_any_init (void)
1424 g_get_any_init_do ();
1428 g_get_any_init_locked (void)
1430 G_LOCK (g_utils_global);
1432 G_UNLOCK (g_utils_global);
1439 * Gets the user name of the current user. The encoding of the returned
1440 * string is system-defined. On UNIX, it might be the preferred file name
1441 * encoding, or something else, and there is no guarantee that it is even
1442 * consistent on a machine. On Windows, it is always UTF-8.
1444 * Returns: the user name of the current user.
1447 g_get_user_name (void)
1449 g_get_any_init_locked ();
1456 * Gets the real name of the user. This usually comes from the user's entry
1457 * in the <filename>passwd</filename> file. The encoding of the returned
1458 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1459 * If the real user name cannot be determined, the string "Unknown" is
1462 * Returns: the user's real name.
1465 g_get_real_name (void)
1467 g_get_any_init_locked ();
1474 * Gets the current user's home directory as defined in the
1475 * password database.
1477 * Note that in contrast to traditional UNIX tools, this function
1478 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1479 * environment variable.
1481 * One of the reasons for this decision is that applications in many
1482 * cases need special handling to deal with the case where
1483 * <envar>HOME</envar> is
1485 * <member>Not owned by the user</member>
1486 * <member>Not writeable</member>
1487 * <member>Not even readable</member>
1489 * Since applications are in general <emphasis>not</emphasis> written
1490 * to deal with these situations it was considered better to make
1491 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1492 * return the real home directory for the user. If applications
1493 * want to pay attention to <envar>HOME</envar>, they can do:
1495 * const char *homedir = g_getenv ("HOME");
1497 * homedir = g_get_home_dir (<!-- -->);
1500 * Returns: the current user's home directory
1503 g_get_home_dir (void)
1505 g_get_any_init_locked ();
1512 * Gets the directory to use for temporary files. This is found from
1513 * inspecting the environment variables <envar>TMPDIR</envar>,
1514 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1515 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1516 * The encoding of the returned string is system-defined. On Windows,
1517 * it is always UTF-8. The return value is never %NULL or the empty string.
1519 * Returns: the directory to use for temporary files.
1522 g_get_tmp_dir (void)
1524 g_get_any_init_locked ();
1531 * Return a name for the machine.
1533 * The returned name is not necessarily a fully-qualified domain name,
1534 * or even present in DNS or some other name service at all. It need
1535 * not even be unique on your local network or site, but usually it
1536 * is. Callers should not rely on the return value having any specific
1537 * properties like uniqueness for security purposes. Even if the name
1538 * of the machine is changed while an application is running, the
1539 * return value from this function does not change. The returned
1540 * string is owned by GLib and should not be modified or freed. If no
1541 * name can be determined, a default fixed string "localhost" is
1544 * Returns: the host name of the machine.
1549 g_get_host_name (void)
1551 g_get_any_init_locked ();
1555 G_LOCK_DEFINE_STATIC (g_prgname);
1556 static gchar *g_prgname = NULL;
1561 * Gets the name of the program. This name should <emphasis>not</emphasis>
1562 * be localized, contrast with g_get_application_name().
1563 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1564 * which is called by gtk_init(). The program name is found by taking
1565 * the last component of <literal>argv[0]</literal>.)
1567 * Returns: the name of the program. The returned string belongs
1568 * to GLib and must not be modified or freed.
1571 g_get_prgname (void)
1577 if (g_prgname == NULL)
1579 static gboolean beenhere = FALSE;
1583 gchar *utf8_buf = NULL;
1584 wchar_t buf[MAX_PATH+1];
1587 if (GetModuleFileNameW (GetModuleHandle (NULL),
1588 buf, G_N_ELEMENTS (buf)) > 0)
1589 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1593 g_prgname = g_path_get_basename (utf8_buf);
1600 G_UNLOCK (g_prgname);
1607 * @prgname: the name of the program.
1609 * Sets the name of the program. This name should <emphasis>not</emphasis>
1610 * be localized, contrast with g_set_application_name(). Note that for
1611 * thread-safety reasons this function can only be called once.
1614 g_set_prgname (const gchar *prgname)
1618 g_prgname = g_strdup (prgname);
1619 G_UNLOCK (g_prgname);
1622 G_LOCK_DEFINE_STATIC (g_application_name);
1623 static gchar *g_application_name = NULL;
1626 * g_get_application_name:
1628 * Gets a human-readable name for the application, as set by
1629 * g_set_application_name(). This name should be localized if
1630 * possible, and is intended for display to the user. Contrast with
1631 * g_get_prgname(), which gets a non-localized name. If
1632 * g_set_application_name() has not been called, returns the result of
1633 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1636 * Return value: human-readable application name. may return %NULL
1641 g_get_application_name (void)
1645 G_LOCK (g_application_name);
1646 retval = g_application_name;
1647 G_UNLOCK (g_application_name);
1650 return g_get_prgname ();
1656 * g_set_application_name:
1657 * @application_name: localized name of the application
1659 * Sets a human-readable name for the application. This name should be
1660 * localized if possible, and is intended for display to the user.
1661 * Contrast with g_set_prgname(), which sets a non-localized name.
1662 * g_set_prgname() will be called automatically by gtk_init(),
1663 * but g_set_application_name() will not.
1665 * Note that for thread safety reasons, this function can only
1668 * The application name will be used in contexts such as error messages,
1669 * or when displaying an application's name in the task list.
1674 g_set_application_name (const gchar *application_name)
1676 gboolean already_set = FALSE;
1678 G_LOCK (g_application_name);
1679 if (g_application_name)
1682 g_application_name = g_strdup (application_name);
1683 G_UNLOCK (g_application_name);
1686 g_warning ("g_set_application_name() called multiple times");
1690 * g_get_user_data_dir:
1692 * Returns a base directory in which to access application data such
1693 * as icons that is customized for a particular user.
1695 * On UNIX platforms this is determined using the mechanisms described in
1696 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1697 * XDG Base Directory Specification</ulink>.
1698 * In this case the directory retrieved will be XDG_DATA_HOME.
1700 * On Windows this is the folder to use for local (as opposed to
1701 * roaming) application data. See documentation for
1702 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1703 * what g_get_user_config_dir() returns.
1705 * Return value: a string owned by GLib that must not be modified
1710 g_get_user_data_dir (void)
1714 G_LOCK (g_utils_global);
1716 if (!g_user_data_dir)
1719 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1721 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1723 if (data_dir && data_dir[0])
1724 data_dir = g_strdup (data_dir);
1726 if (!data_dir || !data_dir[0])
1731 data_dir = g_build_filename (g_home_dir, ".local",
1734 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
1738 g_user_data_dir = data_dir;
1741 data_dir = g_user_data_dir;
1743 G_UNLOCK (g_utils_global);
1749 g_init_user_config_dir (void)
1753 if (!g_user_config_dir)
1756 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1758 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1760 if (config_dir && config_dir[0])
1761 config_dir = g_strdup (config_dir);
1763 if (!config_dir || !config_dir[0])
1768 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1770 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
1773 g_user_config_dir = config_dir;
1778 * g_get_user_config_dir:
1780 * Returns a base directory in which to store user-specific application
1781 * configuration information such as user preferences and settings.
1783 * On UNIX platforms this is determined using the mechanisms described in
1784 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1785 * XDG Base Directory Specification</ulink>.
1786 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1788 * On Windows this is the folder to use for local (as opposed to
1789 * roaming) application data. See documentation for
1790 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1791 * what g_get_user_data_dir() returns.
1793 * Return value: a string owned by GLib that must not be modified
1798 g_get_user_config_dir (void)
1800 G_LOCK (g_utils_global);
1802 g_init_user_config_dir ();
1804 G_UNLOCK (g_utils_global);
1806 return g_user_config_dir;
1810 * g_get_user_cache_dir:
1812 * Returns a base directory in which to store non-essential, cached
1813 * data specific to particular user.
1815 * On UNIX platforms this is determined using the mechanisms described in
1816 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1817 * XDG Base Directory Specification</ulink>.
1818 * In this case the directory retrieved will be XDG_CACHE_HOME.
1820 * On Windows is the directory that serves as a common repository for
1821 * temporary Internet files. A typical path is
1822 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1823 * See documentation for CSIDL_INTERNET_CACHE.
1825 * Return value: a string owned by GLib that must not be modified
1830 g_get_user_cache_dir (void)
1834 G_LOCK (g_utils_global);
1836 if (!g_user_cache_dir)
1839 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1841 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1843 if (cache_dir && cache_dir[0])
1844 cache_dir = g_strdup (cache_dir);
1846 if (!cache_dir || !cache_dir[0])
1851 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1853 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
1855 g_user_cache_dir = cache_dir;
1858 cache_dir = g_user_cache_dir;
1860 G_UNLOCK (g_utils_global);
1866 * g_get_user_runtime_dir:
1868 * Returns a directory that is unique to the current user on the local
1871 * On UNIX platforms this is determined using the mechanisms described in
1872 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1873 * XDG Base Directory Specification</ulink>. This is the directory
1874 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1875 * In the case that this variable is not set, GLib will issue a warning
1876 * message to stderr and return the value of g_get_user_cache_dir().
1878 * On Windows this is the folder to use for local (as opposed to
1879 * roaming) application data. See documentation for
1880 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1881 * what g_get_user_config_dir() returns.
1883 * Returns: a string owned by GLib that must not be modified or freed.
1888 g_get_user_runtime_dir (void)
1891 static const gchar *runtime_dir;
1892 static gsize initialised;
1894 if (g_once_init_enter (&initialised))
1896 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1898 g_once_init_leave (&initialised, 1);
1904 /* Both fallback for UNIX and the default
1905 * in Windows: use the user cache directory.
1909 return g_get_user_cache_dir ();
1915 find_folder (OSType type)
1917 gchar *filename = NULL;
1920 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1922 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1926 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1930 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1934 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1936 CFStringGetCString (path, filename,
1937 CFStringGetLength (path) * 3 + 1,
1938 kCFStringEncodingUTF8);
1952 load_user_special_dirs (void)
1954 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1955 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1956 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1957 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1958 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1959 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1960 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1961 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1964 #endif /* HAVE_CARBON */
1966 #if defined(G_OS_WIN32)
1968 load_user_special_dirs (void)
1970 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1974 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1976 static const GUID FOLDERID_Downloads =
1977 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1978 static const GUID FOLDERID_Public =
1979 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1983 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1984 "SHGetKnownFolderPath");
1986 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1987 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1989 if (p_SHGetKnownFolderPath == NULL)
1991 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1996 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1999 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2000 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2001 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2002 CoTaskMemFree (wcp);
2005 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2008 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2009 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2011 if (p_SHGetKnownFolderPath == NULL)
2014 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2019 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2022 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2023 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2024 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2025 CoTaskMemFree (wcp);
2028 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2031 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2032 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2034 #endif /* G_OS_WIN32 */
2036 static void g_init_user_config_dir (void);
2038 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2040 /* adapted from xdg-user-dir-lookup.c
2042 * Copyright (C) 2007 Red Hat Inc.
2044 * Permission is hereby granted, free of charge, to any person
2045 * obtaining a copy of this software and associated documentation files
2046 * (the "Software"), to deal in the Software without restriction,
2047 * including without limitation the rights to use, copy, modify, merge,
2048 * publish, distribute, sublicense, and/or sell copies of the Software,
2049 * and to permit persons to whom the Software is furnished to do so,
2050 * subject to the following conditions:
2052 * The above copyright notice and this permission notice shall be
2053 * included in all copies or substantial portions of the Software.
2055 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2056 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2057 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2058 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2059 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2060 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2061 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2065 load_user_special_dirs (void)
2072 g_init_user_config_dir ();
2073 config_file = g_build_filename (g_user_config_dir,
2077 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2079 g_free (config_file);
2083 lines = g_strsplit (data, "\n", -1);
2084 n_lines = g_strv_length (lines);
2087 for (i = 0; i < n_lines; i++)
2089 gchar *buffer = lines[i];
2092 gboolean is_relative = FALSE;
2093 GUserDirectory directory;
2095 /* Remove newline at end */
2096 len = strlen (buffer);
2097 if (len > 0 && buffer[len - 1] == '\n')
2098 buffer[len - 1] = 0;
2101 while (*p == ' ' || *p == '\t')
2104 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2106 directory = G_USER_DIRECTORY_DESKTOP;
2107 p += strlen ("XDG_DESKTOP_DIR");
2109 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2111 directory = G_USER_DIRECTORY_DOCUMENTS;
2112 p += strlen ("XDG_DOCUMENTS_DIR");
2114 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2116 directory = G_USER_DIRECTORY_DOWNLOAD;
2117 p += strlen ("XDG_DOWNLOAD_DIR");
2119 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2121 directory = G_USER_DIRECTORY_MUSIC;
2122 p += strlen ("XDG_MUSIC_DIR");
2124 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2126 directory = G_USER_DIRECTORY_PICTURES;
2127 p += strlen ("XDG_PICTURES_DIR");
2129 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2131 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2132 p += strlen ("XDG_PUBLICSHARE_DIR");
2134 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2136 directory = G_USER_DIRECTORY_TEMPLATES;
2137 p += strlen ("XDG_TEMPLATES_DIR");
2139 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2141 directory = G_USER_DIRECTORY_VIDEOS;
2142 p += strlen ("XDG_VIDEOS_DIR");
2147 while (*p == ' ' || *p == '\t')
2154 while (*p == ' ' || *p == '\t')
2161 if (strncmp (p, "$HOME", 5) == 0)
2169 d = strrchr (p, '"');
2176 /* remove trailing slashes */
2178 if (d[len - 1] == '/')
2184 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2187 g_user_special_dirs[directory] = g_strdup (d);
2191 g_free (config_file);
2194 #endif /* G_OS_UNIX && !HAVE_CARBON */
2198 * g_reload_user_special_dirs_cache:
2200 * Resets the cache used for g_get_user_special_dir(), so
2201 * that the latest on-disk version is used. Call this only
2202 * if you just changed the data on disk yourself.
2204 * Due to threadsafety issues this may cause leaking of strings
2205 * that were previously returned from g_get_user_special_dir()
2206 * that can't be freed. We ensure to only leak the data for
2207 * the directories that actually changed value though.
2212 g_reload_user_special_dirs_cache (void)
2216 G_LOCK (g_utils_global);
2218 if (g_user_special_dirs != NULL)
2220 /* save a copy of the pointer, to check if some memory can be preserved */
2221 char **old_g_user_special_dirs = g_user_special_dirs;
2224 /* recreate and reload our cache */
2225 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2226 load_user_special_dirs ();
2228 /* only leak changed directories */
2229 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2231 old_val = old_g_user_special_dirs[i];
2232 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2235 g_free (g_user_special_dirs[i]);
2236 g_user_special_dirs[i] = old_val;
2242 /* free the old array */
2243 g_free (old_g_user_special_dirs);
2246 G_UNLOCK (g_utils_global);
2250 * g_get_user_special_dir:
2251 * @directory: the logical id of special directory
2253 * Returns the full path of a special directory using its logical id.
2255 * On Unix this is done using the XDG special user directories.
2256 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2257 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2258 * user directories have not been set up.
2260 * Depending on the platform, the user might be able to change the path
2261 * of the special directory without requiring the session to restart; GLib
2262 * will not reflect any change once the special directories are loaded.
2264 * Return value: the path to the specified special directory, or %NULL
2265 * if the logical id was not found. The returned string is owned by
2266 * GLib and should not be modified or freed.
2271 g_get_user_special_dir (GUserDirectory directory)
2273 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2274 directory < G_USER_N_DIRECTORIES, NULL);
2276 G_LOCK (g_utils_global);
2278 if (G_UNLIKELY (g_user_special_dirs == NULL))
2280 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2282 load_user_special_dirs ();
2284 /* Special-case desktop for historical compatibility */
2285 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2289 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2290 g_build_filename (g_home_dir, "Desktop", NULL);
2294 G_UNLOCK (g_utils_global);
2296 return g_user_special_dirs[directory];
2301 #undef g_get_system_data_dirs
2304 get_module_for_address (gconstpointer address)
2306 /* Holds the g_utils_global lock */
2308 static gboolean beenhere = FALSE;
2309 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2310 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2311 HMODULE hmodule = NULL;
2318 p_GetModuleHandleExA =
2319 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2320 "GetModuleHandleExA");
2324 if (p_GetModuleHandleExA == NULL ||
2325 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2326 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2329 MEMORY_BASIC_INFORMATION mbi;
2330 VirtualQuery (address, &mbi, sizeof (mbi));
2331 hmodule = (HMODULE) mbi.AllocationBase;
2338 get_module_share_dir (gconstpointer address)
2344 hmodule = get_module_for_address (address);
2345 if (hmodule == NULL)
2348 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2349 retval = g_build_filename (filename, "share", NULL);
2355 const gchar * const *
2356 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2360 static GHashTable *per_module_data_dirs = NULL;
2365 if (address_of_function)
2367 G_LOCK (g_utils_global);
2368 hmodule = get_module_for_address (address_of_function);
2369 if (hmodule != NULL)
2371 if (per_module_data_dirs == NULL)
2372 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2375 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2379 G_UNLOCK (g_utils_global);
2380 return (const gchar * const *) retval;
2386 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2388 /* Documents and Settings\All Users\Application Data */
2389 p = get_special_folder (CSIDL_COMMON_APPDATA);
2391 g_array_append_val (data_dirs, p);
2393 /* Documents and Settings\All Users\Documents */
2394 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2396 g_array_append_val (data_dirs, p);
2398 /* Using the above subfolders of Documents and Settings perhaps
2399 * makes sense from a Windows perspective.
2401 * But looking at the actual use cases of this function in GTK+
2402 * and GNOME software, what we really want is the "share"
2403 * subdirectory of the installation directory for the package
2404 * our caller is a part of.
2406 * The address_of_function parameter, if non-NULL, points to a
2407 * function in the calling module. Use that to determine that
2408 * module's installation folder, and use its "share" subfolder.
2410 * Additionally, also use the "share" subfolder of the installation
2411 * locations of GLib and the .exe file being run.
2413 * To guard against none of the above being what is really wanted,
2414 * callers of this function should have Win32-specific code to look
2415 * up their installation folder themselves, and handle a subfolder
2416 * "share" of it in the same way as the folders returned from this
2420 p = get_module_share_dir (address_of_function);
2422 g_array_append_val (data_dirs, p);
2424 if (glib_dll != NULL)
2426 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2427 p = g_build_filename (glib_root, "share", NULL);
2429 g_array_append_val (data_dirs, p);
2433 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2434 p = g_build_filename (exe_root, "share", NULL);
2436 g_array_append_val (data_dirs, p);
2439 retval = (gchar **) g_array_free (data_dirs, FALSE);
2441 if (address_of_function)
2443 if (hmodule != NULL)
2444 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2445 G_UNLOCK (g_utils_global);
2448 return (const gchar * const *) retval;
2454 * g_get_system_data_dirs:
2456 * Returns an ordered list of base directories in which to access
2457 * system-wide application data.
2459 * On UNIX platforms this is determined using the mechanisms described in
2460 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2461 * XDG Base Directory Specification</ulink>
2462 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2464 * On Windows the first elements in the list are the Application Data
2465 * and Documents folders for All Users. (These can be determined only
2466 * on Windows 2000 or later and are not present in the list on other
2467 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2468 * CSIDL_COMMON_DOCUMENTS.
2470 * Then follows the "share" subfolder in the installation folder for
2471 * the package containing the DLL that calls this function, if it can
2474 * Finally the list contains the "share" subfolder in the installation
2475 * folder for GLib, and in the installation folder for the package the
2476 * application's .exe file belongs to.
2478 * The installation folders above are determined by looking up the
2479 * folder where the module (DLL or EXE) in question is located. If the
2480 * folder's name is "bin", its parent is used, otherwise the folder
2483 * Note that on Windows the returned list can vary depending on where
2484 * this function is called.
2486 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2487 * not be modified or freed.
2490 const gchar * const *
2491 g_get_system_data_dirs (void)
2493 gchar **data_dir_vector;
2495 G_LOCK (g_utils_global);
2497 if (!g_system_data_dirs)
2500 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2502 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2504 if (!data_dirs || !data_dirs[0])
2505 data_dirs = "/usr/local/share/:/usr/share/";
2507 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2510 g_system_data_dirs = data_dir_vector;
2513 data_dir_vector = g_system_data_dirs;
2515 G_UNLOCK (g_utils_global);
2517 return (const gchar * const *) data_dir_vector;
2521 * g_get_system_config_dirs:
2523 * Returns an ordered list of base directories in which to access
2524 * system-wide configuration information.
2526 * On UNIX platforms this is determined using the mechanisms described in
2527 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2528 * XDG Base Directory Specification</ulink>.
2529 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2531 * On Windows is the directory that contains application data for all users.
2532 * A typical path is C:\Documents and Settings\All Users\Application Data.
2533 * This folder is used for application data that is not user specific.
2534 * For example, an application can store a spell-check dictionary, a database
2535 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2536 * This information will not roam and is available to anyone using the computer.
2538 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2539 * not be modified or freed.
2542 const gchar * const *
2543 g_get_system_config_dirs (void)
2545 gchar *conf_dirs, **conf_dir_vector;
2547 G_LOCK (g_utils_global);
2549 if (!g_system_config_dirs)
2552 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2555 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2560 /* Return empty list */
2561 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2564 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2566 if (!conf_dirs || !conf_dirs[0])
2567 conf_dirs = "/etc/xdg";
2569 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2572 g_system_config_dirs = conf_dir_vector;
2575 conf_dir_vector = g_system_config_dirs;
2576 G_UNLOCK (g_utils_global);
2578 return (const gchar * const *) conf_dir_vector;
2583 static GHashTable *alias_table = NULL;
2585 /* read an alias file for the locales */
2587 read_aliases (gchar *file)
2593 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
2594 fp = fopen (file,"r");
2597 while (fgets (buf, 256, fp))
2603 /* Line is a comment */
2604 if ((buf[0] == '#') || (buf[0] == '\0'))
2607 /* Reads first column */
2608 for (p = buf, q = NULL; *p; p++) {
2609 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
2612 while ((*q == '\t') || (*q == ' ')) {
2618 /* The line only had one column */
2619 if (!q || *q == '\0')
2622 /* Read second column */
2623 for (p = q; *p; p++) {
2624 if ((*p == '\t') || (*p == ' ')) {
2630 /* Add to alias table if necessary */
2631 if (!g_hash_table_lookup (alias_table, buf)) {
2632 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
2641 unalias_lang (char *lang)
2648 read_aliases ("/usr/share/locale/locale.alias");
2651 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
2656 static gboolean said_before = FALSE;
2658 g_warning ("Too many alias levels for a locale, "
2659 "may indicate a loop");
2668 /* Mask for components of locale spec. The ordering here is from
2669 * least significant to most significant
2673 COMPONENT_CODESET = 1 << 0,
2674 COMPONENT_TERRITORY = 1 << 1,
2675 COMPONENT_MODIFIER = 1 << 2
2678 /* Break an X/Open style locale specification into components
2681 explode_locale (const gchar *locale,
2687 const gchar *uscore_pos;
2688 const gchar *at_pos;
2689 const gchar *dot_pos;
2693 uscore_pos = strchr (locale, '_');
2694 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
2695 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
2699 mask |= COMPONENT_MODIFIER;
2700 *modifier = g_strdup (at_pos);
2703 at_pos = locale + strlen (locale);
2707 mask |= COMPONENT_CODESET;
2708 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
2715 mask |= COMPONENT_TERRITORY;
2716 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
2719 uscore_pos = dot_pos;
2721 *language = g_strndup (locale, uscore_pos - locale);
2727 * Compute all interesting variants for a given locale name -
2728 * by stripping off different components of the value.
2730 * For simplicity, we assume that the locale is in
2731 * X/Open format: language[_territory][.codeset][@modifier]
2733 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2734 * as well. We could just copy the code from glibc wholesale
2735 * but it is big, ugly, and complicated, so I'm reluctant
2736 * to do so when this should handle 99% of the time...
2739 append_locale_variants (GPtrArray *array,
2740 const gchar *locale)
2742 gchar *language = NULL;
2743 gchar *territory = NULL;
2744 gchar *codeset = NULL;
2745 gchar *modifier = NULL;
2750 g_return_if_fail (locale != NULL);
2752 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
2754 /* Iterate through all possible combinations, from least attractive
2755 * to most attractive.
2757 for (j = 0; j <= mask; ++j)
2761 if ((i & ~mask) == 0)
2763 gchar *val = g_strconcat (language,
2764 (i & COMPONENT_TERRITORY) ? territory : "",
2765 (i & COMPONENT_CODESET) ? codeset : "",
2766 (i & COMPONENT_MODIFIER) ? modifier : "",
2768 g_ptr_array_add (array, val);
2773 if (mask & COMPONENT_CODESET)
2775 if (mask & COMPONENT_TERRITORY)
2777 if (mask & COMPONENT_MODIFIER)
2782 * g_get_locale_variants:
2783 * @locale: a locale identifier
2785 * Returns a list of derived variants of @locale, which can be used to
2786 * e.g. construct locale-dependent filenames or search paths. The returned
2787 * list is sorted from most desirable to least desirable.
2788 * This function handles territory, charset and extra locale modifiers.
2790 * For example, if @locale is "fr_BE", then the returned list
2793 * If you need the list of variants for the <emphasis>current locale</emphasis>,
2794 * use g_get_language_names().
2796 * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
2797 * allocated array of newly allocated strings with the locale variants. Free with
2803 g_get_locale_variants (const gchar *locale)
2807 g_return_val_if_fail (locale != NULL, NULL);
2809 array = g_ptr_array_sized_new (8);
2810 append_locale_variants (array, locale);
2811 g_ptr_array_add (array, NULL);
2813 return (gchar **) g_ptr_array_free (array, FALSE);
2816 /* The following is (partly) taken from the gettext package.
2817 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2819 static const gchar *
2820 guess_category_value (const gchar *category_name)
2822 const gchar *retval;
2824 /* The highest priority value is the `LANGUAGE' environment
2825 variable. This is a GNU extension. */
2826 retval = g_getenv ("LANGUAGE");
2827 if ((retval != NULL) && (retval[0] != '\0'))
2830 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2831 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2832 systems this can be done by the `setlocale' function itself. */
2834 /* Setting of LC_ALL overwrites all other. */
2835 retval = g_getenv ("LC_ALL");
2836 if ((retval != NULL) && (retval[0] != '\0'))
2839 /* Next comes the name of the desired category. */
2840 retval = g_getenv (category_name);
2841 if ((retval != NULL) && (retval[0] != '\0'))
2844 /* Last possibility is the LANG environment variable. */
2845 retval = g_getenv ("LANG");
2846 if ((retval != NULL) && (retval[0] != '\0'))
2849 #ifdef G_PLATFORM_WIN32
2850 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2851 * LANG, which we already did above. Oh well. The main point of
2852 * calling g_win32_getlocale() is to get the thread's locale as used
2853 * by Windows and the Microsoft C runtime (in the "English_United
2854 * States" format) translated into the Unixish format.
2857 char *locale = g_win32_getlocale ();
2858 retval = g_intern_string (locale);
2867 typedef struct _GLanguageNamesCache GLanguageNamesCache;
2869 struct _GLanguageNamesCache {
2871 gchar **language_names;
2875 language_names_cache_free (gpointer data)
2877 GLanguageNamesCache *cache = data;
2878 g_free (cache->languages);
2879 g_strfreev (cache->language_names);
2884 * g_get_language_names:
2886 * Computes a list of applicable locale names, which can be used to
2887 * e.g. construct locale-dependent filenames or search paths. The returned
2888 * list is sorted from most desirable to least desirable and always contains
2889 * the default locale "C".
2891 * For example, if LANGUAGE=de:en_US, then the returned list is
2892 * "de", "en_US", "en", "C".
2894 * This function consults the environment variables <envar>LANGUAGE</envar>,
2895 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2896 * to find the list of locales specified by the user.
2898 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
2899 * that must not be modified or freed.
2903 const gchar * const *
2904 g_get_language_names (void)
2906 static GPrivate cache_private = G_PRIVATE_INIT (language_names_cache_free);
2907 GLanguageNamesCache *cache = g_private_get (&cache_private);
2912 cache = g_new0 (GLanguageNamesCache, 1);
2913 g_private_set (&cache_private, cache);
2916 value = guess_category_value ("LC_MESSAGES");
2920 if (!(cache->languages && strcmp (cache->languages, value) == 0))
2925 g_free (cache->languages);
2926 g_strfreev (cache->language_names);
2927 cache->languages = g_strdup (value);
2929 array = g_ptr_array_sized_new (8);
2931 alist = g_strsplit (value, ":", 0);
2932 for (a = alist; *a; a++)
2933 append_locale_variants (array, unalias_lang (*a));
2935 g_ptr_array_add (array, g_strdup ("C"));
2936 g_ptr_array_add (array, NULL);
2938 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
2941 return (const gchar * const *) cache->language_names;
2945 * g_nullify_pointer:
2946 * @nullify_location: the memory address of the pointer.
2948 * Set the pointer at the specified location to %NULL.
2951 g_nullify_pointer (gpointer *nullify_location)
2953 g_return_if_fail (nullify_location != NULL);
2955 *nullify_location = NULL;
2961 * _glib_get_locale_dir:
2963 * Return the path to the share\locale or lib\locale subfolder of the
2964 * GLib installation folder. The path is in the system codepage. We
2965 * have to use system codepage as bindtextdomain() doesn't have a
2969 _glib_get_locale_dir (void)
2971 gchar *install_dir = NULL, *locale_dir;
2972 gchar *retval = NULL;
2974 if (glib_dll != NULL)
2975 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
2980 * Append "/share/locale" or "/lib/locale" depending on whether
2981 * autoconfigury detected GNU gettext or not.
2983 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
2989 locale_dir = g_build_filename (install_dir, p, NULL);
2991 retval = g_win32_locale_filename_from_utf8 (locale_dir);
2993 g_free (install_dir);
2994 g_free (locale_dir);
3000 return g_strdup ("");
3003 #undef GLIB_LOCALE_DIR
3005 #endif /* G_OS_WIN32 */
3008 ensure_gettext_initialized (void)
3010 static gsize initialised;
3012 if (g_once_init_enter (&initialised))
3015 gchar *tmp = _glib_get_locale_dir ();
3016 bindtextdomain (GETTEXT_PACKAGE, tmp);
3019 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3021 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3022 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3024 g_once_init_leave (&initialised, TRUE);
3030 * @str: The string to be translated
3032 * Returns the translated string from the glib translations.
3033 * This is an internal function and should only be used by
3034 * the internals of glib (such as libgio).
3036 * Returns: the transation of @str to the current locale
3039 glib_gettext (const gchar *str)
3041 ensure_gettext_initialized();
3043 return g_dgettext (GETTEXT_PACKAGE, str);
3048 * @msgctxtid: a combined message context and message id, separated
3049 * by a \004 character
3050 * @msgidoffset: the offset of the message id in @msgctxid
3052 * This function is a variant of glib_gettext() which supports
3053 * a disambiguating message context. See g_dpgettext() for full
3056 * This is an internal function and should only be used by
3057 * the internals of glib (such as libgio).
3059 * Returns: the transation of @str to the current locale
3062 glib_pgettext(const gchar *msgctxtid,
3065 ensure_gettext_initialized();
3067 return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3070 #if defined (G_OS_WIN32) && !defined (_WIN64)
3072 /* Binary compatibility versions. Not for newly compiled code. */
3074 #undef g_find_program_in_path
3077 g_find_program_in_path (const gchar *program)
3079 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3080 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3083 g_free (utf8_program);
3084 if (utf8_retval == NULL)
3086 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3087 g_free (utf8_retval);
3092 #undef g_get_current_dir
3095 g_get_current_dir (void)
3097 gchar *utf8_dir = g_get_current_dir_utf8 ();
3098 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3106 g_getenv (const gchar *variable)
3108 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3109 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3113 g_free (utf8_variable);
3116 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3117 quark = g_quark_from_string (value);
3120 return g_quark_to_string (quark);
3126 g_setenv (const gchar *variable,
3130 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3131 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3132 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3134 g_free (utf8_variable);
3135 g_free (utf8_value);
3143 g_unsetenv (const gchar *variable)
3145 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3147 g_unsetenv_utf8 (utf8_variable);
3149 g_free (utf8_variable);
3152 #undef g_get_user_name
3155 g_get_user_name (void)
3157 g_get_any_init_locked ();
3158 return g_user_name_cp;
3161 #undef g_get_real_name
3164 g_get_real_name (void)
3166 g_get_any_init_locked ();
3167 return g_real_name_cp;
3170 #undef g_get_home_dir
3173 g_get_home_dir (void)
3175 g_get_any_init_locked ();
3176 return g_home_dir_cp;
3179 #undef g_get_tmp_dir
3182 g_get_tmp_dir (void)
3184 g_get_any_init_locked ();
3185 return g_tmp_dir_cp;