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 "gfileutils.h"
106 #include "gprintfint.h"
108 #include "gthreadprivate.h"
109 #include "gtestutils.h"
110 #include "gunicode.h"
111 #include "gstrfuncs.h"
113 #include "glibintl.h"
115 #ifdef G_PLATFORM_WIN32
117 #include "gconvert.h"
124 * @title: Miscellaneous Utility Functions
125 * @short_description: a selection of portable utility functions
127 * These are portable utility functions.
131 #define G_PATH_LENGTH MAXPATHLEN
132 #elif defined (PATH_MAX)
133 #define G_PATH_LENGTH PATH_MAX
134 #elif defined (_PC_PATH_MAX)
135 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
137 #define G_PATH_LENGTH 2048
140 #ifdef G_PLATFORM_WIN32
141 # include <windows.h>
142 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
143 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
144 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
146 # include <lmcons.h> /* For UNLEN */
147 #endif /* G_PLATFORM_WIN32 */
152 /* older SDK (e.g. msvc 5.0) does not have these*/
153 # ifndef CSIDL_MYMUSIC
154 # define CSIDL_MYMUSIC 13
156 # ifndef CSIDL_MYVIDEO
157 # define CSIDL_MYVIDEO 14
159 # ifndef CSIDL_INTERNET_CACHE
160 # define CSIDL_INTERNET_CACHE 32
162 # ifndef CSIDL_COMMON_APPDATA
163 # define CSIDL_COMMON_APPDATA 35
165 # ifndef CSIDL_MYPICTURES
166 # define CSIDL_MYPICTURES 0x27
168 # ifndef CSIDL_COMMON_DOCUMENTS
169 # define CSIDL_COMMON_DOCUMENTS 46
171 # ifndef CSIDL_PROFILE
172 # define CSIDL_PROFILE 40
174 # include <process.h>
178 #include <CoreServices/CoreServices.h>
182 #include <langinfo.h>
185 const guint glib_major_version = GLIB_MAJOR_VERSION;
186 const guint glib_minor_version = GLIB_MINOR_VERSION;
187 const guint glib_micro_version = GLIB_MICRO_VERSION;
188 const guint glib_interface_age = GLIB_INTERFACE_AGE;
189 const guint glib_binary_age = GLIB_BINARY_AGE;
191 #ifdef G_PLATFORM_WIN32
194 _glib_get_dll_directory (void)
198 wchar_t wc_fn[MAX_PATH];
201 if (glib_dll == NULL)
205 /* This code is different from that in
206 * g_win32_get_package_installation_directory_of_module() in that
207 * here we return the actual folder where the GLib DLL is. We don't
208 * do the check for it being in a "bin" or "lib" subfolder and then
209 * returning the parent of that.
211 * In a statically built GLib, glib_dll will be NULL and we will
212 * thus look up the application's .exe file's location.
214 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
217 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
219 p = strrchr (retval, G_DIR_SEPARATOR);
233 * glib_check_version:
234 * @required_major: the required major version.
235 * @required_minor: the required minor version.
236 * @required_micro: the required micro version.
238 * Checks that the GLib library in use is compatible with the
239 * given version. Generally you would pass in the constants
240 * #GLIB_MAJOR_VERSION, #GLIB_MINOR_VERSION, #GLIB_MICRO_VERSION
241 * as the three arguments to this function; that produces
242 * a check that the library in use is compatible with
243 * the version of GLib the application or module was compiled
246 * Compatibility is defined by two things: first the version
247 * of the running library is newer than the version
248 * @required_major.required_minor.@required_micro. Second
249 * the running library must be binary compatible with the
250 * version @required_major.required_minor.@required_micro
251 * (same major version.)
253 * Return value: %NULL if the GLib library is compatible with the
254 * given version, or a string describing the version mismatch.
255 * The returned string is owned by GLib and must not be modified
261 glib_check_version (guint required_major,
262 guint required_minor,
263 guint required_micro)
265 gint glib_effective_micro = 100 * GLIB_MINOR_VERSION + GLIB_MICRO_VERSION;
266 gint required_effective_micro = 100 * required_minor + required_micro;
268 if (required_major > GLIB_MAJOR_VERSION)
269 return "GLib version too old (major mismatch)";
270 if (required_major < GLIB_MAJOR_VERSION)
271 return "GLib version too new (major mismatch)";
272 if (required_effective_micro < glib_effective_micro - GLIB_BINARY_AGE)
273 return "GLib version too new (micro mismatch)";
274 if (required_effective_micro > glib_effective_micro)
275 return "GLib version too old (micro mismatch)";
279 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
282 * @dest: the destination address to copy the bytes to.
283 * @src: the source address to copy the bytes from.
284 * @len: the number of bytes to copy.
286 * Copies a block of memory @len bytes long, from @src to @dest.
287 * The source and destination areas may overlap.
289 * In order to use this function, you must include
290 * <filename>string.h</filename> yourself, because this macro will
291 * typically simply resolve to memmove() and GLib does not include
292 * <filename>string.h</filename> for you.
295 g_memmove (gpointer dest,
299 gchar* destptr = dest;
300 const gchar* srcptr = src;
301 if (src + len < dest || dest + len < src)
303 bcopy (src, dest, len);
306 else if (dest <= src)
309 *(destptr++) = *(srcptr++);
316 *(--destptr) = *(--srcptr);
319 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
327 * @func: (scope async): the function to call on normal program termination.
329 * Specifies a function to be called at normal program termination.
331 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
332 * macro that maps to a call to the atexit() function in the C
333 * library. This means that in case the code that calls g_atexit(),
334 * i.e. atexit(), is in a DLL, the function will be called when the
335 * DLL is detached from the program. This typically makes more sense
336 * than that the function is called when the GLib DLL is detached,
337 * which happened earlier when g_atexit() was a function in the GLib
340 * The behaviour of atexit() in the context of dynamically loaded
341 * modules is not formally specified and varies wildly.
343 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
344 * loaded module which is unloaded before the program terminates might
345 * well cause a crash at program exit.
347 * Some POSIX systems implement atexit() like Windows, and have each
348 * dynamically loaded module maintain an own atexit chain that is
349 * called when the module is unloaded.
351 * On other POSIX systems, before a dynamically loaded module is
352 * unloaded, the registered atexit functions (if any) residing in that
353 * module are called, regardless where the code that registered them
354 * resided. This is presumably the most robust approach.
356 * As can be seen from the above, for portability it's best to avoid
357 * calling g_atexit() (or atexit()) except in the main executable of a
361 g_atexit (GVoidFunc func)
364 const gchar *error = NULL;
366 /* keep this in sync with glib.h */
368 #ifdef G_NATIVE_ATEXIT
369 result = ATEXIT (func);
371 error = g_strerror (errno);
372 #elif defined (HAVE_ATEXIT)
373 # ifdef NeXT /* @#%@! NeXTStep */
374 result = !atexit ((void (*)(void)) func);
376 error = g_strerror (errno);
378 result = atexit ((void (*)(void)) func);
380 error = g_strerror (errno);
382 #elif defined (HAVE_ON_EXIT)
383 result = on_exit ((void (*)(int, void *)) func, NULL);
385 error = g_strerror (errno);
388 error = "no implementation";
389 #endif /* G_NATIVE_ATEXIT */
392 g_error ("Could not register atexit() function: %s", error);
395 /* Based on execvp() from GNU Libc.
396 * Some of this code is cut-and-pasted into gspawn.c
400 my_strchrnul (const gchar *str,
403 gchar *p = (gchar*)str;
404 while (*p && (*p != c))
412 static gchar *inner_find_program_in_path (const gchar *program);
415 g_find_program_in_path (const gchar *program)
417 const gchar *last_dot = strrchr (program, '.');
419 if (last_dot == NULL ||
420 strchr (last_dot, '\\') != NULL ||
421 strchr (last_dot, '/') != NULL)
423 const gint program_length = strlen (program);
424 gchar *pathext = g_build_path (";",
425 ".exe;.cmd;.bat;.com",
426 g_getenv ("PATHEXT"),
429 gchar *decorated_program;
435 gchar *q = my_strchrnul (p, ';');
437 decorated_program = g_malloc (program_length + (q-p) + 1);
438 memcpy (decorated_program, program, program_length);
439 memcpy (decorated_program+program_length, p, q-p);
440 decorated_program [program_length + (q-p)] = '\0';
442 retval = inner_find_program_in_path (decorated_program);
443 g_free (decorated_program);
451 } while (*p++ != '\0');
456 return inner_find_program_in_path (program);
462 * g_find_program_in_path:
463 * @program: a program name in the GLib file name encoding
465 * Locates the first executable named @program in the user's path, in the
466 * same way that execvp() would locate it. Returns an allocated string
467 * with the absolute path name, or %NULL if the program is not found in
468 * the path. If @program is already an absolute path, returns a copy of
469 * @program if @program exists and is executable, and %NULL otherwise.
471 * On Windows, if @program does not have a file type suffix, tries
472 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
473 * the <envar>PATHEXT</envar> environment variable.
475 * On Windows, it looks for the file in the same way as CreateProcess()
476 * would. This means first in the directory where the executing
477 * program was loaded from, then in the current directory, then in the
478 * Windows 32-bit system directory, then in the Windows directory, and
479 * finally in the directories in the <envar>PATH</envar> environment
480 * variable. If the program is found, the return value contains the
481 * full name including the type suffix.
483 * Return value: absolute path, or %NULL
487 inner_find_program_in_path (const gchar *program)
490 g_find_program_in_path (const gchar *program)
493 const gchar *path, *p;
494 gchar *name, *freeme;
496 const gchar *path_copy;
497 gchar *filename = NULL, *appdir = NULL;
498 gchar *sysdir = NULL, *windir = NULL;
500 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
506 g_return_val_if_fail (program != NULL, NULL);
508 /* If it is an absolute path, or a relative path including subdirectories,
509 * don't look in PATH.
511 if (g_path_is_absolute (program)
512 || strchr (program, G_DIR_SEPARATOR) != NULL
514 || strchr (program, '/') != NULL
518 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
519 !g_file_test (program, G_FILE_TEST_IS_DIR))
520 return g_strdup (program);
525 path = g_getenv ("PATH");
526 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
529 /* There is no `PATH' in the environment. The default
530 * search path in GNU libc is the current directory followed by
531 * the path `confstr' returns for `_CS_PATH'.
534 /* In GLib we put . last, for security, and don't use the
535 * unportable confstr(); UNIX98 does not actually specify
536 * what to search if PATH is unset. POSIX may, dunno.
539 path = "/bin:/usr/bin:.";
542 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
543 if (n > 0 && n < MAXPATHLEN)
544 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
546 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
547 if (n > 0 && n < MAXPATHLEN)
548 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
550 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
551 if (n > 0 && n < MAXPATHLEN)
552 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
556 appdir = g_path_get_dirname (filename);
560 path = g_strdup (path);
564 const gchar *tem = path;
565 path = g_strconcat (windir, ";", path, NULL);
566 g_free ((gchar *) tem);
572 const gchar *tem = path;
573 path = g_strconcat (sysdir, ";", path, NULL);
574 g_free ((gchar *) tem);
579 const gchar *tem = path;
580 path = g_strconcat (".;", path, NULL);
581 g_free ((gchar *) tem);
586 const gchar *tem = path;
587 path = g_strconcat (appdir, ";", path, NULL);
588 g_free ((gchar *) tem);
595 len = strlen (program) + 1;
596 pathlen = strlen (path);
597 freeme = name = g_malloc (pathlen + len + 1);
599 /* Copy the file name at the top, including '\0' */
600 memcpy (name + pathlen + 1, program, len);
601 name = name + pathlen;
602 /* And add the slash before the filename */
603 *name = G_DIR_SEPARATOR;
611 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
614 /* Two adjacent colons, or a colon at the beginning or the end
615 * of `PATH' means to search the current directory.
619 startp = memcpy (name - (p - path), path, p - path);
621 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
622 !g_file_test (startp, G_FILE_TEST_IS_DIR))
625 ret = g_strdup (startp);
628 g_free ((gchar *) path_copy);
633 while (*p++ != '\0');
637 g_free ((gchar *) path_copy);
645 * @file_name: the name of the file.
647 * Gets the name of the file without any leading directory components.
648 * It returns a pointer into the given file name string.
650 * Return value: the name of the file without any leading directory components.
652 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
653 * g_path_get_basename() allocates new memory for the returned string, unlike
654 * this function which returns a pointer into the argument.
657 g_basename (const gchar *file_name)
659 register gchar *base;
661 g_return_val_if_fail (file_name != NULL, NULL);
663 base = strrchr (file_name, G_DIR_SEPARATOR);
667 gchar *q = strrchr (file_name, '/');
668 if (base == NULL || (q != NULL && q > base))
677 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
678 return (gchar*) file_name + 2;
679 #endif /* G_OS_WIN32 */
681 return (gchar*) file_name;
685 * g_path_get_basename:
686 * @file_name: the name of the file.
688 * Gets the last component of the filename. If @file_name ends with a
689 * directory separator it gets the component before the last slash. If
690 * @file_name consists only of directory separators (and on Windows,
691 * possibly a drive letter), a single separator is returned. If
692 * @file_name is empty, it gets ".".
694 * Return value: a newly allocated string containing the last component of
698 g_path_get_basename (const gchar *file_name)
700 register gssize base;
701 register gssize last_nonslash;
705 g_return_val_if_fail (file_name != NULL, NULL);
707 if (file_name[0] == '\0')
709 return g_strdup (".");
711 last_nonslash = strlen (file_name) - 1;
713 while (last_nonslash >= 0 && G_IS_DIR_SEPARATOR (file_name [last_nonslash]))
716 if (last_nonslash == -1)
717 /* string only containing slashes */
718 return g_strdup (G_DIR_SEPARATOR_S);
721 if (last_nonslash == 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
722 /* string only containing slashes and a drive */
723 return g_strdup (G_DIR_SEPARATOR_S);
724 #endif /* G_OS_WIN32 */
726 base = last_nonslash;
728 while (base >=0 && !G_IS_DIR_SEPARATOR (file_name [base]))
732 if (base == -1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
734 #endif /* G_OS_WIN32 */
736 len = last_nonslash - base;
737 retval = g_malloc (len + 1);
738 memcpy (retval, file_name + base + 1, len);
744 * g_path_is_absolute:
745 * @file_name: a file name.
747 * Returns %TRUE if the given @file_name is an absolute file name.
748 * Note that this is a somewhat vague concept on Windows.
750 * On POSIX systems, an absolute file name is well-defined. It always
751 * starts from the single root directory. For example "/usr/local".
753 * On Windows, the concepts of current drive and drive-specific
754 * current directory introduce vagueness. This function interprets as
755 * an absolute file name one that either begins with a directory
756 * separator such as "\Users\tml" or begins with the root on a drive,
757 * for example "C:\Windows". The first case also includes UNC paths
758 * such as "\\myserver\docs\foo". In all cases, either slashes or
759 * backslashes are accepted.
761 * Note that a file name relative to the current drive root does not
762 * truly specify a file uniquely over time and across processes, as
763 * the current drive is a per-process value and can be changed.
765 * File names relative the current directory on some specific drive,
766 * such as "D:foo/bar", are not interpreted as absolute by this
767 * function, but they obviously are not relative to the normal current
768 * directory as returned by getcwd() or g_get_current_dir()
769 * either. Such paths should be avoided, or need to be handled using
770 * Windows-specific code.
772 * Returns: %TRUE if @file_name is absolute.
775 g_path_is_absolute (const gchar *file_name)
777 g_return_val_if_fail (file_name != NULL, FALSE);
779 if (G_IS_DIR_SEPARATOR (file_name[0]))
783 /* Recognize drive letter on native Windows */
784 if (g_ascii_isalpha (file_name[0]) &&
785 file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
787 #endif /* G_OS_WIN32 */
794 * @file_name: a file name.
796 * Returns a pointer into @file_name after the root component, i.e. after
797 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
798 * path it returns %NULL.
800 * Returns: a pointer into @file_name after the root component.
803 g_path_skip_root (const gchar *file_name)
805 g_return_val_if_fail (file_name != NULL, NULL);
807 #ifdef G_PLATFORM_WIN32
808 /* Skip \\server\share or //server/share */
809 if (G_IS_DIR_SEPARATOR (file_name[0]) &&
810 G_IS_DIR_SEPARATOR (file_name[1]) &&
812 !G_IS_DIR_SEPARATOR (file_name[2]))
816 p = strchr (file_name + 2, G_DIR_SEPARATOR);
819 gchar *q = strchr (file_name + 2, '/');
820 if (p == NULL || (q != NULL && q < p))
830 while (file_name[0] && !G_IS_DIR_SEPARATOR (file_name[0]))
833 /* Possibly skip a backslash after the share name */
834 if (G_IS_DIR_SEPARATOR (file_name[0]))
837 return (gchar *)file_name;
842 /* Skip initial slashes */
843 if (G_IS_DIR_SEPARATOR (file_name[0]))
845 while (G_IS_DIR_SEPARATOR (file_name[0]))
847 return (gchar *)file_name;
852 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':' && G_IS_DIR_SEPARATOR (file_name[2]))
853 return (gchar *)file_name + 3;
861 * @mask: a #gulong containing flags
862 * @nth_bit: the index of the bit to start the search from
864 * Find the position of the first bit set in @mask, searching
865 * from (but not including) @nth_bit upwards. Bits are numbered
866 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
867 * usually). To start searching from the 0th bit, set @nth_bit to -1.
869 * Returns: the index of the first bit set which is higher than @nth_bit
874 * @mask: a #gulong containing flags
875 * @nth_bit: the index of the bit to start the search from
877 * Find the position of the first bit set in @mask, searching
878 * from (but not including) @nth_bit downwards. Bits are numbered
879 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
880 * usually). To start searching from the last bit, set @nth_bit to
881 * -1 or GLIB_SIZEOF_LONG * 8.
883 * Returns: the index of the first bit set which is lower than @nth_bit
890 * Gets the number of bits used to hold @number,
891 * e.g. if @number is 4, 3 bits are needed.
893 * Returns: the number of bits used to hold @number
898 * @file_name: the name of the file
900 * Gets the directory components of a file name.
901 * If the file name has no directory components "." is returned.
902 * The returned string should be freed when no longer needed.
904 * Returns: the directory components of the file
906 * Deprecated: use g_path_get_dirname() instead
910 * g_path_get_dirname:
911 * @file_name: the name of the file.
913 * Gets the directory components of a file name. If the file name has no
914 * directory components "." is returned. The returned string should be
915 * freed when no longer needed.
917 * Returns: the directory components of the file.
920 g_path_get_dirname (const gchar *file_name)
922 register gchar *base;
925 g_return_val_if_fail (file_name != NULL, NULL);
927 base = strrchr (file_name, G_DIR_SEPARATOR);
930 gchar *q = strrchr (file_name, '/');
931 if (base == NULL || (q != NULL && q > base))
938 if (g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
940 gchar drive_colon_dot[4];
942 drive_colon_dot[0] = file_name[0];
943 drive_colon_dot[1] = ':';
944 drive_colon_dot[2] = '.';
945 drive_colon_dot[3] = '\0';
947 return g_strdup (drive_colon_dot);
950 return g_strdup (".");
953 while (base > file_name && G_IS_DIR_SEPARATOR (*base))
957 /* base points to the char before the last slash.
959 * In case file_name is the root of a drive (X:\) or a child of the
960 * root of a drive (X:\foo), include the slash.
962 * In case file_name is the root share of an UNC path
963 * (\\server\share), add a slash, returning \\server\share\ .
965 * In case file_name is a direct child of a share in an UNC path
966 * (\\server\share\foo), include the slash after the share name,
967 * returning \\server\share\ .
969 if (base == file_name + 1 && g_ascii_isalpha (file_name[0]) && file_name[1] == ':')
971 else if (G_IS_DIR_SEPARATOR (file_name[0]) &&
972 G_IS_DIR_SEPARATOR (file_name[1]) &&
974 !G_IS_DIR_SEPARATOR (file_name[2]) &&
975 base >= file_name + 2)
977 const gchar *p = file_name + 2;
978 while (*p && !G_IS_DIR_SEPARATOR (*p))
982 len = (guint) strlen (file_name) + 1;
983 base = g_new (gchar, len + 1);
984 strcpy (base, file_name);
985 base[len-1] = G_DIR_SEPARATOR;
989 if (G_IS_DIR_SEPARATOR (*p))
992 while (*p && !G_IS_DIR_SEPARATOR (*p))
1000 len = (guint) 1 + base - file_name;
1002 base = g_new (gchar, len + 1);
1003 g_memmove (base, file_name, len);
1010 * g_get_current_dir:
1012 * Gets the current directory.
1013 * The returned string should be freed when no longer needed. The encoding
1014 * of the returned string is system defined. On Windows, it is always UTF-8.
1016 * Returns: the current directory.
1019 g_get_current_dir (void)
1024 wchar_t dummy[2], *wdir;
1027 len = GetCurrentDirectoryW (2, dummy);
1028 wdir = g_new (wchar_t, len);
1030 if (GetCurrentDirectoryW (len, wdir) == len - 1)
1031 dir = g_utf16_to_utf8 (wdir, -1, NULL, NULL, NULL);
1036 dir = g_strdup ("\\");
1042 gchar *buffer = NULL;
1044 static gulong max_len = 0;
1047 max_len = (G_PATH_LENGTH == -1) ? 2048 : G_PATH_LENGTH;
1049 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
1050 * and, if that wasn't bad enough, hangs in doing so.
1052 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
1053 buffer = g_new (gchar, max_len + 1);
1055 dir = getwd (buffer);
1056 #else /* !sun || !HAVE_GETCWD */
1057 while (max_len < G_MAXULONG / 2)
1060 buffer = g_new (gchar, max_len + 1);
1062 dir = getcwd (buffer, max_len);
1064 if (dir || errno != ERANGE)
1069 #endif /* !sun || !HAVE_GETCWD */
1071 if (!dir || !*buffer)
1073 /* hm, should we g_error() out here?
1074 * this can happen if e.g. "./" has mode \0000
1076 buffer[0] = G_DIR_SEPARATOR;
1080 dir = g_strdup (buffer);
1089 * @variable: the environment variable to get, in the GLib file name encoding.
1091 * Returns the value of an environment variable. The name and value
1092 * are in the GLib file name encoding. On UNIX, this means the actual
1093 * bytes which might or might not be in some consistent character set
1094 * and encoding. On Windows, it is in UTF-8. On Windows, in case the
1095 * environment variable's value contains references to other
1096 * environment variables, they are expanded.
1098 * Return value: the value of the environment variable, or %NULL if
1099 * the environment variable is not found. The returned string may be
1100 * overwritten by the next call to g_getenv(), g_setenv() or
1104 g_getenv (const gchar *variable)
1108 g_return_val_if_fail (variable != NULL, NULL);
1110 return getenv (variable);
1112 #else /* G_OS_WIN32 */
1116 wchar_t dummy[2], *wname, *wvalue;
1119 g_return_val_if_fail (variable != NULL, NULL);
1120 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), NULL);
1122 /* On Windows NT, it is relatively typical that environment
1123 * variables contain references to other environment variables. If
1124 * so, use ExpandEnvironmentStrings(). (In an ideal world, such
1125 * environment variables would be stored in the Registry as
1126 * REG_EXPAND_SZ type values, and would then get automatically
1127 * expanded before a program sees them. But there is broken software
1128 * that stores environment variables as REG_SZ values even if they
1129 * contain references to other environment variables.)
1132 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1134 len = GetEnvironmentVariableW (wname, dummy, 2);
1144 wvalue = g_new (wchar_t, len);
1146 if (GetEnvironmentVariableW (wname, wvalue, len) != len - 1)
1153 if (wcschr (wvalue, L'%') != NULL)
1155 wchar_t *tem = wvalue;
1157 len = ExpandEnvironmentStringsW (wvalue, dummy, 2);
1161 wvalue = g_new (wchar_t, len);
1163 if (ExpandEnvironmentStringsW (tem, wvalue, len) != len)
1173 value = g_utf16_to_utf8 (wvalue, -1, NULL, NULL, NULL);
1178 quark = g_quark_from_string (value);
1181 return g_quark_to_string (quark);
1183 #endif /* G_OS_WIN32 */
1186 /* _g_getenv_nomalloc
1187 * this function does a getenv() without doing any kind of allocation
1188 * through glib. it's suitable for chars <= 127 only (both, for the
1189 * variable name and the contents) and for contents < 1024 chars in
1190 * length. also, it aliases "" to a NULL return value.
1193 _g_getenv_nomalloc (const gchar *variable,
1196 const gchar *retval = getenv (variable);
1197 if (retval && retval[0])
1199 gint l = strlen (retval);
1202 strncpy (buffer, retval, l);
1212 * @variable: the environment variable to set, must not contain '='.
1213 * @value: the value for to set the variable to.
1214 * @overwrite: whether to change the variable if it already exists.
1216 * Sets an environment variable. Both the variable's name and value
1217 * should be in the GLib file name encoding. On UNIX, this means that
1218 * they can be any sequence of bytes. On Windows, they should be in
1221 * Note that on some systems, when variables are overwritten, the memory
1222 * used for the previous variables and its value isn't reclaimed.
1225 * Environment variable handling in UNIX is not thread-safe, and your
1226 * program may crash if one thread calls g_setenv() while another
1227 * thread is calling getenv(). (And note that many functions, such as
1228 * gettext(), call getenv() internally.) This function is only safe to
1229 * use at the very start of your program, before creating any other
1230 * threads (or creating objects that create worker threads of their
1234 * Returns: %FALSE if the environment variable couldn't be set.
1239 g_setenv (const gchar *variable,
1250 g_return_val_if_fail (variable != NULL, FALSE);
1251 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1254 result = setenv (variable, value, overwrite);
1256 if (!overwrite && getenv (variable) != NULL)
1259 /* This results in a leak when you overwrite existing
1260 * settings. It would be fairly easy to fix this by keeping
1261 * our own parallel array or hash table.
1263 string = g_strconcat (variable, "=", value, NULL);
1264 result = putenv (string);
1268 #else /* G_OS_WIN32 */
1271 wchar_t *wname, *wvalue, *wassignment;
1274 g_return_val_if_fail (variable != NULL, FALSE);
1275 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1276 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1277 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1279 if (!overwrite && g_getenv (variable) != NULL)
1282 /* We want to (if possible) set both the environment variable copy
1283 * kept by the C runtime and the one kept by the system.
1285 * We can't use only the C runtime's putenv or _wputenv() as that
1286 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1287 * (with main() and not wmain()). In a "main()" app the C runtime
1288 * initializes the C runtime's environment table by converting the
1289 * real (wide char) environment variables to system codepage, thus
1290 * breaking those that aren't representable in the system codepage.
1292 * As the C runtime's putenv() will also set the system copy, we do
1293 * the putenv() first, then call SetEnvironmentValueW ourselves.
1296 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1297 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1298 tem = g_strconcat (variable, "=", value, NULL);
1299 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1302 _wputenv (wassignment);
1303 g_free (wassignment);
1305 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1312 #endif /* G_OS_WIN32 */
1315 #ifdef HAVE__NSGETENVIRON
1316 #define environ (*_NSGetEnviron())
1317 #elif !defined(G_OS_WIN32)
1319 /* According to the Single Unix Specification, environ is not in
1320 * any system header, although unistd.h often declares it.
1322 extern char **environ;
1327 * @variable: the environment variable to remove, must not contain '='.
1329 * Removes an environment variable from the environment.
1331 * Note that on some systems, when variables are overwritten, the memory
1332 * used for the previous variables and its value isn't reclaimed.
1335 * Environment variable handling in UNIX is not thread-safe, and your
1336 * program may crash if one thread calls g_unsetenv() while another
1337 * thread is calling getenv(). (And note that many functions, such as
1338 * gettext(), call getenv() internally.) This function is only safe to
1339 * use at the very start of your program, before creating any other
1340 * threads (or creating objects that create worker threads of their
1347 g_unsetenv (const gchar *variable)
1351 #ifdef HAVE_UNSETENV
1352 g_return_if_fail (variable != NULL);
1353 g_return_if_fail (strchr (variable, '=') == NULL);
1355 unsetenv (variable);
1356 #else /* !HAVE_UNSETENV */
1360 g_return_if_fail (variable != NULL);
1361 g_return_if_fail (strchr (variable, '=') == NULL);
1363 len = strlen (variable);
1365 /* Mess directly with the environ array.
1366 * This seems to be the only portable way to do this.
1368 * Note that we remove *all* environment entries for
1369 * the variable name, not just the first.
1374 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1382 #endif /* !HAVE_UNSETENV */
1384 #else /* G_OS_WIN32 */
1386 wchar_t *wname, *wassignment;
1389 g_return_if_fail (variable != NULL);
1390 g_return_if_fail (strchr (variable, '=') == NULL);
1391 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1393 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1394 tem = g_strconcat (variable, "=", NULL);
1395 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1398 _wputenv (wassignment);
1399 g_free (wassignment);
1401 SetEnvironmentVariableW (wname, NULL);
1405 #endif /* G_OS_WIN32 */
1411 * Gets the names of all variables set in the environment.
1413 * Returns: (array zero-terminated=1) (transfer full): a %NULL-terminated list of strings which must be freed
1414 * with g_strfreev().
1416 * Programs that want to be portable to Windows should typically use
1417 * this function and g_getenv() instead of using the environ array
1418 * from the C library directly. On Windows, the strings in the environ
1419 * array are in system codepage encoding, while in most of the typical
1420 * use cases for environment variables in GLib-using programs you want
1421 * the UTF-8 encoding that this function and g_getenv() provide.
1429 gchar **result, *eq;
1432 len = g_strv_length (environ);
1433 result = g_new0 (gchar *, len + 1);
1436 for (i = 0; i < len; i++)
1438 eq = strchr (environ[i], '=');
1440 result[j++] = g_strndup (environ[i], eq - environ[i]);
1447 gchar **result, *eq;
1451 p = (wchar_t *) GetEnvironmentStringsW ();
1457 q += wcslen (q) + 1;
1461 result = g_new0 (gchar *, len + 1);
1467 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1468 if (result[j] != NULL)
1470 eq = strchr (result[j], '=');
1471 if (eq && eq > result[j])
1479 q += wcslen (q) + 1;
1482 FreeEnvironmentStringsW (p);
1491 * Gets the list of environment variables for the current process. The
1492 * list is %NULL terminated and each item in the list is of the form
1495 * This is equivalent to direct access to the 'environ' global variable,
1498 * The return value is freshly allocated and it should be freed with
1499 * g_strfreev() when it is no longer needed.
1501 * Returns: (array zero-terminated=1) (transfer full): the list of environment variables
1506 g_get_environ (void)
1509 return g_strdupv (environ);
1515 strings = GetEnvironmentStringsW ();
1516 for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1517 result = g_new (char *, n + 1);
1518 for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1519 result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1520 FreeEnvironmentStringsW (strings);
1527 G_LOCK_DEFINE_STATIC (g_utils_global);
1529 static gchar *g_tmp_dir = NULL;
1530 static gchar *g_user_name = NULL;
1531 static gchar *g_real_name = NULL;
1532 static gchar *g_home_dir = NULL;
1533 static gchar *g_host_name = NULL;
1536 /* System codepage versions of the above, kept at file level so that they,
1537 * too, are produced only once.
1539 static gchar *g_tmp_dir_cp = NULL;
1540 static gchar *g_user_name_cp = NULL;
1541 static gchar *g_real_name_cp = NULL;
1542 static gchar *g_home_dir_cp = NULL;
1545 static gchar *g_user_data_dir = NULL;
1546 static gchar **g_system_data_dirs = NULL;
1547 static gchar *g_user_cache_dir = NULL;
1548 static gchar *g_user_config_dir = NULL;
1549 static gchar **g_system_config_dirs = NULL;
1551 static gchar **g_user_special_dirs = NULL;
1553 /* fifteen minutes of fame for everybody */
1554 #define G_USER_DIRS_EXPIRE 15 * 60
1559 get_special_folder (int csidl)
1561 wchar_t path[MAX_PATH+1];
1563 LPITEMIDLIST pidl = NULL;
1565 gchar *retval = NULL;
1567 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1570 b = SHGetPathFromIDListW (pidl, path);
1572 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1573 CoTaskMemFree (pidl);
1579 get_windows_directory_root (void)
1581 wchar_t wwindowsdir[MAX_PATH];
1583 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1585 /* Usually X:\Windows, but in terminal server environments
1586 * might be an UNC path, AFAIK.
1588 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1591 if (windowsdir == NULL)
1592 return g_strdup ("C:\\");
1594 p = (char *) g_path_skip_root (windowsdir);
1595 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1601 return g_strdup ("C:\\");
1606 /* HOLDS: g_utils_global_lock */
1608 g_get_any_init_do (void)
1610 gchar hostname[100];
1612 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1613 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1614 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1615 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1616 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1619 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1620 g_tmp_dir = get_windows_directory_root ();
1623 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1626 g_tmp_dir = g_strdup (P_tmpdir);
1627 k = strlen (g_tmp_dir);
1628 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1629 g_tmp_dir[k - 1] = '\0';
1633 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1635 g_tmp_dir = g_strdup ("/tmp");
1637 #endif /* !G_OS_WIN32 */
1640 /* We check $HOME first for Win32, though it is a last resort for Unix
1641 * where we prefer the results of getpwuid().
1643 g_home_dir = g_strdup (g_getenv ("HOME"));
1645 /* Only believe HOME if it is an absolute path and exists */
1648 if (!(g_path_is_absolute (g_home_dir) &&
1649 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1651 g_free (g_home_dir);
1656 /* In case HOME is Unix-style (it happens), convert it to
1662 while ((p = strchr (g_home_dir, '/')) != NULL)
1668 /* USERPROFILE is probably the closest equivalent to $HOME? */
1669 if (g_getenv ("USERPROFILE") != NULL)
1670 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1674 g_home_dir = get_special_folder (CSIDL_PROFILE);
1677 g_home_dir = get_windows_directory_root ();
1678 #endif /* G_OS_WIN32 */
1682 struct passwd *pw = NULL;
1683 gpointer buffer = NULL;
1687 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1689 # ifdef _SC_GETPW_R_SIZE_MAX
1690 /* This reurns the maximum length */
1691 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1695 # else /* _SC_GETPW_R_SIZE_MAX */
1697 # endif /* _SC_GETPW_R_SIZE_MAX */
1699 logname = (gchar *) g_getenv ("LOGNAME");
1704 /* we allocate 6 extra bytes to work around a bug in
1705 * Mac OS < 10.3. See #156446
1707 buffer = g_malloc (bufsize + 6);
1710 # ifdef HAVE_POSIX_GETPWUID_R
1712 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1713 if (!pw || (pw->pw_uid != getuid ())) {
1714 /* LOGNAME is lying, fall back to looking up the uid */
1715 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1718 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1720 error = error < 0 ? errno : error;
1721 # else /* HAVE_NONPOSIX_GETPWUID_R */
1722 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1723 # if defined(_AIX) || defined(__hpux)
1724 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1725 pw = error == 0 ? &pwd : NULL;
1728 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1729 if (!pw || (pw->pw_uid != getuid ())) {
1730 /* LOGNAME is lying, fall back to looking up the uid */
1731 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1734 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1736 error = pw ? 0 : errno;
1738 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1742 /* we bail out prematurely if the user id can't be found
1743 * (should be pretty rare case actually), or if the buffer
1744 * should be sufficiently big and lookups are still not
1747 if (error == 0 || error == ENOENT)
1749 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1750 (gulong) getuid ());
1753 if (bufsize > 32 * 1024)
1755 g_warning ("getpwuid_r(): failed due to: %s.",
1756 g_strerror (error));
1764 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1769 pw = getpwuid (getuid ());
1774 g_user_name = g_strdup (pw->pw_name);
1776 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1778 gchar **gecos_fields;
1781 /* split the gecos field and substitute '&' */
1782 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1783 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1784 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1785 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1786 g_strfreev (gecos_fields);
1787 g_strfreev (name_parts);
1791 g_home_dir = g_strdup (pw->pw_dir);
1796 #else /* !HAVE_PWD_H */
1800 guint len = UNLEN+1;
1801 wchar_t buffer[UNLEN+1];
1803 if (GetUserNameW (buffer, (LPDWORD) &len))
1805 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1806 g_real_name = g_strdup (g_user_name);
1809 #endif /* G_OS_WIN32 */
1811 #endif /* !HAVE_PWD_H */
1815 g_home_dir = g_strdup (g_getenv ("HOME"));
1819 /* change '\\' in %HOME% to '/' */
1820 g_strdelimit (g_home_dir, "\\",'/');
1823 g_user_name = g_strdup ("somebody");
1825 g_real_name = g_strdup ("Unknown");
1829 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1831 DWORD size = sizeof (hostname);
1832 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1834 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1838 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1839 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1840 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1843 g_tmp_dir_cp = g_strdup ("\\");
1844 if (!g_user_name_cp)
1845 g_user_name_cp = g_strdup ("somebody");
1846 if (!g_real_name_cp)
1847 g_real_name_cp = g_strdup ("Unknown");
1849 /* home_dir might be NULL, unlike tmp_dir, user_name and
1853 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
1855 g_home_dir_cp = NULL;
1856 #endif /* G_OS_WIN32 */
1860 g_get_any_init (void)
1863 g_get_any_init_do ();
1867 g_get_any_init_locked (void)
1869 G_LOCK (g_utils_global);
1871 G_UNLOCK (g_utils_global);
1878 * Gets the user name of the current user. The encoding of the returned
1879 * string is system-defined. On UNIX, it might be the preferred file name
1880 * encoding, or something else, and there is no guarantee that it is even
1881 * consistent on a machine. On Windows, it is always UTF-8.
1883 * Returns: the user name of the current user.
1886 g_get_user_name (void)
1888 g_get_any_init_locked ();
1895 * Gets the real name of the user. This usually comes from the user's entry
1896 * in the <filename>passwd</filename> file. The encoding of the returned
1897 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1898 * If the real user name cannot be determined, the string "Unknown" is
1901 * Returns: the user's real name.
1904 g_get_real_name (void)
1906 g_get_any_init_locked ();
1913 * Gets the current user's home directory as defined in the
1914 * password database.
1916 * Note that in contrast to traditional UNIX tools, this function
1917 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1918 * environment variable.
1920 * One of the reasons for this decision is that applications in many
1921 * cases need special handling to deal with the case where
1922 * <envar>HOME</envar> is
1924 * <member>Not owned by the user</member>
1925 * <member>Not writeable</member>
1926 * <member>Not even readable</member>
1928 * Since applications are in general <emphasis>not</emphasis> written
1929 * to deal with these situations it was considered better to make
1930 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1931 * return the real home directory for the user. If applications
1932 * want to pay attention to <envar>HOME</envar>, they can do:
1934 * const char *homedir = g_getenv ("HOME");
1936 * homedir = g_get_home_dir (<!-- -->);
1939 * Returns: the current user's home directory
1942 g_get_home_dir (void)
1944 g_get_any_init_locked ();
1951 * Gets the directory to use for temporary files. This is found from
1952 * inspecting the environment variables <envar>TMPDIR</envar>,
1953 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1954 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1955 * The encoding of the returned string is system-defined. On Windows,
1956 * it is always UTF-8. The return value is never %NULL or the empty string.
1958 * Returns: the directory to use for temporary files.
1961 g_get_tmp_dir (void)
1963 g_get_any_init_locked ();
1970 * Return a name for the machine.
1972 * The returned name is not necessarily a fully-qualified domain name,
1973 * or even present in DNS or some other name service at all. It need
1974 * not even be unique on your local network or site, but usually it
1975 * is. Callers should not rely on the return value having any specific
1976 * properties like uniqueness for security purposes. Even if the name
1977 * of the machine is changed while an application is running, the
1978 * return value from this function does not change. The returned
1979 * string is owned by GLib and should not be modified or freed. If no
1980 * name can be determined, a default fixed string "localhost" is
1983 * Returns: the host name of the machine.
1988 g_get_host_name (void)
1990 g_get_any_init_locked ();
1994 G_LOCK_DEFINE_STATIC (g_prgname);
1995 static gchar *g_prgname = NULL;
2000 * Gets the name of the program. This name should <emphasis>not</emphasis>
2001 * be localized, contrast with g_get_application_name().
2002 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
2003 * which is called by gtk_init(). The program name is found by taking
2004 * the last component of <literal>argv[0]</literal>.)
2006 * Returns: the name of the program. The returned string belongs
2007 * to GLib and must not be modified or freed.
2010 g_get_prgname (void)
2016 if (g_prgname == NULL)
2018 static gboolean beenhere = FALSE;
2022 gchar *utf8_buf = NULL;
2023 wchar_t buf[MAX_PATH+1];
2026 if (GetModuleFileNameW (GetModuleHandle (NULL),
2027 buf, G_N_ELEMENTS (buf)) > 0)
2028 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2032 g_prgname = g_path_get_basename (utf8_buf);
2039 G_UNLOCK (g_prgname);
2046 * @prgname: the name of the program.
2048 * Sets the name of the program. This name should <emphasis>not</emphasis>
2049 * be localized, contrast with g_set_application_name(). Note that for
2050 * thread-safety reasons this function can only be called once.
2053 g_set_prgname (const gchar *prgname)
2057 g_prgname = g_strdup (prgname);
2058 G_UNLOCK (g_prgname);
2061 G_LOCK_DEFINE_STATIC (g_application_name);
2062 static gchar *g_application_name = NULL;
2065 * g_get_application_name:
2067 * Gets a human-readable name for the application, as set by
2068 * g_set_application_name(). This name should be localized if
2069 * possible, and is intended for display to the user. Contrast with
2070 * g_get_prgname(), which gets a non-localized name. If
2071 * g_set_application_name() has not been called, returns the result of
2072 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2075 * Return value: human-readable application name. may return %NULL
2080 g_get_application_name (void)
2084 G_LOCK (g_application_name);
2085 retval = g_application_name;
2086 G_UNLOCK (g_application_name);
2089 return g_get_prgname ();
2095 * g_set_application_name:
2096 * @application_name: localized name of the application
2098 * Sets a human-readable name for the application. This name should be
2099 * localized if possible, and is intended for display to the user.
2100 * Contrast with g_set_prgname(), which sets a non-localized name.
2101 * g_set_prgname() will be called automatically by gtk_init(),
2102 * but g_set_application_name() will not.
2104 * Note that for thread safety reasons, this function can only
2107 * The application name will be used in contexts such as error messages,
2108 * or when displaying an application's name in the task list.
2113 g_set_application_name (const gchar *application_name)
2115 gboolean already_set = FALSE;
2117 G_LOCK (g_application_name);
2118 if (g_application_name)
2121 g_application_name = g_strdup (application_name);
2122 G_UNLOCK (g_application_name);
2125 g_warning ("g_set_application_name() called multiple times");
2129 * g_get_user_data_dir:
2131 * Returns a base directory in which to access application data such
2132 * as icons that is customized for a particular user.
2134 * On UNIX platforms this is determined using the mechanisms described in
2135 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2136 * XDG Base Directory Specification</ulink>.
2137 * In this case the directory retrieved will be XDG_DATA_HOME.
2139 * On Windows this is the folder to use for local (as opposed to
2140 * roaming) application data. See documentation for
2141 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2142 * what g_get_user_config_dir() returns.
2144 * Return value: a string owned by GLib that must not be modified
2149 g_get_user_data_dir (void)
2153 G_LOCK (g_utils_global);
2155 if (!g_user_data_dir)
2158 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2160 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2162 if (data_dir && data_dir[0])
2163 data_dir = g_strdup (data_dir);
2165 if (!data_dir || !data_dir[0])
2170 data_dir = g_build_filename (g_home_dir, ".local",
2173 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2177 g_user_data_dir = data_dir;
2180 data_dir = g_user_data_dir;
2182 G_UNLOCK (g_utils_global);
2188 g_init_user_config_dir (void)
2192 if (!g_user_config_dir)
2195 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2197 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2199 if (config_dir && config_dir[0])
2200 config_dir = g_strdup (config_dir);
2202 if (!config_dir || !config_dir[0])
2207 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2209 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2212 g_user_config_dir = config_dir;
2217 * g_get_user_config_dir:
2219 * Returns a base directory in which to store user-specific application
2220 * configuration information such as user preferences and settings.
2222 * On UNIX platforms this is determined using the mechanisms described in
2223 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2224 * XDG Base Directory Specification</ulink>.
2225 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2227 * On Windows this is the folder to use for local (as opposed to
2228 * roaming) application data. See documentation for
2229 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2230 * what g_get_user_data_dir() returns.
2232 * Return value: a string owned by GLib that must not be modified
2237 g_get_user_config_dir (void)
2239 G_LOCK (g_utils_global);
2241 g_init_user_config_dir ();
2243 G_UNLOCK (g_utils_global);
2245 return g_user_config_dir;
2249 * g_get_user_cache_dir:
2251 * Returns a base directory in which to store non-essential, cached
2252 * data specific to particular user.
2254 * On UNIX platforms this is determined using the mechanisms described in
2255 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2256 * XDG Base Directory Specification</ulink>.
2257 * In this case the directory retrieved will be XDG_CACHE_HOME.
2259 * On Windows is the directory that serves as a common repository for
2260 * temporary Internet files. A typical path is
2261 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2262 * See documentation for CSIDL_INTERNET_CACHE.
2264 * Return value: a string owned by GLib that must not be modified
2269 g_get_user_cache_dir (void)
2273 G_LOCK (g_utils_global);
2275 if (!g_user_cache_dir)
2278 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2280 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2282 if (cache_dir && cache_dir[0])
2283 cache_dir = g_strdup (cache_dir);
2285 if (!cache_dir || !cache_dir[0])
2290 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2292 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2294 g_user_cache_dir = cache_dir;
2297 cache_dir = g_user_cache_dir;
2299 G_UNLOCK (g_utils_global);
2305 * g_get_user_runtime_dir:
2307 * Returns a directory that is unique to the current user on the local
2310 * On UNIX platforms this is determined using the mechanisms described in
2311 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2312 * XDG Base Directory Specification</ulink>. This is the directory
2313 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2314 * In the case that this variable is not set, GLib will issue a warning
2315 * message to stderr and return the value of g_get_user_cache_dir().
2317 * On Windows this is the folder to use for local (as opposed to
2318 * roaming) application data. See documentation for
2319 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2320 * what g_get_user_config_dir() returns.
2322 * Returns: a string owned by GLib that must not be modified or freed.
2327 g_get_user_runtime_dir (void)
2330 static const gchar *runtime_dir;
2331 static gsize initialised;
2333 if (g_once_init_enter (&initialised))
2335 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2337 g_once_init_leave (&initialised, 1);
2343 /* Both fallback for UNIX and the default
2344 * in Windows: use the user cache directory.
2348 return g_get_user_cache_dir ();
2354 find_folder (OSType type)
2356 gchar *filename = NULL;
2359 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2361 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2365 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2369 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2373 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2375 CFStringGetCString (path, filename,
2376 CFStringGetLength (path) * 3 + 1,
2377 kCFStringEncodingUTF8);
2391 load_user_special_dirs (void)
2393 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2394 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2395 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2396 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2397 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2398 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2399 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2400 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2403 #endif /* HAVE_CARBON */
2405 #if defined(G_OS_WIN32)
2407 load_user_special_dirs (void)
2409 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2413 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2415 static const GUID FOLDERID_Downloads =
2416 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2417 static const GUID FOLDERID_Public =
2418 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2422 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2423 "SHGetKnownFolderPath");
2425 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2426 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2428 if (p_SHGetKnownFolderPath == NULL)
2430 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2435 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2438 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2439 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2440 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2441 CoTaskMemFree (wcp);
2444 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2447 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2448 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2450 if (p_SHGetKnownFolderPath == NULL)
2453 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2458 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2461 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2462 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2463 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2464 CoTaskMemFree (wcp);
2467 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2470 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2471 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2473 #endif /* G_OS_WIN32 */
2475 static void g_init_user_config_dir (void);
2477 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2479 /* adapted from xdg-user-dir-lookup.c
2481 * Copyright (C) 2007 Red Hat Inc.
2483 * Permission is hereby granted, free of charge, to any person
2484 * obtaining a copy of this software and associated documentation files
2485 * (the "Software"), to deal in the Software without restriction,
2486 * including without limitation the rights to use, copy, modify, merge,
2487 * publish, distribute, sublicense, and/or sell copies of the Software,
2488 * and to permit persons to whom the Software is furnished to do so,
2489 * subject to the following conditions:
2491 * The above copyright notice and this permission notice shall be
2492 * included in all copies or substantial portions of the Software.
2494 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2495 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2496 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2497 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2498 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2499 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2500 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2504 load_user_special_dirs (void)
2511 g_init_user_config_dir ();
2512 config_file = g_build_filename (g_user_config_dir,
2516 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2518 g_free (config_file);
2522 lines = g_strsplit (data, "\n", -1);
2523 n_lines = g_strv_length (lines);
2526 for (i = 0; i < n_lines; i++)
2528 gchar *buffer = lines[i];
2531 gboolean is_relative = FALSE;
2532 GUserDirectory directory;
2534 /* Remove newline at end */
2535 len = strlen (buffer);
2536 if (len > 0 && buffer[len - 1] == '\n')
2537 buffer[len - 1] = 0;
2540 while (*p == ' ' || *p == '\t')
2543 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2545 directory = G_USER_DIRECTORY_DESKTOP;
2546 p += strlen ("XDG_DESKTOP_DIR");
2548 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2550 directory = G_USER_DIRECTORY_DOCUMENTS;
2551 p += strlen ("XDG_DOCUMENTS_DIR");
2553 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2555 directory = G_USER_DIRECTORY_DOWNLOAD;
2556 p += strlen ("XDG_DOWNLOAD_DIR");
2558 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2560 directory = G_USER_DIRECTORY_MUSIC;
2561 p += strlen ("XDG_MUSIC_DIR");
2563 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2565 directory = G_USER_DIRECTORY_PICTURES;
2566 p += strlen ("XDG_PICTURES_DIR");
2568 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2570 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2571 p += strlen ("XDG_PUBLICSHARE_DIR");
2573 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2575 directory = G_USER_DIRECTORY_TEMPLATES;
2576 p += strlen ("XDG_TEMPLATES_DIR");
2578 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2580 directory = G_USER_DIRECTORY_VIDEOS;
2581 p += strlen ("XDG_VIDEOS_DIR");
2586 while (*p == ' ' || *p == '\t')
2593 while (*p == ' ' || *p == '\t')
2600 if (strncmp (p, "$HOME", 5) == 0)
2608 d = strrchr (p, '"');
2615 /* remove trailing slashes */
2617 if (d[len - 1] == '/')
2623 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2626 g_user_special_dirs[directory] = g_strdup (d);
2630 g_free (config_file);
2633 #endif /* G_OS_UNIX && !HAVE_CARBON */
2637 * g_reload_user_special_dirs_cache:
2639 * Resets the cache used for g_get_user_special_dir(), so
2640 * that the latest on-disk version is used. Call this only
2641 * if you just changed the data on disk yourself.
2643 * Due to threadsafety issues this may cause leaking of strings
2644 * that were previously returned from g_get_user_special_dir()
2645 * that can't be freed. We ensure to only leak the data for
2646 * the directories that actually changed value though.
2651 g_reload_user_special_dirs_cache (void)
2655 G_LOCK (g_utils_global);
2657 if (g_user_special_dirs != NULL)
2659 /* save a copy of the pointer, to check if some memory can be preserved */
2660 char **old_g_user_special_dirs = g_user_special_dirs;
2663 /* recreate and reload our cache */
2664 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2665 load_user_special_dirs ();
2667 /* only leak changed directories */
2668 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2670 old_val = old_g_user_special_dirs[i];
2671 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2674 g_free (g_user_special_dirs[i]);
2675 g_user_special_dirs[i] = old_val;
2681 /* free the old array */
2682 g_free (old_g_user_special_dirs);
2685 G_UNLOCK (g_utils_global);
2689 * g_get_user_special_dir:
2690 * @directory: the logical id of special directory
2692 * Returns the full path of a special directory using its logical id.
2694 * On Unix this is done using the XDG special user directories.
2695 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2696 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2697 * user directories have not been set up.
2699 * Depending on the platform, the user might be able to change the path
2700 * of the special directory without requiring the session to restart; GLib
2701 * will not reflect any change once the special directories are loaded.
2703 * Return value: the path to the specified special directory, or %NULL
2704 * if the logical id was not found. The returned string is owned by
2705 * GLib and should not be modified or freed.
2710 g_get_user_special_dir (GUserDirectory directory)
2712 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2713 directory < G_USER_N_DIRECTORIES, NULL);
2715 G_LOCK (g_utils_global);
2717 if (G_UNLIKELY (g_user_special_dirs == NULL))
2719 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2721 load_user_special_dirs ();
2723 /* Special-case desktop for historical compatibility */
2724 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2728 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2729 g_build_filename (g_home_dir, "Desktop", NULL);
2733 G_UNLOCK (g_utils_global);
2735 return g_user_special_dirs[directory];
2740 #undef g_get_system_data_dirs
2743 get_module_for_address (gconstpointer address)
2745 /* Holds the g_utils_global lock */
2747 static gboolean beenhere = FALSE;
2748 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2749 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2750 HMODULE hmodule = NULL;
2757 p_GetModuleHandleExA =
2758 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2759 "GetModuleHandleExA");
2763 if (p_GetModuleHandleExA == NULL ||
2764 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2765 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2768 MEMORY_BASIC_INFORMATION mbi;
2769 VirtualQuery (address, &mbi, sizeof (mbi));
2770 hmodule = (HMODULE) mbi.AllocationBase;
2777 get_module_share_dir (gconstpointer address)
2783 hmodule = get_module_for_address (address);
2784 if (hmodule == NULL)
2787 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2788 retval = g_build_filename (filename, "share", NULL);
2794 const gchar * const *
2795 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2799 static GHashTable *per_module_data_dirs = NULL;
2804 if (address_of_function)
2806 G_LOCK (g_utils_global);
2807 hmodule = get_module_for_address (address_of_function);
2808 if (hmodule != NULL)
2810 if (per_module_data_dirs == NULL)
2811 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2814 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2818 G_UNLOCK (g_utils_global);
2819 return (const gchar * const *) retval;
2825 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2827 /* Documents and Settings\All Users\Application Data */
2828 p = get_special_folder (CSIDL_COMMON_APPDATA);
2830 g_array_append_val (data_dirs, p);
2832 /* Documents and Settings\All Users\Documents */
2833 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2835 g_array_append_val (data_dirs, p);
2837 /* Using the above subfolders of Documents and Settings perhaps
2838 * makes sense from a Windows perspective.
2840 * But looking at the actual use cases of this function in GTK+
2841 * and GNOME software, what we really want is the "share"
2842 * subdirectory of the installation directory for the package
2843 * our caller is a part of.
2845 * The address_of_function parameter, if non-NULL, points to a
2846 * function in the calling module. Use that to determine that
2847 * module's installation folder, and use its "share" subfolder.
2849 * Additionally, also use the "share" subfolder of the installation
2850 * locations of GLib and the .exe file being run.
2852 * To guard against none of the above being what is really wanted,
2853 * callers of this function should have Win32-specific code to look
2854 * up their installation folder themselves, and handle a subfolder
2855 * "share" of it in the same way as the folders returned from this
2859 p = get_module_share_dir (address_of_function);
2861 g_array_append_val (data_dirs, p);
2863 if (glib_dll != NULL)
2865 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
2866 p = g_build_filename (glib_root, "share", NULL);
2868 g_array_append_val (data_dirs, p);
2872 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
2873 p = g_build_filename (exe_root, "share", NULL);
2875 g_array_append_val (data_dirs, p);
2878 retval = (gchar **) g_array_free (data_dirs, FALSE);
2880 if (address_of_function)
2882 if (hmodule != NULL)
2883 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
2884 G_UNLOCK (g_utils_global);
2887 return (const gchar * const *) retval;
2893 * g_get_system_data_dirs:
2895 * Returns an ordered list of base directories in which to access
2896 * system-wide application data.
2898 * On UNIX platforms this is determined using the mechanisms described in
2899 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2900 * XDG Base Directory Specification</ulink>
2901 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2903 * On Windows the first elements in the list are the Application Data
2904 * and Documents folders for All Users. (These can be determined only
2905 * on Windows 2000 or later and are not present in the list on other
2906 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2907 * CSIDL_COMMON_DOCUMENTS.
2909 * Then follows the "share" subfolder in the installation folder for
2910 * the package containing the DLL that calls this function, if it can
2913 * Finally the list contains the "share" subfolder in the installation
2914 * folder for GLib, and in the installation folder for the package the
2915 * application's .exe file belongs to.
2917 * The installation folders above are determined by looking up the
2918 * folder where the module (DLL or EXE) in question is located. If the
2919 * folder's name is "bin", its parent is used, otherwise the folder
2922 * Note that on Windows the returned list can vary depending on where
2923 * this function is called.
2925 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2926 * not be modified or freed.
2929 const gchar * const *
2930 g_get_system_data_dirs (void)
2932 gchar **data_dir_vector;
2934 G_LOCK (g_utils_global);
2936 if (!g_system_data_dirs)
2939 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2941 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2943 if (!data_dirs || !data_dirs[0])
2944 data_dirs = "/usr/local/share/:/usr/share/";
2946 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2949 g_system_data_dirs = data_dir_vector;
2952 data_dir_vector = g_system_data_dirs;
2954 G_UNLOCK (g_utils_global);
2956 return (const gchar * const *) data_dir_vector;
2960 * g_get_system_config_dirs:
2962 * Returns an ordered list of base directories in which to access
2963 * system-wide configuration information.
2965 * On UNIX platforms this is determined using the mechanisms described in
2966 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2967 * XDG Base Directory Specification</ulink>.
2968 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2970 * On Windows is the directory that contains application data for all users.
2971 * A typical path is C:\Documents and Settings\All Users\Application Data.
2972 * This folder is used for application data that is not user specific.
2973 * For example, an application can store a spell-check dictionary, a database
2974 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2975 * This information will not roam and is available to anyone using the computer.
2977 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2978 * not be modified or freed.
2981 const gchar * const *
2982 g_get_system_config_dirs (void)
2984 gchar *conf_dirs, **conf_dir_vector;
2986 G_LOCK (g_utils_global);
2988 if (!g_system_config_dirs)
2991 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2994 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2999 /* Return empty list */
3000 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
3003 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
3005 if (!conf_dirs || !conf_dirs[0])
3006 conf_dirs = "/etc/xdg";
3008 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3011 g_system_config_dirs = conf_dir_vector;
3014 conf_dir_vector = g_system_config_dirs;
3015 G_UNLOCK (g_utils_global);
3017 return (const gchar * const *) conf_dir_vector;
3022 static GHashTable *alias_table = NULL;
3024 /* read an alias file for the locales */
3026 read_aliases (gchar *file)
3032 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3033 fp = fopen (file,"r");
3036 while (fgets (buf, 256, fp))
3042 /* Line is a comment */
3043 if ((buf[0] == '#') || (buf[0] == '\0'))
3046 /* Reads first column */
3047 for (p = buf, q = NULL; *p; p++) {
3048 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3051 while ((*q == '\t') || (*q == ' ')) {
3057 /* The line only had one column */
3058 if (!q || *q == '\0')
3061 /* Read second column */
3062 for (p = q; *p; p++) {
3063 if ((*p == '\t') || (*p == ' ')) {
3069 /* Add to alias table if necessary */
3070 if (!g_hash_table_lookup (alias_table, buf)) {
3071 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3080 unalias_lang (char *lang)
3087 read_aliases ("/usr/share/locale/locale.alias");
3090 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3095 static gboolean said_before = FALSE;
3097 g_warning ("Too many alias levels for a locale, "
3098 "may indicate a loop");
3107 /* Mask for components of locale spec. The ordering here is from
3108 * least significant to most significant
3112 COMPONENT_CODESET = 1 << 0,
3113 COMPONENT_TERRITORY = 1 << 1,
3114 COMPONENT_MODIFIER = 1 << 2
3117 /* Break an X/Open style locale specification into components
3120 explode_locale (const gchar *locale,
3126 const gchar *uscore_pos;
3127 const gchar *at_pos;
3128 const gchar *dot_pos;
3132 uscore_pos = strchr (locale, '_');
3133 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3134 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3138 mask |= COMPONENT_MODIFIER;
3139 *modifier = g_strdup (at_pos);
3142 at_pos = locale + strlen (locale);
3146 mask |= COMPONENT_CODESET;
3147 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3154 mask |= COMPONENT_TERRITORY;
3155 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3158 uscore_pos = dot_pos;
3160 *language = g_strndup (locale, uscore_pos - locale);
3166 * Compute all interesting variants for a given locale name -
3167 * by stripping off different components of the value.
3169 * For simplicity, we assume that the locale is in
3170 * X/Open format: language[_territory][.codeset][@modifier]
3172 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3173 * as well. We could just copy the code from glibc wholesale
3174 * but it is big, ugly, and complicated, so I'm reluctant
3175 * to do so when this should handle 99% of the time...
3178 append_locale_variants (GPtrArray *array,
3179 const gchar *locale)
3181 gchar *language = NULL;
3182 gchar *territory = NULL;
3183 gchar *codeset = NULL;
3184 gchar *modifier = NULL;
3189 g_return_if_fail (locale != NULL);
3191 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3193 /* Iterate through all possible combinations, from least attractive
3194 * to most attractive.
3196 for (j = 0; j <= mask; ++j)
3200 if ((i & ~mask) == 0)
3202 gchar *val = g_strconcat (language,
3203 (i & COMPONENT_TERRITORY) ? territory : "",
3204 (i & COMPONENT_CODESET) ? codeset : "",
3205 (i & COMPONENT_MODIFIER) ? modifier : "",
3207 g_ptr_array_add (array, val);
3212 if (mask & COMPONENT_CODESET)
3214 if (mask & COMPONENT_TERRITORY)
3216 if (mask & COMPONENT_MODIFIER)
3221 * g_get_locale_variants:
3222 * @locale: a locale identifier
3224 * Returns a list of derived variants of @locale, which can be used to
3225 * e.g. construct locale-dependent filenames or search paths. The returned
3226 * list is sorted from most desirable to least desirable.
3227 * This function handles territory, charset and extra locale modifiers.
3229 * For example, if @locale is "fr_BE", then the returned list
3232 * If you need the list of variants for the <emphasis>current locale</emphasis>,
3233 * use g_get_language_names().
3235 * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
3236 * allocated array of newly allocated strings with the locale variants. Free with
3242 g_get_locale_variants (const gchar *locale)
3246 g_return_val_if_fail (locale != NULL, NULL);
3248 array = g_ptr_array_sized_new (8);
3249 append_locale_variants (array, locale);
3250 g_ptr_array_add (array, NULL);
3252 return (gchar **) g_ptr_array_free (array, FALSE);
3255 /* The following is (partly) taken from the gettext package.
3256 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3258 static const gchar *
3259 guess_category_value (const gchar *category_name)
3261 const gchar *retval;
3263 /* The highest priority value is the `LANGUAGE' environment
3264 variable. This is a GNU extension. */
3265 retval = g_getenv ("LANGUAGE");
3266 if ((retval != NULL) && (retval[0] != '\0'))
3269 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3270 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3271 systems this can be done by the `setlocale' function itself. */
3273 /* Setting of LC_ALL overwrites all other. */
3274 retval = g_getenv ("LC_ALL");
3275 if ((retval != NULL) && (retval[0] != '\0'))
3278 /* Next comes the name of the desired category. */
3279 retval = g_getenv (category_name);
3280 if ((retval != NULL) && (retval[0] != '\0'))
3283 /* Last possibility is the LANG environment variable. */
3284 retval = g_getenv ("LANG");
3285 if ((retval != NULL) && (retval[0] != '\0'))
3288 #ifdef G_PLATFORM_WIN32
3289 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3290 * LANG, which we already did above. Oh well. The main point of
3291 * calling g_win32_getlocale() is to get the thread's locale as used
3292 * by Windows and the Microsoft C runtime (in the "English_United
3293 * States" format) translated into the Unixish format.
3296 char *locale = g_win32_getlocale ();
3297 retval = g_intern_string (locale);
3306 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3308 struct _GLanguageNamesCache {
3310 gchar **language_names;
3314 language_names_cache_free (gpointer data)
3316 GLanguageNamesCache *cache = data;
3317 g_free (cache->languages);
3318 g_strfreev (cache->language_names);
3323 * g_get_language_names:
3325 * Computes a list of applicable locale names, which can be used to
3326 * e.g. construct locale-dependent filenames or search paths. The returned
3327 * list is sorted from most desirable to least desirable and always contains
3328 * the default locale "C".
3330 * For example, if LANGUAGE=de:en_US, then the returned list is
3331 * "de", "en_US", "en", "C".
3333 * This function consults the environment variables <envar>LANGUAGE</envar>,
3334 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3335 * to find the list of locales specified by the user.
3337 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
3338 * that must not be modified or freed.
3342 const gchar * const *
3343 g_get_language_names (void)
3345 static GPrivate cache_private = G_PRIVATE_INIT (language_names_cache_free);
3346 GLanguageNamesCache *cache = g_private_get (&cache_private);
3351 cache = g_new0 (GLanguageNamesCache, 1);
3352 g_private_set (&cache_private, cache);
3355 value = guess_category_value ("LC_MESSAGES");
3359 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3364 g_free (cache->languages);
3365 g_strfreev (cache->language_names);
3366 cache->languages = g_strdup (value);
3368 array = g_ptr_array_sized_new (8);
3370 alist = g_strsplit (value, ":", 0);
3371 for (a = alist; *a; a++)
3372 append_locale_variants (array, unalias_lang (*a));
3374 g_ptr_array_add (array, g_strdup ("C"));
3375 g_ptr_array_add (array, NULL);
3377 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3380 return (const gchar * const *) cache->language_names;
3384 * g_nullify_pointer:
3385 * @nullify_location: the memory address of the pointer.
3387 * Set the pointer at the specified location to %NULL.
3390 g_nullify_pointer (gpointer *nullify_location)
3392 g_return_if_fail (nullify_location != NULL);
3394 *nullify_location = NULL;
3400 * Get the codeset for the current locale.
3402 * Return value: a newly allocated string containing the name
3403 * of the codeset. This string must be freed with g_free().
3406 g_get_codeset (void)
3408 const gchar *charset;
3410 g_get_charset (&charset);
3412 return g_strdup (charset);
3418 * _glib_get_locale_dir:
3420 * Return the path to the share\locale or lib\locale subfolder of the
3421 * GLib installation folder. The path is in the system codepage. We
3422 * have to use system codepage as bindtextdomain() doesn't have a
3426 _glib_get_locale_dir (void)
3428 gchar *install_dir = NULL, *locale_dir;
3429 gchar *retval = NULL;
3431 if (glib_dll != NULL)
3432 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3437 * Append "/share/locale" or "/lib/locale" depending on whether
3438 * autoconfigury detected GNU gettext or not.
3440 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3446 locale_dir = g_build_filename (install_dir, p, NULL);
3448 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3450 g_free (install_dir);
3451 g_free (locale_dir);
3457 return g_strdup ("");
3460 #undef GLIB_LOCALE_DIR
3462 #endif /* G_OS_WIN32 */
3465 ensure_gettext_initialized (void)
3467 static gsize initialised;
3469 if (g_once_init_enter (&initialised))
3472 gchar *tmp = _glib_get_locale_dir ();
3473 bindtextdomain (GETTEXT_PACKAGE, tmp);
3476 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3478 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3479 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3481 g_once_init_leave (&initialised, TRUE);
3487 * @str: The string to be translated
3489 * Returns the translated string from the glib translations.
3490 * This is an internal function and should only be used by
3491 * the internals of glib (such as libgio).
3493 * Returns: the transation of @str to the current locale
3496 glib_gettext (const gchar *str)
3498 ensure_gettext_initialized();
3500 return g_dgettext (GETTEXT_PACKAGE, str);
3505 * @msgctxtid: a combined message context and message id, separated
3506 * by a \004 character
3507 * @msgidoffset: the offset of the message id in @msgctxid
3509 * This function is a variant of glib_gettext() which supports
3510 * a disambiguating message context. See g_dpgettext() for full
3513 * This is an internal function and should only be used by
3514 * the internals of glib (such as libgio).
3516 * Returns: the transation of @str to the current locale
3519 glib_pgettext(const gchar *msgctxtid,
3522 ensure_gettext_initialized();
3524 return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3527 #if defined (G_OS_WIN32) && !defined (_WIN64)
3529 /* Binary compatibility versions. Not for newly compiled code. */
3531 #undef g_find_program_in_path
3534 g_find_program_in_path (const gchar *program)
3536 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3537 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3540 g_free (utf8_program);
3541 if (utf8_retval == NULL)
3543 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3544 g_free (utf8_retval);
3549 #undef g_get_current_dir
3552 g_get_current_dir (void)
3554 gchar *utf8_dir = g_get_current_dir_utf8 ();
3555 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3563 g_getenv (const gchar *variable)
3565 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3566 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3570 g_free (utf8_variable);
3573 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3574 quark = g_quark_from_string (value);
3577 return g_quark_to_string (quark);
3583 g_setenv (const gchar *variable,
3587 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3588 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3589 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3591 g_free (utf8_variable);
3592 g_free (utf8_value);
3600 g_unsetenv (const gchar *variable)
3602 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3604 g_unsetenv_utf8 (utf8_variable);
3606 g_free (utf8_variable);
3609 #undef g_get_user_name
3612 g_get_user_name (void)
3614 g_get_any_init_locked ();
3615 return g_user_name_cp;
3618 #undef g_get_real_name
3621 g_get_real_name (void)
3623 g_get_any_init_locked ();
3624 return g_real_name_cp;
3627 #undef g_get_home_dir
3630 g_get_home_dir (void)
3632 g_get_any_init_locked ();
3633 return g_home_dir_cp;
3636 #undef g_get_tmp_dir
3639 g_get_tmp_dir (void)
3641 g_get_any_init_locked ();
3642 return g_tmp_dir_cp;