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 arbitrary byte strings. 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
1233 * If you need to set up the environment for a child process, you can
1234 * use g_get_environ() to get an environment array, modify that with
1235 * g_environ_setenv() and g_environ_unsetenv(), and then pass that
1236 * array directly to execvpe(), g_spawn_async(), or the like.
1239 * Returns: %FALSE if the environment variable couldn't be set.
1244 g_setenv (const gchar *variable,
1255 g_return_val_if_fail (variable != NULL, FALSE);
1256 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1259 result = setenv (variable, value, overwrite);
1261 if (!overwrite && getenv (variable) != NULL)
1264 /* This results in a leak when you overwrite existing
1265 * settings. It would be fairly easy to fix this by keeping
1266 * our own parallel array or hash table.
1268 string = g_strconcat (variable, "=", value, NULL);
1269 result = putenv (string);
1273 #else /* G_OS_WIN32 */
1276 wchar_t *wname, *wvalue, *wassignment;
1279 g_return_val_if_fail (variable != NULL, FALSE);
1280 g_return_val_if_fail (strchr (variable, '=') == NULL, FALSE);
1281 g_return_val_if_fail (g_utf8_validate (variable, -1, NULL), FALSE);
1282 g_return_val_if_fail (g_utf8_validate (value, -1, NULL), FALSE);
1284 if (!overwrite && g_getenv (variable) != NULL)
1287 /* We want to (if possible) set both the environment variable copy
1288 * kept by the C runtime and the one kept by the system.
1290 * We can't use only the C runtime's putenv or _wputenv() as that
1291 * won't work for arbitrary Unicode strings in a "non-Unicode" app
1292 * (with main() and not wmain()). In a "main()" app the C runtime
1293 * initializes the C runtime's environment table by converting the
1294 * real (wide char) environment variables to system codepage, thus
1295 * breaking those that aren't representable in the system codepage.
1297 * As the C runtime's putenv() will also set the system copy, we do
1298 * the putenv() first, then call SetEnvironmentValueW ourselves.
1301 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1302 wvalue = g_utf8_to_utf16 (value, -1, NULL, NULL, NULL);
1303 tem = g_strconcat (variable, "=", value, NULL);
1304 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1307 _wputenv (wassignment);
1308 g_free (wassignment);
1310 retval = (SetEnvironmentVariableW (wname, wvalue) != 0);
1317 #endif /* G_OS_WIN32 */
1320 #ifdef HAVE__NSGETENVIRON
1321 #define environ (*_NSGetEnviron())
1322 #elif !defined(G_OS_WIN32)
1324 /* According to the Single Unix Specification, environ is not in
1325 * any system header, although unistd.h often declares it.
1327 extern char **environ;
1332 * @variable: the environment variable to remove, must not contain '='.
1334 * Removes an environment variable from the environment.
1336 * Note that on some systems, when variables are overwritten, the memory
1337 * used for the previous variables and its value isn't reclaimed.
1340 * Environment variable handling in UNIX is not thread-safe, and your
1341 * program may crash if one thread calls g_unsetenv() while another
1342 * thread is calling getenv(). (And note that many functions, such as
1343 * gettext(), call getenv() internally.) This function is only safe to
1344 * use at the very start of your program, before creating any other
1345 * threads (or creating objects that create worker threads of their
1348 * If you need to set up the environment for a child process, you can
1349 * use g_get_environ() to get an environment array, modify that with
1350 * g_environ_setenv() and g_environ_unsetenv(), and then pass that
1351 * array directly to execvpe(), g_spawn_async(), or the like.
1357 g_unsetenv (const gchar *variable)
1361 #ifdef HAVE_UNSETENV
1362 g_return_if_fail (variable != NULL);
1363 g_return_if_fail (strchr (variable, '=') == NULL);
1365 unsetenv (variable);
1366 #else /* !HAVE_UNSETENV */
1367 g_return_if_fail (variable != NULL);
1368 g_return_if_fail (strchr (variable, '=') == NULL);
1370 /* Mess directly with the environ array.
1371 * This seems to be the only portable way to do this.
1373 g_environ_unsetenv (environ, variable);
1374 #endif /* !HAVE_UNSETENV */
1376 #else /* G_OS_WIN32 */
1378 wchar_t *wname, *wassignment;
1381 g_return_if_fail (variable != NULL);
1382 g_return_if_fail (strchr (variable, '=') == NULL);
1383 g_return_if_fail (g_utf8_validate (variable, -1, NULL));
1385 wname = g_utf8_to_utf16 (variable, -1, NULL, NULL, NULL);
1386 tem = g_strconcat (variable, "=", NULL);
1387 wassignment = g_utf8_to_utf16 (tem, -1, NULL, NULL, NULL);
1390 _wputenv (wassignment);
1391 g_free (wassignment);
1393 SetEnvironmentVariableW (wname, NULL);
1397 #endif /* G_OS_WIN32 */
1403 * Gets the names of all variables set in the environment.
1405 * Returns: (array zero-terminated=1) (transfer full): a %NULL-terminated list of strings which must be freed
1406 * with g_strfreev().
1408 * Programs that want to be portable to Windows should typically use
1409 * this function and g_getenv() instead of using the environ array
1410 * from the C library directly. On Windows, the strings in the environ
1411 * array are in system codepage encoding, while in most of the typical
1412 * use cases for environment variables in GLib-using programs you want
1413 * the UTF-8 encoding that this function and g_getenv() provide.
1421 gchar **result, *eq;
1424 len = g_strv_length (environ);
1425 result = g_new0 (gchar *, len + 1);
1428 for (i = 0; i < len; i++)
1430 eq = strchr (environ[i], '=');
1432 result[j++] = g_strndup (environ[i], eq - environ[i]);
1439 gchar **result, *eq;
1443 p = (wchar_t *) GetEnvironmentStringsW ();
1449 q += wcslen (q) + 1;
1453 result = g_new0 (gchar *, len + 1);
1459 result[j] = g_utf16_to_utf8 (q, -1, NULL, NULL, NULL);
1460 if (result[j] != NULL)
1462 eq = strchr (result[j], '=');
1463 if (eq && eq > result[j])
1471 q += wcslen (q) + 1;
1474 FreeEnvironmentStringsW (p);
1483 * Gets the list of environment variables for the current process. The
1484 * list is %NULL terminated and each item in the list is of the form
1487 * This is equivalent to direct access to the 'environ' global variable,
1490 * The return value is freshly allocated and it should be freed with
1491 * g_strfreev() when it is no longer needed.
1493 * Returns: (array zero-terminated=1) (transfer full): the list of
1494 * environment variables
1499 g_get_environ (void)
1502 return g_strdupv (environ);
1508 strings = GetEnvironmentStringsW ();
1509 for (n = 0; strings[n]; n += wcslen (strings + n) + 1);
1510 result = g_new (char *, n + 1);
1511 for (i = 0; strings[i]; i += wcslen (strings + i) + 1)
1512 result[i] = g_utf16_to_utf8 (strings + i, -1, NULL, NULL, NULL);
1513 FreeEnvironmentStringsW (strings);
1521 g_environ_find (gchar **envp,
1522 const gchar *variable)
1526 len = strlen (variable);
1528 for (i = 0; envp[i]; i++)
1530 if (strncmp (envp[i], variable, len) == 0 &&
1531 envp[i][len] == '=')
1540 * @envp: (array zero-terminated=1) (transfer none): an environment
1541 * list (eg, as returned from g_get_environ())
1542 * @variable: the environment variable to get, in the GLib file name
1545 * Returns the value of the environment variable @variable in the
1546 * provided list @envp.
1548 * The name and value are in the GLib file name encoding.
1549 * On UNIX, this means the actual bytes which might or might not
1550 * be in some consistent character set and encoding. On Windows,
1551 * it is in UTF-8. On Windows, in case the environment variable's
1552 * value contains references to other environment variables, they
1555 * Return value: the value of the environment variable, or %NULL if
1556 * the environment variable is not set in @envp. The returned
1557 * string is owned by @envp, and will be freed if @variable is
1558 * set or unset again.
1563 g_environ_getenv (gchar **envp,
1564 const gchar *variable)
1568 g_return_val_if_fail (envp != NULL, NULL);
1569 g_return_val_if_fail (variable != NULL, NULL);
1571 index = g_environ_find (envp, variable);
1573 return envp[index] + strlen (variable) + 1;
1580 * @envp: (array zero-terminated=1) (transfer full): an environment
1581 * list (eg, as returned from g_get_environ())
1582 * @variable: the environment variable to set, must not contain '='
1583 * @value: the value for to set the variable to
1584 * @overwrite: whether to change the variable if it already exists
1586 * Sets the environment variable @variable in the provided list
1589 * Both the variable's name and value should be in the GLib
1590 * file name encoding. On UNIX, this means that they can be
1591 * arbitrary byte strings. On Windows, they should be in UTF-8.
1593 * Return value: (array zero-terminated=1) (transfer full): the
1594 * updated environment
1599 g_environ_setenv (gchar **envp,
1600 const gchar *variable,
1606 g_return_val_if_fail (envp != NULL, NULL);
1607 g_return_val_if_fail (variable != NULL, NULL);
1608 g_return_val_if_fail (strchr (variable, '=') == NULL, NULL);
1610 index = g_environ_find (envp, variable);
1615 g_free (envp[index]);
1616 envp[index] = g_strdup_printf ("%s=%s", variable, value);
1623 length = g_strv_length (envp);
1624 envp = g_renew (gchar *, envp, length + 2);
1625 envp[length] = g_strdup_printf ("%s=%s", variable, value);
1626 envp[length + 1] = NULL;
1633 * g_environ_unsetenv:
1634 * @envp: (array zero-terminated=1) (transfer full): an environment
1635 * list (eg, as returned from g_get_environ())
1636 * @variable: the environment variable to remove, must not contain '='
1638 * Removes the environment variable @variable from the provided
1639 * environment @envp.
1641 * Return value: (array zero-terminated=1) (transfer full): the
1642 * updated environment
1647 g_environ_unsetenv (gchar **envp,
1648 const gchar *variable)
1653 g_return_val_if_fail (envp != NULL, NULL);
1654 g_return_val_if_fail (variable != NULL, NULL);
1655 g_return_val_if_fail (strchr (variable, '=') == NULL, NULL);
1657 len = strlen (variable);
1659 /* Note that we remove *all* environment entries for
1660 * the variable name, not just the first.
1665 if (strncmp (*e, variable, len) != 0 || (*e)[len] != '=')
1677 G_LOCK_DEFINE_STATIC (g_utils_global);
1679 static gchar *g_tmp_dir = NULL;
1680 static gchar *g_user_name = NULL;
1681 static gchar *g_real_name = NULL;
1682 static gchar *g_home_dir = NULL;
1683 static gchar *g_host_name = NULL;
1686 /* System codepage versions of the above, kept at file level so that they,
1687 * too, are produced only once.
1689 static gchar *g_tmp_dir_cp = NULL;
1690 static gchar *g_user_name_cp = NULL;
1691 static gchar *g_real_name_cp = NULL;
1692 static gchar *g_home_dir_cp = NULL;
1695 static gchar *g_user_data_dir = NULL;
1696 static gchar **g_system_data_dirs = NULL;
1697 static gchar *g_user_cache_dir = NULL;
1698 static gchar *g_user_config_dir = NULL;
1699 static gchar **g_system_config_dirs = NULL;
1701 static gchar **g_user_special_dirs = NULL;
1703 /* fifteen minutes of fame for everybody */
1704 #define G_USER_DIRS_EXPIRE 15 * 60
1709 get_special_folder (int csidl)
1711 wchar_t path[MAX_PATH+1];
1713 LPITEMIDLIST pidl = NULL;
1715 gchar *retval = NULL;
1717 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
1720 b = SHGetPathFromIDListW (pidl, path);
1722 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
1723 CoTaskMemFree (pidl);
1729 get_windows_directory_root (void)
1731 wchar_t wwindowsdir[MAX_PATH];
1733 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
1735 /* Usually X:\Windows, but in terminal server environments
1736 * might be an UNC path, AFAIK.
1738 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
1741 if (windowsdir == NULL)
1742 return g_strdup ("C:\\");
1744 p = (char *) g_path_skip_root (windowsdir);
1745 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
1751 return g_strdup ("C:\\");
1756 /* HOLDS: g_utils_global_lock */
1758 g_get_any_init_do (void)
1760 gchar hostname[100];
1762 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
1763 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1764 g_tmp_dir = g_strdup (g_getenv ("TMP"));
1765 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1766 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
1769 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1770 g_tmp_dir = get_windows_directory_root ();
1773 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1776 g_tmp_dir = g_strdup (P_tmpdir);
1777 k = strlen (g_tmp_dir);
1778 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
1779 g_tmp_dir[k - 1] = '\0';
1783 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
1785 g_tmp_dir = g_strdup ("/tmp");
1787 #endif /* !G_OS_WIN32 */
1790 /* We check $HOME first for Win32, though it is a last resort for Unix
1791 * where we prefer the results of getpwuid().
1793 g_home_dir = g_strdup (g_getenv ("HOME"));
1795 /* Only believe HOME if it is an absolute path and exists */
1798 if (!(g_path_is_absolute (g_home_dir) &&
1799 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
1801 g_free (g_home_dir);
1806 /* In case HOME is Unix-style (it happens), convert it to
1812 while ((p = strchr (g_home_dir, '/')) != NULL)
1818 /* USERPROFILE is probably the closest equivalent to $HOME? */
1819 if (g_getenv ("USERPROFILE") != NULL)
1820 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
1824 g_home_dir = get_special_folder (CSIDL_PROFILE);
1827 g_home_dir = get_windows_directory_root ();
1828 #endif /* G_OS_WIN32 */
1832 struct passwd *pw = NULL;
1833 gpointer buffer = NULL;
1837 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1839 # ifdef _SC_GETPW_R_SIZE_MAX
1840 /* This reurns the maximum length */
1841 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
1845 # else /* _SC_GETPW_R_SIZE_MAX */
1847 # endif /* _SC_GETPW_R_SIZE_MAX */
1849 logname = (gchar *) g_getenv ("LOGNAME");
1854 /* we allocate 6 extra bytes to work around a bug in
1855 * Mac OS < 10.3. See #156446
1857 buffer = g_malloc (bufsize + 6);
1860 # ifdef HAVE_POSIX_GETPWUID_R
1862 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
1863 if (!pw || (pw->pw_uid != getuid ())) {
1864 /* LOGNAME is lying, fall back to looking up the uid */
1865 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1868 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
1870 error = error < 0 ? errno : error;
1871 # else /* HAVE_NONPOSIX_GETPWUID_R */
1872 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1873 # if defined(_AIX) || defined(__hpux)
1874 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1875 pw = error == 0 ? &pwd : NULL;
1878 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
1879 if (!pw || (pw->pw_uid != getuid ())) {
1880 /* LOGNAME is lying, fall back to looking up the uid */
1881 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1884 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
1886 error = pw ? 0 : errno;
1888 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1892 /* we bail out prematurely if the user id can't be found
1893 * (should be pretty rare case actually), or if the buffer
1894 * should be sufficiently big and lookups are still not
1897 if (error == 0 || error == ENOENT)
1899 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1900 (gulong) getuid ());
1903 if (bufsize > 32 * 1024)
1905 g_warning ("getpwuid_r(): failed due to: %s.",
1906 g_strerror (error));
1914 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1919 pw = getpwuid (getuid ());
1924 g_user_name = g_strdup (pw->pw_name);
1926 if (pw->pw_gecos && *pw->pw_gecos != '\0')
1928 gchar **gecos_fields;
1931 /* split the gecos field and substitute '&' */
1932 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
1933 name_parts = g_strsplit (gecos_fields[0], "&", 0);
1934 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
1935 g_real_name = g_strjoinv (pw->pw_name, name_parts);
1936 g_strfreev (gecos_fields);
1937 g_strfreev (name_parts);
1941 g_home_dir = g_strdup (pw->pw_dir);
1946 #else /* !HAVE_PWD_H */
1950 guint len = UNLEN+1;
1951 wchar_t buffer[UNLEN+1];
1953 if (GetUserNameW (buffer, (LPDWORD) &len))
1955 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
1956 g_real_name = g_strdup (g_user_name);
1959 #endif /* G_OS_WIN32 */
1961 #endif /* !HAVE_PWD_H */
1965 g_home_dir = g_strdup (g_getenv ("HOME"));
1969 /* change '\\' in %HOME% to '/' */
1970 g_strdelimit (g_home_dir, "\\",'/');
1973 g_user_name = g_strdup ("somebody");
1975 g_real_name = g_strdup ("Unknown");
1979 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
1981 DWORD size = sizeof (hostname);
1982 gboolean hostname_fail = (!GetComputerName (hostname, &size));
1984 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
1988 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
1989 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
1990 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
1993 g_tmp_dir_cp = g_strdup ("\\");
1994 if (!g_user_name_cp)
1995 g_user_name_cp = g_strdup ("somebody");
1996 if (!g_real_name_cp)
1997 g_real_name_cp = g_strdup ("Unknown");
1999 /* home_dir might be NULL, unlike tmp_dir, user_name and
2003 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
2005 g_home_dir_cp = NULL;
2006 #endif /* G_OS_WIN32 */
2010 g_get_any_init (void)
2013 g_get_any_init_do ();
2017 g_get_any_init_locked (void)
2019 G_LOCK (g_utils_global);
2021 G_UNLOCK (g_utils_global);
2028 * Gets the user name of the current user. The encoding of the returned
2029 * string is system-defined. On UNIX, it might be the preferred file name
2030 * encoding, or something else, and there is no guarantee that it is even
2031 * consistent on a machine. On Windows, it is always UTF-8.
2033 * Returns: the user name of the current user.
2036 g_get_user_name (void)
2038 g_get_any_init_locked ();
2045 * Gets the real name of the user. This usually comes from the user's entry
2046 * in the <filename>passwd</filename> file. The encoding of the returned
2047 * string is system-defined. (On Windows, it is, however, always UTF-8.)
2048 * If the real user name cannot be determined, the string "Unknown" is
2051 * Returns: the user's real name.
2054 g_get_real_name (void)
2056 g_get_any_init_locked ();
2063 * Gets the current user's home directory as defined in the
2064 * password database.
2066 * Note that in contrast to traditional UNIX tools, this function
2067 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
2068 * environment variable.
2070 * One of the reasons for this decision is that applications in many
2071 * cases need special handling to deal with the case where
2072 * <envar>HOME</envar> is
2074 * <member>Not owned by the user</member>
2075 * <member>Not writeable</member>
2076 * <member>Not even readable</member>
2078 * Since applications are in general <emphasis>not</emphasis> written
2079 * to deal with these situations it was considered better to make
2080 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
2081 * return the real home directory for the user. If applications
2082 * want to pay attention to <envar>HOME</envar>, they can do:
2084 * const char *homedir = g_getenv ("HOME");
2086 * homedir = g_get_home_dir (<!-- -->);
2089 * Returns: the current user's home directory
2092 g_get_home_dir (void)
2094 g_get_any_init_locked ();
2101 * Gets the directory to use for temporary files. This is found from
2102 * inspecting the environment variables <envar>TMPDIR</envar>,
2103 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
2104 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
2105 * The encoding of the returned string is system-defined. On Windows,
2106 * it is always UTF-8. The return value is never %NULL or the empty string.
2108 * Returns: the directory to use for temporary files.
2111 g_get_tmp_dir (void)
2113 g_get_any_init_locked ();
2120 * Return a name for the machine.
2122 * The returned name is not necessarily a fully-qualified domain name,
2123 * or even present in DNS or some other name service at all. It need
2124 * not even be unique on your local network or site, but usually it
2125 * is. Callers should not rely on the return value having any specific
2126 * properties like uniqueness for security purposes. Even if the name
2127 * of the machine is changed while an application is running, the
2128 * return value from this function does not change. The returned
2129 * string is owned by GLib and should not be modified or freed. If no
2130 * name can be determined, a default fixed string "localhost" is
2133 * Returns: the host name of the machine.
2138 g_get_host_name (void)
2140 g_get_any_init_locked ();
2144 G_LOCK_DEFINE_STATIC (g_prgname);
2145 static gchar *g_prgname = NULL;
2150 * Gets the name of the program. This name should <emphasis>not</emphasis>
2151 * be localized, contrast with g_get_application_name().
2152 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
2153 * which is called by gtk_init(). The program name is found by taking
2154 * the last component of <literal>argv[0]</literal>.)
2156 * Returns: the name of the program. The returned string belongs
2157 * to GLib and must not be modified or freed.
2160 g_get_prgname (void)
2166 if (g_prgname == NULL)
2168 static gboolean beenhere = FALSE;
2172 gchar *utf8_buf = NULL;
2173 wchar_t buf[MAX_PATH+1];
2176 if (GetModuleFileNameW (GetModuleHandle (NULL),
2177 buf, G_N_ELEMENTS (buf)) > 0)
2178 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
2182 g_prgname = g_path_get_basename (utf8_buf);
2189 G_UNLOCK (g_prgname);
2196 * @prgname: the name of the program.
2198 * Sets the name of the program. This name should <emphasis>not</emphasis>
2199 * be localized, contrast with g_set_application_name(). Note that for
2200 * thread-safety reasons this function can only be called once.
2203 g_set_prgname (const gchar *prgname)
2207 g_prgname = g_strdup (prgname);
2208 G_UNLOCK (g_prgname);
2211 G_LOCK_DEFINE_STATIC (g_application_name);
2212 static gchar *g_application_name = NULL;
2215 * g_get_application_name:
2217 * Gets a human-readable name for the application, as set by
2218 * g_set_application_name(). This name should be localized if
2219 * possible, and is intended for display to the user. Contrast with
2220 * g_get_prgname(), which gets a non-localized name. If
2221 * g_set_application_name() has not been called, returns the result of
2222 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
2225 * Return value: human-readable application name. may return %NULL
2230 g_get_application_name (void)
2234 G_LOCK (g_application_name);
2235 retval = g_application_name;
2236 G_UNLOCK (g_application_name);
2239 return g_get_prgname ();
2245 * g_set_application_name:
2246 * @application_name: localized name of the application
2248 * Sets a human-readable name for the application. This name should be
2249 * localized if possible, and is intended for display to the user.
2250 * Contrast with g_set_prgname(), which sets a non-localized name.
2251 * g_set_prgname() will be called automatically by gtk_init(),
2252 * but g_set_application_name() will not.
2254 * Note that for thread safety reasons, this function can only
2257 * The application name will be used in contexts such as error messages,
2258 * or when displaying an application's name in the task list.
2263 g_set_application_name (const gchar *application_name)
2265 gboolean already_set = FALSE;
2267 G_LOCK (g_application_name);
2268 if (g_application_name)
2271 g_application_name = g_strdup (application_name);
2272 G_UNLOCK (g_application_name);
2275 g_warning ("g_set_application_name() called multiple times");
2279 * g_get_user_data_dir:
2281 * Returns a base directory in which to access application data such
2282 * as icons that is customized for a particular user.
2284 * On UNIX platforms this is determined using the mechanisms described in
2285 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2286 * XDG Base Directory Specification</ulink>.
2287 * In this case the directory retrieved will be XDG_DATA_HOME.
2289 * On Windows this is the folder to use for local (as opposed to
2290 * roaming) application data. See documentation for
2291 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2292 * what g_get_user_config_dir() returns.
2294 * Return value: a string owned by GLib that must not be modified
2299 g_get_user_data_dir (void)
2303 G_LOCK (g_utils_global);
2305 if (!g_user_data_dir)
2308 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2310 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
2312 if (data_dir && data_dir[0])
2313 data_dir = g_strdup (data_dir);
2315 if (!data_dir || !data_dir[0])
2320 data_dir = g_build_filename (g_home_dir, ".local",
2323 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
2327 g_user_data_dir = data_dir;
2330 data_dir = g_user_data_dir;
2332 G_UNLOCK (g_utils_global);
2338 g_init_user_config_dir (void)
2342 if (!g_user_config_dir)
2345 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
2347 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
2349 if (config_dir && config_dir[0])
2350 config_dir = g_strdup (config_dir);
2352 if (!config_dir || !config_dir[0])
2357 config_dir = g_build_filename (g_home_dir, ".config", NULL);
2359 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
2362 g_user_config_dir = config_dir;
2367 * g_get_user_config_dir:
2369 * Returns a base directory in which to store user-specific application
2370 * configuration information such as user preferences and settings.
2372 * On UNIX platforms this is determined using the mechanisms described in
2373 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2374 * XDG Base Directory Specification</ulink>.
2375 * In this case the directory retrieved will be XDG_CONFIG_HOME.
2377 * On Windows this is the folder to use for local (as opposed to
2378 * roaming) application data. See documentation for
2379 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2380 * what g_get_user_data_dir() returns.
2382 * Return value: a string owned by GLib that must not be modified
2387 g_get_user_config_dir (void)
2389 G_LOCK (g_utils_global);
2391 g_init_user_config_dir ();
2393 G_UNLOCK (g_utils_global);
2395 return g_user_config_dir;
2399 * g_get_user_cache_dir:
2401 * Returns a base directory in which to store non-essential, cached
2402 * data specific to particular user.
2404 * On UNIX platforms this is determined using the mechanisms described in
2405 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2406 * XDG Base Directory Specification</ulink>.
2407 * In this case the directory retrieved will be XDG_CACHE_HOME.
2409 * On Windows is the directory that serves as a common repository for
2410 * temporary Internet files. A typical path is
2411 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
2412 * See documentation for CSIDL_INTERNET_CACHE.
2414 * Return value: a string owned by GLib that must not be modified
2419 g_get_user_cache_dir (void)
2423 G_LOCK (g_utils_global);
2425 if (!g_user_cache_dir)
2428 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
2430 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
2432 if (cache_dir && cache_dir[0])
2433 cache_dir = g_strdup (cache_dir);
2435 if (!cache_dir || !cache_dir[0])
2440 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
2442 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
2444 g_user_cache_dir = cache_dir;
2447 cache_dir = g_user_cache_dir;
2449 G_UNLOCK (g_utils_global);
2455 * g_get_user_runtime_dir:
2457 * Returns a directory that is unique to the current user on the local
2460 * On UNIX platforms this is determined using the mechanisms described in
2461 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2462 * XDG Base Directory Specification</ulink>. This is the directory
2463 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
2464 * In the case that this variable is not set, GLib will issue a warning
2465 * message to stderr and return the value of g_get_user_cache_dir().
2467 * On Windows this is the folder to use for local (as opposed to
2468 * roaming) application data. See documentation for
2469 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
2470 * what g_get_user_config_dir() returns.
2472 * Returns: a string owned by GLib that must not be modified or freed.
2477 g_get_user_runtime_dir (void)
2480 static const gchar *runtime_dir;
2481 static gsize initialised;
2483 if (g_once_init_enter (&initialised))
2485 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
2487 g_once_init_leave (&initialised, 1);
2493 /* Both fallback for UNIX and the default
2494 * in Windows: use the user cache directory.
2498 return g_get_user_cache_dir ();
2504 find_folder (OSType type)
2506 gchar *filename = NULL;
2509 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
2511 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
2515 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
2519 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
2523 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
2525 CFStringGetCString (path, filename,
2526 CFStringGetLength (path) * 3 + 1,
2527 kCFStringEncodingUTF8);
2541 load_user_special_dirs (void)
2543 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
2544 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
2545 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
2546 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
2547 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
2548 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
2549 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
2550 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
2553 #endif /* HAVE_CARBON */
2555 #if defined(G_OS_WIN32)
2557 load_user_special_dirs (void)
2559 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
2563 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
2565 static const GUID FOLDERID_Downloads =
2566 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
2567 static const GUID FOLDERID_Public =
2568 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
2572 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
2573 "SHGetKnownFolderPath");
2575 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2576 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
2578 if (p_SHGetKnownFolderPath == NULL)
2580 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2585 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
2588 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2589 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
2590 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2591 CoTaskMemFree (wcp);
2594 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
2597 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
2598 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
2600 if (p_SHGetKnownFolderPath == NULL)
2603 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2608 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
2611 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
2612 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
2613 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2614 CoTaskMemFree (wcp);
2617 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2620 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
2621 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
2623 #endif /* G_OS_WIN32 */
2625 static void g_init_user_config_dir (void);
2627 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
2629 /* adapted from xdg-user-dir-lookup.c
2631 * Copyright (C) 2007 Red Hat Inc.
2633 * Permission is hereby granted, free of charge, to any person
2634 * obtaining a copy of this software and associated documentation files
2635 * (the "Software"), to deal in the Software without restriction,
2636 * including without limitation the rights to use, copy, modify, merge,
2637 * publish, distribute, sublicense, and/or sell copies of the Software,
2638 * and to permit persons to whom the Software is furnished to do so,
2639 * subject to the following conditions:
2641 * The above copyright notice and this permission notice shall be
2642 * included in all copies or substantial portions of the Software.
2644 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
2645 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
2646 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
2647 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
2648 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
2649 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
2650 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
2654 load_user_special_dirs (void)
2661 g_init_user_config_dir ();
2662 config_file = g_build_filename (g_user_config_dir,
2666 if (!g_file_get_contents (config_file, &data, NULL, NULL))
2668 g_free (config_file);
2672 lines = g_strsplit (data, "\n", -1);
2673 n_lines = g_strv_length (lines);
2676 for (i = 0; i < n_lines; i++)
2678 gchar *buffer = lines[i];
2681 gboolean is_relative = FALSE;
2682 GUserDirectory directory;
2684 /* Remove newline at end */
2685 len = strlen (buffer);
2686 if (len > 0 && buffer[len - 1] == '\n')
2687 buffer[len - 1] = 0;
2690 while (*p == ' ' || *p == '\t')
2693 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2695 directory = G_USER_DIRECTORY_DESKTOP;
2696 p += strlen ("XDG_DESKTOP_DIR");
2698 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2700 directory = G_USER_DIRECTORY_DOCUMENTS;
2701 p += strlen ("XDG_DOCUMENTS_DIR");
2703 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2705 directory = G_USER_DIRECTORY_DOWNLOAD;
2706 p += strlen ("XDG_DOWNLOAD_DIR");
2708 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2710 directory = G_USER_DIRECTORY_MUSIC;
2711 p += strlen ("XDG_MUSIC_DIR");
2713 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2715 directory = G_USER_DIRECTORY_PICTURES;
2716 p += strlen ("XDG_PICTURES_DIR");
2718 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2720 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
2721 p += strlen ("XDG_PUBLICSHARE_DIR");
2723 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2725 directory = G_USER_DIRECTORY_TEMPLATES;
2726 p += strlen ("XDG_TEMPLATES_DIR");
2728 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2730 directory = G_USER_DIRECTORY_VIDEOS;
2731 p += strlen ("XDG_VIDEOS_DIR");
2736 while (*p == ' ' || *p == '\t')
2743 while (*p == ' ' || *p == '\t')
2750 if (strncmp (p, "$HOME", 5) == 0)
2758 d = strrchr (p, '"');
2765 /* remove trailing slashes */
2767 if (d[len - 1] == '/')
2773 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
2776 g_user_special_dirs[directory] = g_strdup (d);
2780 g_free (config_file);
2783 #endif /* G_OS_UNIX && !HAVE_CARBON */
2787 * g_reload_user_special_dirs_cache:
2789 * Resets the cache used for g_get_user_special_dir(), so
2790 * that the latest on-disk version is used. Call this only
2791 * if you just changed the data on disk yourself.
2793 * Due to threadsafety issues this may cause leaking of strings
2794 * that were previously returned from g_get_user_special_dir()
2795 * that can't be freed. We ensure to only leak the data for
2796 * the directories that actually changed value though.
2801 g_reload_user_special_dirs_cache (void)
2805 G_LOCK (g_utils_global);
2807 if (g_user_special_dirs != NULL)
2809 /* save a copy of the pointer, to check if some memory can be preserved */
2810 char **old_g_user_special_dirs = g_user_special_dirs;
2813 /* recreate and reload our cache */
2814 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2815 load_user_special_dirs ();
2817 /* only leak changed directories */
2818 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
2820 old_val = old_g_user_special_dirs[i];
2821 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
2824 g_free (g_user_special_dirs[i]);
2825 g_user_special_dirs[i] = old_val;
2831 /* free the old array */
2832 g_free (old_g_user_special_dirs);
2835 G_UNLOCK (g_utils_global);
2839 * g_get_user_special_dir:
2840 * @directory: the logical id of special directory
2842 * Returns the full path of a special directory using its logical id.
2844 * On Unix this is done using the XDG special user directories.
2845 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2846 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2847 * user directories have not been set up.
2849 * Depending on the platform, the user might be able to change the path
2850 * of the special directory without requiring the session to restart; GLib
2851 * will not reflect any change once the special directories are loaded.
2853 * Return value: the path to the specified special directory, or %NULL
2854 * if the logical id was not found. The returned string is owned by
2855 * GLib and should not be modified or freed.
2860 g_get_user_special_dir (GUserDirectory directory)
2862 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
2863 directory < G_USER_N_DIRECTORIES, NULL);
2865 G_LOCK (g_utils_global);
2867 if (G_UNLIKELY (g_user_special_dirs == NULL))
2869 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
2871 load_user_special_dirs ();
2873 /* Special-case desktop for historical compatibility */
2874 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
2878 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
2879 g_build_filename (g_home_dir, "Desktop", NULL);
2883 G_UNLOCK (g_utils_global);
2885 return g_user_special_dirs[directory];
2890 #undef g_get_system_data_dirs
2893 get_module_for_address (gconstpointer address)
2895 /* Holds the g_utils_global lock */
2897 static gboolean beenhere = FALSE;
2898 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
2899 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
2900 HMODULE hmodule = NULL;
2907 p_GetModuleHandleExA =
2908 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2909 "GetModuleHandleExA");
2913 if (p_GetModuleHandleExA == NULL ||
2914 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
2915 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
2918 MEMORY_BASIC_INFORMATION mbi;
2919 VirtualQuery (address, &mbi, sizeof (mbi));
2920 hmodule = (HMODULE) mbi.AllocationBase;
2927 get_module_share_dir (gconstpointer address)
2933 hmodule = get_module_for_address (address);
2934 if (hmodule == NULL)
2937 filename = g_win32_get_package_installation_directory_of_module (hmodule);
2938 retval = g_build_filename (filename, "share", NULL);
2944 const gchar * const *
2945 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
2949 static GHashTable *per_module_data_dirs = NULL;
2954 if (address_of_function)
2956 G_LOCK (g_utils_global);
2957 hmodule = get_module_for_address (address_of_function);
2958 if (hmodule != NULL)
2960 if (per_module_data_dirs == NULL)
2961 per_module_data_dirs = g_hash_table_new (NULL, NULL);
2964 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
2968 G_UNLOCK (g_utils_global);
2969 return (const gchar * const *) retval;
2975 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
2977 /* Documents and Settings\All Users\Application Data */
2978 p = get_special_folder (CSIDL_COMMON_APPDATA);
2980 g_array_append_val (data_dirs, p);
2982 /* Documents and Settings\All Users\Documents */
2983 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
2985 g_array_append_val (data_dirs, p);
2987 /* Using the above subfolders of Documents and Settings perhaps
2988 * makes sense from a Windows perspective.
2990 * But looking at the actual use cases of this function in GTK+
2991 * and GNOME software, what we really want is the "share"
2992 * subdirectory of the installation directory for the package
2993 * our caller is a part of.
2995 * The address_of_function parameter, if non-NULL, points to a
2996 * function in the calling module. Use that to determine that
2997 * module's installation folder, and use its "share" subfolder.
2999 * Additionally, also use the "share" subfolder of the installation
3000 * locations of GLib and the .exe file being run.
3002 * To guard against none of the above being what is really wanted,
3003 * callers of this function should have Win32-specific code to look
3004 * up their installation folder themselves, and handle a subfolder
3005 * "share" of it in the same way as the folders returned from this
3009 p = get_module_share_dir (address_of_function);
3011 g_array_append_val (data_dirs, p);
3013 if (glib_dll != NULL)
3015 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
3016 p = g_build_filename (glib_root, "share", NULL);
3018 g_array_append_val (data_dirs, p);
3022 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
3023 p = g_build_filename (exe_root, "share", NULL);
3025 g_array_append_val (data_dirs, p);
3028 retval = (gchar **) g_array_free (data_dirs, FALSE);
3030 if (address_of_function)
3032 if (hmodule != NULL)
3033 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
3034 G_UNLOCK (g_utils_global);
3037 return (const gchar * const *) retval;
3043 * g_get_system_data_dirs:
3045 * Returns an ordered list of base directories in which to access
3046 * system-wide application data.
3048 * On UNIX platforms this is determined using the mechanisms described in
3049 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
3050 * XDG Base Directory Specification</ulink>
3051 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
3053 * On Windows the first elements in the list are the Application Data
3054 * and Documents folders for All Users. (These can be determined only
3055 * on Windows 2000 or later and are not present in the list on other
3056 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
3057 * CSIDL_COMMON_DOCUMENTS.
3059 * Then follows the "share" subfolder in the installation folder for
3060 * the package containing the DLL that calls this function, if it can
3063 * Finally the list contains the "share" subfolder in the installation
3064 * folder for GLib, and in the installation folder for the package the
3065 * application's .exe file belongs to.
3067 * The installation folders above are determined by looking up the
3068 * folder where the module (DLL or EXE) in question is located. If the
3069 * folder's name is "bin", its parent is used, otherwise the folder
3072 * Note that on Windows the returned list can vary depending on where
3073 * this function is called.
3075 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
3076 * not be modified or freed.
3079 const gchar * const *
3080 g_get_system_data_dirs (void)
3082 gchar **data_dir_vector;
3084 G_LOCK (g_utils_global);
3086 if (!g_system_data_dirs)
3089 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
3091 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
3093 if (!data_dirs || !data_dirs[0])
3094 data_dirs = "/usr/local/share/:/usr/share/";
3096 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3099 g_system_data_dirs = data_dir_vector;
3102 data_dir_vector = g_system_data_dirs;
3104 G_UNLOCK (g_utils_global);
3106 return (const gchar * const *) data_dir_vector;
3110 * g_get_system_config_dirs:
3112 * Returns an ordered list of base directories in which to access
3113 * system-wide configuration information.
3115 * On UNIX platforms this is determined using the mechanisms described in
3116 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
3117 * XDG Base Directory Specification</ulink>.
3118 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
3120 * On Windows is the directory that contains application data for all users.
3121 * A typical path is C:\Documents and Settings\All Users\Application Data.
3122 * This folder is used for application data that is not user specific.
3123 * For example, an application can store a spell-check dictionary, a database
3124 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
3125 * This information will not roam and is available to anyone using the computer.
3127 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
3128 * not be modified or freed.
3131 const gchar * const *
3132 g_get_system_config_dirs (void)
3134 gchar *conf_dirs, **conf_dir_vector;
3136 G_LOCK (g_utils_global);
3138 if (!g_system_config_dirs)
3141 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
3144 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3149 /* Return empty list */
3150 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
3153 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
3155 if (!conf_dirs || !conf_dirs[0])
3156 conf_dirs = "/etc/xdg";
3158 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
3161 g_system_config_dirs = conf_dir_vector;
3164 conf_dir_vector = g_system_config_dirs;
3165 G_UNLOCK (g_utils_global);
3167 return (const gchar * const *) conf_dir_vector;
3172 static GHashTable *alias_table = NULL;
3174 /* read an alias file for the locales */
3176 read_aliases (gchar *file)
3182 alias_table = g_hash_table_new (g_str_hash, g_str_equal);
3183 fp = fopen (file,"r");
3186 while (fgets (buf, 256, fp))
3192 /* Line is a comment */
3193 if ((buf[0] == '#') || (buf[0] == '\0'))
3196 /* Reads first column */
3197 for (p = buf, q = NULL; *p; p++) {
3198 if ((*p == '\t') || (*p == ' ') || (*p == ':')) {
3201 while ((*q == '\t') || (*q == ' ')) {
3207 /* The line only had one column */
3208 if (!q || *q == '\0')
3211 /* Read second column */
3212 for (p = q; *p; p++) {
3213 if ((*p == '\t') || (*p == ' ')) {
3219 /* Add to alias table if necessary */
3220 if (!g_hash_table_lookup (alias_table, buf)) {
3221 g_hash_table_insert (alias_table, g_strdup (buf), g_strdup (q));
3230 unalias_lang (char *lang)
3237 read_aliases ("/usr/share/locale/locale.alias");
3240 while ((p = g_hash_table_lookup (alias_table, lang)) && (strcmp (p, lang) != 0))
3245 static gboolean said_before = FALSE;
3247 g_warning ("Too many alias levels for a locale, "
3248 "may indicate a loop");
3257 /* Mask for components of locale spec. The ordering here is from
3258 * least significant to most significant
3262 COMPONENT_CODESET = 1 << 0,
3263 COMPONENT_TERRITORY = 1 << 1,
3264 COMPONENT_MODIFIER = 1 << 2
3267 /* Break an X/Open style locale specification into components
3270 explode_locale (const gchar *locale,
3276 const gchar *uscore_pos;
3277 const gchar *at_pos;
3278 const gchar *dot_pos;
3282 uscore_pos = strchr (locale, '_');
3283 dot_pos = strchr (uscore_pos ? uscore_pos : locale, '.');
3284 at_pos = strchr (dot_pos ? dot_pos : (uscore_pos ? uscore_pos : locale), '@');
3288 mask |= COMPONENT_MODIFIER;
3289 *modifier = g_strdup (at_pos);
3292 at_pos = locale + strlen (locale);
3296 mask |= COMPONENT_CODESET;
3297 *codeset = g_strndup (dot_pos, at_pos - dot_pos);
3304 mask |= COMPONENT_TERRITORY;
3305 *territory = g_strndup (uscore_pos, dot_pos - uscore_pos);
3308 uscore_pos = dot_pos;
3310 *language = g_strndup (locale, uscore_pos - locale);
3316 * Compute all interesting variants for a given locale name -
3317 * by stripping off different components of the value.
3319 * For simplicity, we assume that the locale is in
3320 * X/Open format: language[_territory][.codeset][@modifier]
3322 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
3323 * as well. We could just copy the code from glibc wholesale
3324 * but it is big, ugly, and complicated, so I'm reluctant
3325 * to do so when this should handle 99% of the time...
3328 append_locale_variants (GPtrArray *array,
3329 const gchar *locale)
3331 gchar *language = NULL;
3332 gchar *territory = NULL;
3333 gchar *codeset = NULL;
3334 gchar *modifier = NULL;
3339 g_return_if_fail (locale != NULL);
3341 mask = explode_locale (locale, &language, &territory, &codeset, &modifier);
3343 /* Iterate through all possible combinations, from least attractive
3344 * to most attractive.
3346 for (j = 0; j <= mask; ++j)
3350 if ((i & ~mask) == 0)
3352 gchar *val = g_strconcat (language,
3353 (i & COMPONENT_TERRITORY) ? territory : "",
3354 (i & COMPONENT_CODESET) ? codeset : "",
3355 (i & COMPONENT_MODIFIER) ? modifier : "",
3357 g_ptr_array_add (array, val);
3362 if (mask & COMPONENT_CODESET)
3364 if (mask & COMPONENT_TERRITORY)
3366 if (mask & COMPONENT_MODIFIER)
3371 * g_get_locale_variants:
3372 * @locale: a locale identifier
3374 * Returns a list of derived variants of @locale, which can be used to
3375 * e.g. construct locale-dependent filenames or search paths. The returned
3376 * list is sorted from most desirable to least desirable.
3377 * This function handles territory, charset and extra locale modifiers.
3379 * For example, if @locale is "fr_BE", then the returned list
3382 * If you need the list of variants for the <emphasis>current locale</emphasis>,
3383 * use g_get_language_names().
3385 * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
3386 * allocated array of newly allocated strings with the locale variants. Free with
3392 g_get_locale_variants (const gchar *locale)
3396 g_return_val_if_fail (locale != NULL, NULL);
3398 array = g_ptr_array_sized_new (8);
3399 append_locale_variants (array, locale);
3400 g_ptr_array_add (array, NULL);
3402 return (gchar **) g_ptr_array_free (array, FALSE);
3405 /* The following is (partly) taken from the gettext package.
3406 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
3408 static const gchar *
3409 guess_category_value (const gchar *category_name)
3411 const gchar *retval;
3413 /* The highest priority value is the `LANGUAGE' environment
3414 variable. This is a GNU extension. */
3415 retval = g_getenv ("LANGUAGE");
3416 if ((retval != NULL) && (retval[0] != '\0'))
3419 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
3420 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
3421 systems this can be done by the `setlocale' function itself. */
3423 /* Setting of LC_ALL overwrites all other. */
3424 retval = g_getenv ("LC_ALL");
3425 if ((retval != NULL) && (retval[0] != '\0'))
3428 /* Next comes the name of the desired category. */
3429 retval = g_getenv (category_name);
3430 if ((retval != NULL) && (retval[0] != '\0'))
3433 /* Last possibility is the LANG environment variable. */
3434 retval = g_getenv ("LANG");
3435 if ((retval != NULL) && (retval[0] != '\0'))
3438 #ifdef G_PLATFORM_WIN32
3439 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
3440 * LANG, which we already did above. Oh well. The main point of
3441 * calling g_win32_getlocale() is to get the thread's locale as used
3442 * by Windows and the Microsoft C runtime (in the "English_United
3443 * States" format) translated into the Unixish format.
3446 char *locale = g_win32_getlocale ();
3447 retval = g_intern_string (locale);
3456 typedef struct _GLanguageNamesCache GLanguageNamesCache;
3458 struct _GLanguageNamesCache {
3460 gchar **language_names;
3464 language_names_cache_free (gpointer data)
3466 GLanguageNamesCache *cache = data;
3467 g_free (cache->languages);
3468 g_strfreev (cache->language_names);
3473 * g_get_language_names:
3475 * Computes a list of applicable locale names, which can be used to
3476 * e.g. construct locale-dependent filenames or search paths. The returned
3477 * list is sorted from most desirable to least desirable and always contains
3478 * the default locale "C".
3480 * For example, if LANGUAGE=de:en_US, then the returned list is
3481 * "de", "en_US", "en", "C".
3483 * This function consults the environment variables <envar>LANGUAGE</envar>,
3484 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
3485 * to find the list of locales specified by the user.
3487 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
3488 * that must not be modified or freed.
3492 const gchar * const *
3493 g_get_language_names (void)
3495 static GPrivate cache_private = G_PRIVATE_INIT (language_names_cache_free);
3496 GLanguageNamesCache *cache = g_private_get (&cache_private);
3501 cache = g_new0 (GLanguageNamesCache, 1);
3502 g_private_set (&cache_private, cache);
3505 value = guess_category_value ("LC_MESSAGES");
3509 if (!(cache->languages && strcmp (cache->languages, value) == 0))
3514 g_free (cache->languages);
3515 g_strfreev (cache->language_names);
3516 cache->languages = g_strdup (value);
3518 array = g_ptr_array_sized_new (8);
3520 alist = g_strsplit (value, ":", 0);
3521 for (a = alist; *a; a++)
3522 append_locale_variants (array, unalias_lang (*a));
3524 g_ptr_array_add (array, g_strdup ("C"));
3525 g_ptr_array_add (array, NULL);
3527 cache->language_names = (gchar **) g_ptr_array_free (array, FALSE);
3530 return (const gchar * const *) cache->language_names;
3534 * g_nullify_pointer:
3535 * @nullify_location: the memory address of the pointer.
3537 * Set the pointer at the specified location to %NULL.
3540 g_nullify_pointer (gpointer *nullify_location)
3542 g_return_if_fail (nullify_location != NULL);
3544 *nullify_location = NULL;
3550 * Get the codeset for the current locale.
3552 * Return value: a newly allocated string containing the name
3553 * of the codeset. This string must be freed with g_free().
3556 g_get_codeset (void)
3558 const gchar *charset;
3560 g_get_charset (&charset);
3562 return g_strdup (charset);
3568 * _glib_get_locale_dir:
3570 * Return the path to the share\locale or lib\locale subfolder of the
3571 * GLib installation folder. The path is in the system codepage. We
3572 * have to use system codepage as bindtextdomain() doesn't have a
3576 _glib_get_locale_dir (void)
3578 gchar *install_dir = NULL, *locale_dir;
3579 gchar *retval = NULL;
3581 if (glib_dll != NULL)
3582 install_dir = g_win32_get_package_installation_directory_of_module (glib_dll);
3587 * Append "/share/locale" or "/lib/locale" depending on whether
3588 * autoconfigury detected GNU gettext or not.
3590 const char *p = GLIB_LOCALE_DIR + strlen (GLIB_LOCALE_DIR);
3596 locale_dir = g_build_filename (install_dir, p, NULL);
3598 retval = g_win32_locale_filename_from_utf8 (locale_dir);
3600 g_free (install_dir);
3601 g_free (locale_dir);
3607 return g_strdup ("");
3610 #undef GLIB_LOCALE_DIR
3612 #endif /* G_OS_WIN32 */
3615 ensure_gettext_initialized (void)
3617 static gsize initialised;
3619 if (g_once_init_enter (&initialised))
3622 gchar *tmp = _glib_get_locale_dir ();
3623 bindtextdomain (GETTEXT_PACKAGE, tmp);
3626 bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
3628 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
3629 bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
3631 g_once_init_leave (&initialised, TRUE);
3637 * @str: The string to be translated
3639 * Returns the translated string from the glib translations.
3640 * This is an internal function and should only be used by
3641 * the internals of glib (such as libgio).
3643 * Returns: the transation of @str to the current locale
3646 glib_gettext (const gchar *str)
3648 ensure_gettext_initialized();
3650 return g_dgettext (GETTEXT_PACKAGE, str);
3655 * @msgctxtid: a combined message context and message id, separated
3656 * by a \004 character
3657 * @msgidoffset: the offset of the message id in @msgctxid
3659 * This function is a variant of glib_gettext() which supports
3660 * a disambiguating message context. See g_dpgettext() for full
3663 * This is an internal function and should only be used by
3664 * the internals of glib (such as libgio).
3666 * Returns: the transation of @str to the current locale
3669 glib_pgettext(const gchar *msgctxtid,
3672 ensure_gettext_initialized();
3674 return g_dpgettext (GETTEXT_PACKAGE, msgctxtid, msgidoffset);
3677 #if defined (G_OS_WIN32) && !defined (_WIN64)
3679 /* Binary compatibility versions. Not for newly compiled code. */
3681 #undef g_find_program_in_path
3684 g_find_program_in_path (const gchar *program)
3686 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
3687 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
3690 g_free (utf8_program);
3691 if (utf8_retval == NULL)
3693 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
3694 g_free (utf8_retval);
3699 #undef g_get_current_dir
3702 g_get_current_dir (void)
3704 gchar *utf8_dir = g_get_current_dir_utf8 ();
3705 gchar *dir = g_locale_from_utf8 (utf8_dir, -1, NULL, NULL, NULL);
3713 g_getenv (const gchar *variable)
3715 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3716 const gchar *utf8_value = g_getenv_utf8 (utf8_variable);
3720 g_free (utf8_variable);
3723 value = g_locale_from_utf8 (utf8_value, -1, NULL, NULL, NULL);
3724 quark = g_quark_from_string (value);
3727 return g_quark_to_string (quark);
3733 g_setenv (const gchar *variable,
3737 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3738 gchar *utf8_value = g_locale_to_utf8 (value, -1, NULL, NULL, NULL);
3739 gboolean retval = g_setenv_utf8 (utf8_variable, utf8_value, overwrite);
3741 g_free (utf8_variable);
3742 g_free (utf8_value);
3750 g_unsetenv (const gchar *variable)
3752 gchar *utf8_variable = g_locale_to_utf8 (variable, -1, NULL, NULL, NULL);
3754 g_unsetenv_utf8 (utf8_variable);
3756 g_free (utf8_variable);
3759 #undef g_get_user_name
3762 g_get_user_name (void)
3764 g_get_any_init_locked ();
3765 return g_user_name_cp;
3768 #undef g_get_real_name
3771 g_get_real_name (void)
3773 g_get_any_init_locked ();
3774 return g_real_name_cp;
3777 #undef g_get_home_dir
3780 g_get_home_dir (void)
3782 g_get_any_init_locked ();
3783 return g_home_dir_cp;
3786 #undef g_get_tmp_dir
3789 g_get_tmp_dir (void)
3791 g_get_any_init_locked ();
3792 return g_tmp_dir_cp;