1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1998 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
21 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
22 * file for a list of people on the GLib Team. See the ChangeLog
23 * files for a list of changes. These files are distributed with
24 * GLib at ftp://ftp.gtk.org/pub/gtk/.
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
41 #include <ctype.h> /* For tolower() */
43 #include <sys/types.h>
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
52 #ifdef HAVE_CRT_EXTERNS_H
53 #include <crt_externs.h> /* for _NSGetEnviron */
56 /* implement gutils's inline functions
58 #define G_IMPLEMENT_INLINES 1
62 #include "glib-init.h"
64 #include "gfileutils.h"
68 #include "gtestutils.h"
70 #include "gstrfuncs.h"
74 #ifdef G_PLATFORM_WIN32
82 * @title: Miscellaneous Utility Functions
83 * @short_description: a selection of portable utility functions
85 * These are portable utility functions.
88 #ifdef G_PLATFORM_WIN32
90 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
91 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
92 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
94 # include <lmcons.h> /* For UNLEN */
95 #endif /* G_PLATFORM_WIN32 */
100 /* older SDK (e.g. msvc 5.0) does not have these*/
101 # ifndef CSIDL_MYMUSIC
102 # define CSIDL_MYMUSIC 13
104 # ifndef CSIDL_MYVIDEO
105 # define CSIDL_MYVIDEO 14
107 # ifndef CSIDL_INTERNET_CACHE
108 # define CSIDL_INTERNET_CACHE 32
110 # ifndef CSIDL_COMMON_APPDATA
111 # define CSIDL_COMMON_APPDATA 35
113 # ifndef CSIDL_MYPICTURES
114 # define CSIDL_MYPICTURES 0x27
116 # ifndef CSIDL_COMMON_DOCUMENTS
117 # define CSIDL_COMMON_DOCUMENTS 46
119 # ifndef CSIDL_PROFILE
120 # define CSIDL_PROFILE 40
122 # include <process.h>
126 #include <CoreServices/CoreServices.h>
130 #include <langinfo.h>
133 #ifdef G_PLATFORM_WIN32
136 _glib_get_dll_directory (void)
140 wchar_t wc_fn[MAX_PATH];
143 if (glib_dll == NULL)
147 /* This code is different from that in
148 * g_win32_get_package_installation_directory_of_module() in that
149 * here we return the actual folder where the GLib DLL is. We don't
150 * do the check for it being in a "bin" or "lib" subfolder and then
151 * returning the parent of that.
153 * In a statically built GLib, glib_dll will be NULL and we will
154 * thus look up the application's .exe file's location.
156 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
159 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
161 p = strrchr (retval, G_DIR_SEPARATOR);
174 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
177 * @dest: the destination address to copy the bytes to.
178 * @src: the source address to copy the bytes from.
179 * @len: the number of bytes to copy.
181 * Copies a block of memory @len bytes long, from @src to @dest.
182 * The source and destination areas may overlap.
184 * In order to use this function, you must include
185 * <filename>string.h</filename> yourself, because this macro will
186 * typically simply resolve to memmove() and GLib does not include
187 * <filename>string.h</filename> for you.
190 g_memmove (gpointer dest,
194 gchar* destptr = dest;
195 const gchar* srcptr = src;
196 if (src + len < dest || dest + len < src)
198 bcopy (src, dest, len);
201 else if (dest <= src)
204 *(destptr++) = *(srcptr++);
211 *(--destptr) = *(--srcptr);
214 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
222 * @func: (scope async): the function to call on normal program termination.
224 * Specifies a function to be called at normal program termination.
226 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
227 * macro that maps to a call to the atexit() function in the C
228 * library. This means that in case the code that calls g_atexit(),
229 * i.e. atexit(), is in a DLL, the function will be called when the
230 * DLL is detached from the program. This typically makes more sense
231 * than that the function is called when the GLib DLL is detached,
232 * which happened earlier when g_atexit() was a function in the GLib
235 * The behaviour of atexit() in the context of dynamically loaded
236 * modules is not formally specified and varies wildly.
238 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
239 * loaded module which is unloaded before the program terminates might
240 * well cause a crash at program exit.
242 * Some POSIX systems implement atexit() like Windows, and have each
243 * dynamically loaded module maintain an own atexit chain that is
244 * called when the module is unloaded.
246 * On other POSIX systems, before a dynamically loaded module is
247 * unloaded, the registered atexit functions (if any) residing in that
248 * module are called, regardless where the code that registered them
249 * resided. This is presumably the most robust approach.
251 * As can be seen from the above, for portability it's best to avoid
252 * calling g_atexit() (or atexit()) except in the main executable of a
255 * Deprecated:2.32: It is best to avoid g_atexit().
258 g_atexit (GVoidFunc func)
261 const gchar *error = NULL;
263 /* keep this in sync with glib.h */
265 #ifdef G_NATIVE_ATEXIT
266 result = ATEXIT (func);
268 error = g_strerror (errno);
269 #elif defined (HAVE_ATEXIT)
270 # ifdef NeXT /* @#%@! NeXTStep */
271 result = !atexit ((void (*)(void)) func);
273 error = g_strerror (errno);
275 result = atexit ((void (*)(void)) func);
277 error = g_strerror (errno);
279 #elif defined (HAVE_ON_EXIT)
280 result = on_exit ((void (*)(int, void *)) func, NULL);
282 error = g_strerror (errno);
285 error = "no implementation";
286 #endif /* G_NATIVE_ATEXIT */
289 g_error ("Could not register atexit() function: %s", error);
292 /* Based on execvp() from GNU Libc.
293 * Some of this code is cut-and-pasted into gspawn.c
297 my_strchrnul (const gchar *str,
300 gchar *p = (gchar*)str;
301 while (*p && (*p != c))
309 static gchar *inner_find_program_in_path (const gchar *program);
312 g_find_program_in_path (const gchar *program)
314 const gchar *last_dot = strrchr (program, '.');
316 if (last_dot == NULL ||
317 strchr (last_dot, '\\') != NULL ||
318 strchr (last_dot, '/') != NULL)
320 const gint program_length = strlen (program);
321 gchar *pathext = g_build_path (";",
322 ".exe;.cmd;.bat;.com",
323 g_getenv ("PATHEXT"),
326 gchar *decorated_program;
332 gchar *q = my_strchrnul (p, ';');
334 decorated_program = g_malloc (program_length + (q-p) + 1);
335 memcpy (decorated_program, program, program_length);
336 memcpy (decorated_program+program_length, p, q-p);
337 decorated_program [program_length + (q-p)] = '\0';
339 retval = inner_find_program_in_path (decorated_program);
340 g_free (decorated_program);
348 } while (*p++ != '\0');
353 return inner_find_program_in_path (program);
359 * g_find_program_in_path:
360 * @program: a program name in the GLib file name encoding
362 * Locates the first executable named @program in the user's path, in the
363 * same way that execvp() would locate it. Returns an allocated string
364 * with the absolute path name, or %NULL if the program is not found in
365 * the path. If @program is already an absolute path, returns a copy of
366 * @program if @program exists and is executable, and %NULL otherwise.
368 * On Windows, if @program does not have a file type suffix, tries
369 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
370 * the <envar>PATHEXT</envar> environment variable.
372 * On Windows, it looks for the file in the same way as CreateProcess()
373 * would. This means first in the directory where the executing
374 * program was loaded from, then in the current directory, then in the
375 * Windows 32-bit system directory, then in the Windows directory, and
376 * finally in the directories in the <envar>PATH</envar> environment
377 * variable. If the program is found, the return value contains the
378 * full name including the type suffix.
380 * Return value: absolute path, or %NULL
384 inner_find_program_in_path (const gchar *program)
387 g_find_program_in_path (const gchar *program)
390 const gchar *path, *p;
391 gchar *name, *freeme;
393 const gchar *path_copy;
394 gchar *filename = NULL, *appdir = NULL;
395 gchar *sysdir = NULL, *windir = NULL;
397 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
403 g_return_val_if_fail (program != NULL, NULL);
405 /* If it is an absolute path, or a relative path including subdirectories,
406 * don't look in PATH.
408 if (g_path_is_absolute (program)
409 || strchr (program, G_DIR_SEPARATOR) != NULL
411 || strchr (program, '/') != NULL
415 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
416 !g_file_test (program, G_FILE_TEST_IS_DIR))
417 return g_strdup (program);
422 path = g_getenv ("PATH");
423 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
426 /* There is no `PATH' in the environment. The default
427 * search path in GNU libc is the current directory followed by
428 * the path `confstr' returns for `_CS_PATH'.
431 /* In GLib we put . last, for security, and don't use the
432 * unportable confstr(); UNIX98 does not actually specify
433 * what to search if PATH is unset. POSIX may, dunno.
436 path = "/bin:/usr/bin:.";
439 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
440 if (n > 0 && n < MAXPATHLEN)
441 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
443 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
444 if (n > 0 && n < MAXPATHLEN)
445 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
447 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
448 if (n > 0 && n < MAXPATHLEN)
449 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
453 appdir = g_path_get_dirname (filename);
457 path = g_strdup (path);
461 const gchar *tem = path;
462 path = g_strconcat (windir, ";", path, NULL);
463 g_free ((gchar *) tem);
469 const gchar *tem = path;
470 path = g_strconcat (sysdir, ";", path, NULL);
471 g_free ((gchar *) tem);
476 const gchar *tem = path;
477 path = g_strconcat (".;", path, NULL);
478 g_free ((gchar *) tem);
483 const gchar *tem = path;
484 path = g_strconcat (appdir, ";", path, NULL);
485 g_free ((gchar *) tem);
492 len = strlen (program) + 1;
493 pathlen = strlen (path);
494 freeme = name = g_malloc (pathlen + len + 1);
496 /* Copy the file name at the top, including '\0' */
497 memcpy (name + pathlen + 1, program, len);
498 name = name + pathlen;
499 /* And add the slash before the filename */
500 *name = G_DIR_SEPARATOR;
508 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
511 /* Two adjacent colons, or a colon at the beginning or the end
512 * of `PATH' means to search the current directory.
516 startp = memcpy (name - (p - path), path, p - path);
518 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
519 !g_file_test (startp, G_FILE_TEST_IS_DIR))
522 ret = g_strdup (startp);
525 g_free ((gchar *) path_copy);
530 while (*p++ != '\0');
534 g_free ((gchar *) path_copy);
542 * @mask: a #gulong containing flags
543 * @nth_bit: the index of the bit to start the search from
545 * Find the position of the first bit set in @mask, searching
546 * from (but not including) @nth_bit upwards. Bits are numbered
547 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
548 * usually). To start searching from the 0th bit, set @nth_bit to -1.
550 * Returns: the index of the first bit set which is higher than @nth_bit
555 * @mask: a #gulong containing flags
556 * @nth_bit: the index of the bit to start the search from
558 * Find the position of the first bit set in @mask, searching
559 * from (but not including) @nth_bit downwards. Bits are numbered
560 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
561 * usually). To start searching from the last bit, set @nth_bit to
562 * -1 or GLIB_SIZEOF_LONG * 8.
564 * Returns: the index of the first bit set which is lower than @nth_bit
571 * Gets the number of bits used to hold @number,
572 * e.g. if @number is 4, 3 bits are needed.
574 * Returns: the number of bits used to hold @number
577 G_LOCK_DEFINE_STATIC (g_utils_global);
579 static gchar *g_tmp_dir = NULL;
580 static gchar *g_user_name = NULL;
581 static gchar *g_real_name = NULL;
582 static gchar *g_home_dir = NULL;
583 static gchar *g_host_name = NULL;
586 /* System codepage versions of the above, kept at file level so that they,
587 * too, are produced only once.
589 static gchar *g_tmp_dir_cp = NULL;
590 static gchar *g_user_name_cp = NULL;
591 static gchar *g_real_name_cp = NULL;
592 static gchar *g_home_dir_cp = NULL;
595 static gchar *g_user_data_dir = NULL;
596 static gchar **g_system_data_dirs = NULL;
597 static gchar *g_user_cache_dir = NULL;
598 static gchar *g_user_config_dir = NULL;
599 static gchar **g_system_config_dirs = NULL;
601 static gchar **g_user_special_dirs = NULL;
603 /* fifteen minutes of fame for everybody */
604 #define G_USER_DIRS_EXPIRE 15 * 60
609 get_special_folder (int csidl)
611 wchar_t path[MAX_PATH+1];
613 LPITEMIDLIST pidl = NULL;
615 gchar *retval = NULL;
617 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
620 b = SHGetPathFromIDListW (pidl, path);
622 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
623 CoTaskMemFree (pidl);
629 get_windows_directory_root (void)
631 wchar_t wwindowsdir[MAX_PATH];
633 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
635 /* Usually X:\Windows, but in terminal server environments
636 * might be an UNC path, AFAIK.
638 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
641 if (windowsdir == NULL)
642 return g_strdup ("C:\\");
644 p = (char *) g_path_skip_root (windowsdir);
645 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
651 return g_strdup ("C:\\");
656 /* HOLDS: g_utils_global_lock */
658 g_get_any_init_do (void)
662 g_tmp_dir = g_strdup (g_getenv ("TMPDIR"));
663 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
664 g_tmp_dir = g_strdup (g_getenv ("TMP"));
665 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
666 g_tmp_dir = g_strdup (g_getenv ("TEMP"));
669 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
670 g_tmp_dir = get_windows_directory_root ();
673 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
676 g_tmp_dir = g_strdup (P_tmpdir);
677 k = strlen (g_tmp_dir);
678 if (k > 1 && G_IS_DIR_SEPARATOR (g_tmp_dir[k - 1]))
679 g_tmp_dir[k - 1] = '\0';
683 if (g_tmp_dir == NULL || *g_tmp_dir == '\0')
685 g_tmp_dir = g_strdup ("/tmp");
687 #endif /* !G_OS_WIN32 */
690 /* We check $HOME first for Win32, though it is a last resort for Unix
691 * where we prefer the results of getpwuid().
693 g_home_dir = g_strdup (g_getenv ("HOME"));
695 /* Only believe HOME if it is an absolute path and exists */
698 if (!(g_path_is_absolute (g_home_dir) &&
699 g_file_test (g_home_dir, G_FILE_TEST_IS_DIR)))
706 /* In case HOME is Unix-style (it happens), convert it to
712 while ((p = strchr (g_home_dir, '/')) != NULL)
718 /* USERPROFILE is probably the closest equivalent to $HOME? */
719 if (g_getenv ("USERPROFILE") != NULL)
720 g_home_dir = g_strdup (g_getenv ("USERPROFILE"));
724 g_home_dir = get_special_folder (CSIDL_PROFILE);
727 g_home_dir = get_windows_directory_root ();
728 #endif /* G_OS_WIN32 */
732 struct passwd *pw = NULL;
733 gpointer buffer = NULL;
737 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
739 # ifdef _SC_GETPW_R_SIZE_MAX
740 /* This reurns the maximum length */
741 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
745 # else /* _SC_GETPW_R_SIZE_MAX */
747 # endif /* _SC_GETPW_R_SIZE_MAX */
749 logname = (gchar *) g_getenv ("LOGNAME");
754 /* we allocate 6 extra bytes to work around a bug in
755 * Mac OS < 10.3. See #156446
757 buffer = g_malloc (bufsize + 6);
760 # ifdef HAVE_POSIX_GETPWUID_R
762 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
763 if (!pw || (pw->pw_uid != getuid ())) {
764 /* LOGNAME is lying, fall back to looking up the uid */
765 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
768 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
770 error = error < 0 ? errno : error;
771 # else /* HAVE_NONPOSIX_GETPWUID_R */
772 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
773 # if defined(_AIX) || defined(__hpux)
774 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
775 pw = error == 0 ? &pwd : NULL;
778 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
779 if (!pw || (pw->pw_uid != getuid ())) {
780 /* LOGNAME is lying, fall back to looking up the uid */
781 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
784 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
786 error = pw ? 0 : errno;
788 # endif /* HAVE_NONPOSIX_GETPWUID_R */
792 /* we bail out prematurely if the user id can't be found
793 * (should be pretty rare case actually), or if the buffer
794 * should be sufficiently big and lookups are still not
797 if (error == 0 || error == ENOENT)
799 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
803 if (bufsize > 32 * 1024)
805 g_warning ("getpwuid_r(): failed due to: %s.",
814 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
819 pw = getpwuid (getuid ());
824 g_user_name = g_strdup (pw->pw_name);
826 if (pw->pw_gecos && *pw->pw_gecos != '\0')
828 gchar **gecos_fields;
831 /* split the gecos field and substitute '&' */
832 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
833 name_parts = g_strsplit (gecos_fields[0], "&", 0);
834 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
835 g_real_name = g_strjoinv (pw->pw_name, name_parts);
836 g_strfreev (gecos_fields);
837 g_strfreev (name_parts);
841 g_home_dir = g_strdup (pw->pw_dir);
846 #else /* !HAVE_PWD_H */
851 wchar_t buffer[UNLEN+1];
853 if (GetUserNameW (buffer, (LPDWORD) &len))
855 g_user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
856 g_real_name = g_strdup (g_user_name);
859 #endif /* G_OS_WIN32 */
861 #endif /* !HAVE_PWD_H */
865 g_home_dir = g_strdup (g_getenv ("HOME"));
869 /* change '\\' in %HOME% to '/' */
870 g_strdelimit (g_home_dir, "\\",'/');
873 g_user_name = g_strdup ("somebody");
875 g_real_name = g_strdup ("Unknown");
879 gboolean hostname_fail = (gethostname (hostname, sizeof (hostname)) == -1);
881 DWORD size = sizeof (hostname);
882 gboolean hostname_fail = (!GetComputerName (hostname, &size));
884 g_host_name = g_strdup (hostname_fail ? "localhost" : hostname);
888 g_tmp_dir_cp = g_locale_from_utf8 (g_tmp_dir, -1, NULL, NULL, NULL);
889 g_user_name_cp = g_locale_from_utf8 (g_user_name, -1, NULL, NULL, NULL);
890 g_real_name_cp = g_locale_from_utf8 (g_real_name, -1, NULL, NULL, NULL);
893 g_tmp_dir_cp = g_strdup ("\\");
895 g_user_name_cp = g_strdup ("somebody");
897 g_real_name_cp = g_strdup ("Unknown");
899 /* home_dir might be NULL, unlike tmp_dir, user_name and
903 g_home_dir_cp = g_locale_from_utf8 (g_home_dir, -1, NULL, NULL, NULL);
905 g_home_dir_cp = NULL;
906 #endif /* G_OS_WIN32 */
910 g_get_any_init (void)
913 g_get_any_init_do ();
917 g_get_any_init_locked (void)
919 G_LOCK (g_utils_global);
921 G_UNLOCK (g_utils_global);
928 * Gets the user name of the current user. The encoding of the returned
929 * string is system-defined. On UNIX, it might be the preferred file name
930 * encoding, or something else, and there is no guarantee that it is even
931 * consistent on a machine. On Windows, it is always UTF-8.
933 * Returns: the user name of the current user.
936 g_get_user_name (void)
938 g_get_any_init_locked ();
945 * Gets the real name of the user. This usually comes from the user's entry
946 * in the <filename>passwd</filename> file. The encoding of the returned
947 * string is system-defined. (On Windows, it is, however, always UTF-8.)
948 * If the real user name cannot be determined, the string "Unknown" is
951 * Returns: the user's real name.
954 g_get_real_name (void)
956 g_get_any_init_locked ();
963 * Gets the current user's home directory as defined in the
966 * Note that in contrast to traditional UNIX tools, this function
967 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
968 * environment variable.
970 * One of the reasons for this decision is that applications in many
971 * cases need special handling to deal with the case where
972 * <envar>HOME</envar> is
974 * <member>Not owned by the user</member>
975 * <member>Not writeable</member>
976 * <member>Not even readable</member>
978 * Since applications are in general <emphasis>not</emphasis> written
979 * to deal with these situations it was considered better to make
980 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
981 * return the real home directory for the user. If applications
982 * want to pay attention to <envar>HOME</envar>, they can do:
984 * const char *homedir = g_getenv ("HOME");
986 * homedir = g_get_home_dir (<!-- -->);
989 * Returns: the current user's home directory
992 g_get_home_dir (void)
994 g_get_any_init_locked ();
1001 * Gets the directory to use for temporary files. This is found from
1002 * inspecting the environment variables <envar>TMPDIR</envar>,
1003 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1004 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1005 * The encoding of the returned string is system-defined. On Windows,
1006 * it is always UTF-8. The return value is never %NULL or the empty string.
1008 * Returns: the directory to use for temporary files.
1011 g_get_tmp_dir (void)
1013 g_get_any_init_locked ();
1020 * Return a name for the machine.
1022 * The returned name is not necessarily a fully-qualified domain name,
1023 * or even present in DNS or some other name service at all. It need
1024 * not even be unique on your local network or site, but usually it
1025 * is. Callers should not rely on the return value having any specific
1026 * properties like uniqueness for security purposes. Even if the name
1027 * of the machine is changed while an application is running, the
1028 * return value from this function does not change. The returned
1029 * string is owned by GLib and should not be modified or freed. If no
1030 * name can be determined, a default fixed string "localhost" is
1033 * Returns: the host name of the machine.
1038 g_get_host_name (void)
1040 g_get_any_init_locked ();
1044 G_LOCK_DEFINE_STATIC (g_prgname);
1045 static gchar *g_prgname = NULL;
1050 * Gets the name of the program. This name should <emphasis>not</emphasis>
1051 * be localized, contrast with g_get_application_name().
1052 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1053 * which is called by gtk_init(). The program name is found by taking
1054 * the last component of <literal>argv[0]</literal>.)
1056 * Returns: the name of the program. The returned string belongs
1057 * to GLib and must not be modified or freed.
1060 g_get_prgname (void)
1066 if (g_prgname == NULL)
1068 static gboolean beenhere = FALSE;
1072 gchar *utf8_buf = NULL;
1073 wchar_t buf[MAX_PATH+1];
1076 if (GetModuleFileNameW (GetModuleHandle (NULL),
1077 buf, G_N_ELEMENTS (buf)) > 0)
1078 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1082 g_prgname = g_path_get_basename (utf8_buf);
1089 G_UNLOCK (g_prgname);
1096 * @prgname: the name of the program.
1098 * Sets the name of the program. This name should <emphasis>not</emphasis>
1099 * be localized, contrast with g_set_application_name(). Note that for
1100 * thread-safety reasons this function can only be called once.
1103 g_set_prgname (const gchar *prgname)
1107 g_prgname = g_strdup (prgname);
1108 G_UNLOCK (g_prgname);
1111 G_LOCK_DEFINE_STATIC (g_application_name);
1112 static gchar *g_application_name = NULL;
1115 * g_get_application_name:
1117 * Gets a human-readable name for the application, as set by
1118 * g_set_application_name(). This name should be localized if
1119 * possible, and is intended for display to the user. Contrast with
1120 * g_get_prgname(), which gets a non-localized name. If
1121 * g_set_application_name() has not been called, returns the result of
1122 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1125 * Return value: human-readable application name. may return %NULL
1130 g_get_application_name (void)
1134 G_LOCK (g_application_name);
1135 retval = g_application_name;
1136 G_UNLOCK (g_application_name);
1139 return g_get_prgname ();
1145 * g_set_application_name:
1146 * @application_name: localized name of the application
1148 * Sets a human-readable name for the application. This name should be
1149 * localized if possible, and is intended for display to the user.
1150 * Contrast with g_set_prgname(), which sets a non-localized name.
1151 * g_set_prgname() will be called automatically by gtk_init(),
1152 * but g_set_application_name() will not.
1154 * Note that for thread safety reasons, this function can only
1157 * The application name will be used in contexts such as error messages,
1158 * or when displaying an application's name in the task list.
1163 g_set_application_name (const gchar *application_name)
1165 gboolean already_set = FALSE;
1167 G_LOCK (g_application_name);
1168 if (g_application_name)
1171 g_application_name = g_strdup (application_name);
1172 G_UNLOCK (g_application_name);
1175 g_warning ("g_set_application_name() called multiple times");
1179 * g_get_user_data_dir:
1181 * Returns a base directory in which to access application data such
1182 * as icons that is customized for a particular user.
1184 * On UNIX platforms this is determined using the mechanisms described in
1185 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1186 * XDG Base Directory Specification</ulink>.
1187 * In this case the directory retrieved will be XDG_DATA_HOME.
1189 * On Windows this is the folder to use for local (as opposed to
1190 * roaming) application data. See documentation for
1191 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1192 * what g_get_user_config_dir() returns.
1194 * Return value: a string owned by GLib that must not be modified
1199 g_get_user_data_dir (void)
1203 G_LOCK (g_utils_global);
1205 if (!g_user_data_dir)
1208 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1210 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1212 if (data_dir && data_dir[0])
1213 data_dir = g_strdup (data_dir);
1215 if (!data_dir || !data_dir[0])
1220 data_dir = g_build_filename (g_home_dir, ".local",
1223 data_dir = g_build_filename (g_tmp_dir, g_user_name, ".local",
1227 g_user_data_dir = data_dir;
1230 data_dir = g_user_data_dir;
1232 G_UNLOCK (g_utils_global);
1238 g_init_user_config_dir (void)
1242 if (!g_user_config_dir)
1245 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1247 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1249 if (config_dir && config_dir[0])
1250 config_dir = g_strdup (config_dir);
1252 if (!config_dir || !config_dir[0])
1257 config_dir = g_build_filename (g_home_dir, ".config", NULL);
1259 config_dir = g_build_filename (g_tmp_dir, g_user_name, ".config", NULL);
1262 g_user_config_dir = config_dir;
1267 * g_get_user_config_dir:
1269 * Returns a base directory in which to store user-specific application
1270 * configuration information such as user preferences and settings.
1272 * On UNIX platforms this is determined using the mechanisms described in
1273 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1274 * XDG Base Directory Specification</ulink>.
1275 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1277 * On Windows this is the folder to use for local (as opposed to
1278 * roaming) application data. See documentation for
1279 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1280 * what g_get_user_data_dir() returns.
1282 * Return value: a string owned by GLib that must not be modified
1287 g_get_user_config_dir (void)
1289 G_LOCK (g_utils_global);
1291 g_init_user_config_dir ();
1293 G_UNLOCK (g_utils_global);
1295 return g_user_config_dir;
1299 * g_get_user_cache_dir:
1301 * Returns a base directory in which to store non-essential, cached
1302 * data specific to particular user.
1304 * On UNIX platforms this is determined using the mechanisms described in
1305 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1306 * XDG Base Directory Specification</ulink>.
1307 * In this case the directory retrieved will be XDG_CACHE_HOME.
1309 * On Windows is the directory that serves as a common repository for
1310 * temporary Internet files. A typical path is
1311 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1312 * See documentation for CSIDL_INTERNET_CACHE.
1314 * Return value: a string owned by GLib that must not be modified
1319 g_get_user_cache_dir (void)
1323 G_LOCK (g_utils_global);
1325 if (!g_user_cache_dir)
1328 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1330 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1332 if (cache_dir && cache_dir[0])
1333 cache_dir = g_strdup (cache_dir);
1335 if (!cache_dir || !cache_dir[0])
1340 cache_dir = g_build_filename (g_home_dir, ".cache", NULL);
1342 cache_dir = g_build_filename (g_tmp_dir, g_user_name, ".cache", NULL);
1344 g_user_cache_dir = cache_dir;
1347 cache_dir = g_user_cache_dir;
1349 G_UNLOCK (g_utils_global);
1355 * g_get_user_runtime_dir:
1357 * Returns a directory that is unique to the current user on the local
1360 * On UNIX platforms this is determined using the mechanisms described in
1361 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1362 * XDG Base Directory Specification</ulink>. This is the directory
1363 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1364 * In the case that this variable is not set, GLib will issue a warning
1365 * message to stderr and return the value of g_get_user_cache_dir().
1367 * On Windows this is the folder to use for local (as opposed to
1368 * roaming) application data. See documentation for
1369 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1370 * what g_get_user_config_dir() returns.
1372 * Returns: a string owned by GLib that must not be modified or freed.
1377 g_get_user_runtime_dir (void)
1380 static const gchar *runtime_dir;
1381 static gsize initialised;
1383 if (g_once_init_enter (&initialised))
1385 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1387 g_once_init_leave (&initialised, 1);
1393 /* Both fallback for UNIX and the default
1394 * in Windows: use the user cache directory.
1398 return g_get_user_cache_dir ();
1404 find_folder (OSType type)
1406 gchar *filename = NULL;
1409 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1411 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1415 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1419 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1423 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1425 CFStringGetCString (path, filename,
1426 CFStringGetLength (path) * 3 + 1,
1427 kCFStringEncodingUTF8);
1441 load_user_special_dirs (void)
1443 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1444 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1445 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1446 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1447 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1448 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1449 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1450 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1453 #endif /* HAVE_CARBON */
1455 #if defined(G_OS_WIN32)
1457 load_user_special_dirs (void)
1459 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1463 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1465 static const GUID FOLDERID_Downloads =
1466 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1467 static const GUID FOLDERID_Public =
1468 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1472 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1473 "SHGetKnownFolderPath");
1475 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1476 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1478 if (p_SHGetKnownFolderPath == NULL)
1480 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1485 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1488 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1489 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1490 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1491 CoTaskMemFree (wcp);
1494 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1497 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1498 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1500 if (p_SHGetKnownFolderPath == NULL)
1503 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1508 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1511 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1512 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1513 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1514 CoTaskMemFree (wcp);
1517 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1520 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1521 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1523 #endif /* G_OS_WIN32 */
1525 static void g_init_user_config_dir (void);
1527 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1529 /* adapted from xdg-user-dir-lookup.c
1531 * Copyright (C) 2007 Red Hat Inc.
1533 * Permission is hereby granted, free of charge, to any person
1534 * obtaining a copy of this software and associated documentation files
1535 * (the "Software"), to deal in the Software without restriction,
1536 * including without limitation the rights to use, copy, modify, merge,
1537 * publish, distribute, sublicense, and/or sell copies of the Software,
1538 * and to permit persons to whom the Software is furnished to do so,
1539 * subject to the following conditions:
1541 * The above copyright notice and this permission notice shall be
1542 * included in all copies or substantial portions of the Software.
1544 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1545 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1546 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1547 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1548 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1549 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1550 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1554 load_user_special_dirs (void)
1561 g_init_user_config_dir ();
1562 config_file = g_build_filename (g_user_config_dir,
1566 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1568 g_free (config_file);
1572 lines = g_strsplit (data, "\n", -1);
1573 n_lines = g_strv_length (lines);
1576 for (i = 0; i < n_lines; i++)
1578 gchar *buffer = lines[i];
1581 gboolean is_relative = FALSE;
1582 GUserDirectory directory;
1584 /* Remove newline at end */
1585 len = strlen (buffer);
1586 if (len > 0 && buffer[len - 1] == '\n')
1587 buffer[len - 1] = 0;
1590 while (*p == ' ' || *p == '\t')
1593 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1595 directory = G_USER_DIRECTORY_DESKTOP;
1596 p += strlen ("XDG_DESKTOP_DIR");
1598 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1600 directory = G_USER_DIRECTORY_DOCUMENTS;
1601 p += strlen ("XDG_DOCUMENTS_DIR");
1603 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1605 directory = G_USER_DIRECTORY_DOWNLOAD;
1606 p += strlen ("XDG_DOWNLOAD_DIR");
1608 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1610 directory = G_USER_DIRECTORY_MUSIC;
1611 p += strlen ("XDG_MUSIC_DIR");
1613 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1615 directory = G_USER_DIRECTORY_PICTURES;
1616 p += strlen ("XDG_PICTURES_DIR");
1618 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1620 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1621 p += strlen ("XDG_PUBLICSHARE_DIR");
1623 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1625 directory = G_USER_DIRECTORY_TEMPLATES;
1626 p += strlen ("XDG_TEMPLATES_DIR");
1628 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1630 directory = G_USER_DIRECTORY_VIDEOS;
1631 p += strlen ("XDG_VIDEOS_DIR");
1636 while (*p == ' ' || *p == '\t')
1643 while (*p == ' ' || *p == '\t')
1650 if (strncmp (p, "$HOME", 5) == 0)
1658 d = strrchr (p, '"');
1665 /* remove trailing slashes */
1667 if (d[len - 1] == '/')
1673 g_user_special_dirs[directory] = g_build_filename (g_home_dir, d, NULL);
1676 g_user_special_dirs[directory] = g_strdup (d);
1680 g_free (config_file);
1683 #endif /* G_OS_UNIX && !HAVE_CARBON */
1687 * g_reload_user_special_dirs_cache:
1689 * Resets the cache used for g_get_user_special_dir(), so
1690 * that the latest on-disk version is used. Call this only
1691 * if you just changed the data on disk yourself.
1693 * Due to threadsafety issues this may cause leaking of strings
1694 * that were previously returned from g_get_user_special_dir()
1695 * that can't be freed. We ensure to only leak the data for
1696 * the directories that actually changed value though.
1701 g_reload_user_special_dirs_cache (void)
1705 G_LOCK (g_utils_global);
1707 if (g_user_special_dirs != NULL)
1709 /* save a copy of the pointer, to check if some memory can be preserved */
1710 char **old_g_user_special_dirs = g_user_special_dirs;
1713 /* recreate and reload our cache */
1714 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1715 load_user_special_dirs ();
1717 /* only leak changed directories */
1718 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1720 old_val = old_g_user_special_dirs[i];
1721 if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1724 g_free (g_user_special_dirs[i]);
1725 g_user_special_dirs[i] = old_val;
1731 /* free the old array */
1732 g_free (old_g_user_special_dirs);
1735 G_UNLOCK (g_utils_global);
1739 * g_get_user_special_dir:
1740 * @directory: the logical id of special directory
1742 * Returns the full path of a special directory using its logical id.
1744 * On Unix this is done using the XDG special user directories.
1745 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1746 * falls back to <filename>$HOME/Desktop</filename> when XDG special
1747 * user directories have not been set up.
1749 * Depending on the platform, the user might be able to change the path
1750 * of the special directory without requiring the session to restart; GLib
1751 * will not reflect any change once the special directories are loaded.
1753 * Return value: the path to the specified special directory, or %NULL
1754 * if the logical id was not found. The returned string is owned by
1755 * GLib and should not be modified or freed.
1760 g_get_user_special_dir (GUserDirectory directory)
1762 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1763 directory < G_USER_N_DIRECTORIES, NULL);
1765 G_LOCK (g_utils_global);
1767 if (G_UNLIKELY (g_user_special_dirs == NULL))
1769 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1771 load_user_special_dirs ();
1773 /* Special-case desktop for historical compatibility */
1774 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1778 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] =
1779 g_build_filename (g_home_dir, "Desktop", NULL);
1783 G_UNLOCK (g_utils_global);
1785 return g_user_special_dirs[directory];
1790 #undef g_get_system_data_dirs
1793 get_module_for_address (gconstpointer address)
1795 /* Holds the g_utils_global lock */
1797 static gboolean beenhere = FALSE;
1798 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1799 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1800 HMODULE hmodule = NULL;
1807 p_GetModuleHandleExA =
1808 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1809 "GetModuleHandleExA");
1813 if (p_GetModuleHandleExA == NULL ||
1814 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1815 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1818 MEMORY_BASIC_INFORMATION mbi;
1819 VirtualQuery (address, &mbi, sizeof (mbi));
1820 hmodule = (HMODULE) mbi.AllocationBase;
1827 get_module_share_dir (gconstpointer address)
1833 hmodule = get_module_for_address (address);
1834 if (hmodule == NULL)
1837 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1838 retval = g_build_filename (filename, "share", NULL);
1844 const gchar * const *
1845 g_win32_get_system_data_dirs_for_module (void (*address_of_function)())
1849 static GHashTable *per_module_data_dirs = NULL;
1854 if (address_of_function)
1856 G_LOCK (g_utils_global);
1857 hmodule = get_module_for_address (address_of_function);
1858 if (hmodule != NULL)
1860 if (per_module_data_dirs == NULL)
1861 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1864 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1868 G_UNLOCK (g_utils_global);
1869 return (const gchar * const *) retval;
1875 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1877 /* Documents and Settings\All Users\Application Data */
1878 p = get_special_folder (CSIDL_COMMON_APPDATA);
1880 g_array_append_val (data_dirs, p);
1882 /* Documents and Settings\All Users\Documents */
1883 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1885 g_array_append_val (data_dirs, p);
1887 /* Using the above subfolders of Documents and Settings perhaps
1888 * makes sense from a Windows perspective.
1890 * But looking at the actual use cases of this function in GTK+
1891 * and GNOME software, what we really want is the "share"
1892 * subdirectory of the installation directory for the package
1893 * our caller is a part of.
1895 * The address_of_function parameter, if non-NULL, points to a
1896 * function in the calling module. Use that to determine that
1897 * module's installation folder, and use its "share" subfolder.
1899 * Additionally, also use the "share" subfolder of the installation
1900 * locations of GLib and the .exe file being run.
1902 * To guard against none of the above being what is really wanted,
1903 * callers of this function should have Win32-specific code to look
1904 * up their installation folder themselves, and handle a subfolder
1905 * "share" of it in the same way as the folders returned from this
1909 p = get_module_share_dir (address_of_function);
1911 g_array_append_val (data_dirs, p);
1913 if (glib_dll != NULL)
1915 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1916 p = g_build_filename (glib_root, "share", NULL);
1918 g_array_append_val (data_dirs, p);
1922 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1923 p = g_build_filename (exe_root, "share", NULL);
1925 g_array_append_val (data_dirs, p);
1928 retval = (gchar **) g_array_free (data_dirs, FALSE);
1930 if (address_of_function)
1932 if (hmodule != NULL)
1933 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1934 G_UNLOCK (g_utils_global);
1937 return (const gchar * const *) retval;
1943 * g_get_system_data_dirs:
1945 * Returns an ordered list of base directories in which to access
1946 * system-wide application data.
1948 * On UNIX platforms this is determined using the mechanisms described in
1949 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1950 * XDG Base Directory Specification</ulink>
1951 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1953 * On Windows the first elements in the list are the Application Data
1954 * and Documents folders for All Users. (These can be determined only
1955 * on Windows 2000 or later and are not present in the list on other
1956 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1957 * CSIDL_COMMON_DOCUMENTS.
1959 * Then follows the "share" subfolder in the installation folder for
1960 * the package containing the DLL that calls this function, if it can
1963 * Finally the list contains the "share" subfolder in the installation
1964 * folder for GLib, and in the installation folder for the package the
1965 * application's .exe file belongs to.
1967 * The installation folders above are determined by looking up the
1968 * folder where the module (DLL or EXE) in question is located. If the
1969 * folder's name is "bin", its parent is used, otherwise the folder
1972 * Note that on Windows the returned list can vary depending on where
1973 * this function is called.
1975 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1976 * not be modified or freed.
1979 const gchar * const *
1980 g_get_system_data_dirs (void)
1982 gchar **data_dir_vector;
1984 G_LOCK (g_utils_global);
1986 if (!g_system_data_dirs)
1989 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
1991 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
1993 if (!data_dirs || !data_dirs[0])
1994 data_dirs = "/usr/local/share/:/usr/share/";
1996 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
1999 g_system_data_dirs = data_dir_vector;
2002 data_dir_vector = g_system_data_dirs;
2004 G_UNLOCK (g_utils_global);
2006 return (const gchar * const *) data_dir_vector;
2010 * g_get_system_config_dirs:
2012 * Returns an ordered list of base directories in which to access
2013 * system-wide configuration information.
2015 * On UNIX platforms this is determined using the mechanisms described in
2016 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2017 * XDG Base Directory Specification</ulink>.
2018 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2020 * On Windows is the directory that contains application data for all users.
2021 * A typical path is C:\Documents and Settings\All Users\Application Data.
2022 * This folder is used for application data that is not user specific.
2023 * For example, an application can store a spell-check dictionary, a database
2024 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2025 * This information will not roam and is available to anyone using the computer.
2027 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2028 * not be modified or freed.
2031 const gchar * const *
2032 g_get_system_config_dirs (void)
2034 gchar *conf_dirs, **conf_dir_vector;
2036 G_LOCK (g_utils_global);
2038 if (!g_system_config_dirs)
2041 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2044 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2049 /* Return empty list */
2050 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2053 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2055 if (!conf_dirs || !conf_dirs[0])
2056 conf_dirs = "/etc/xdg";
2058 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2061 g_system_config_dirs = conf_dir_vector;
2064 conf_dir_vector = g_system_config_dirs;
2065 G_UNLOCK (g_utils_global);
2067 return (const gchar * const *) conf_dir_vector;
2071 * g_nullify_pointer:
2072 * @nullify_location: the memory address of the pointer.
2074 * Set the pointer at the specified location to %NULL.
2077 g_nullify_pointer (gpointer *nullify_location)
2079 g_return_if_fail (nullify_location != NULL);
2081 *nullify_location = NULL;
2084 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2085 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2086 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2087 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2088 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2089 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2091 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2092 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2093 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2094 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2095 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2096 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2100 * @size: a size in bytes
2102 * Formats a size (for example the size of a file) into a human readable
2103 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2104 * and are displayed rounded to the nearest tenth. E.g. the file size
2105 * 3292528 bytes will be converted into the string "3.2 MB".
2107 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2109 * This string should be freed with g_free() when not needed any longer.
2111 * See g_format_size_full() for more options about how the size might be
2114 * Returns: a newly-allocated formatted string containing a human readable
2120 g_format_size (guint64 size)
2122 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2127 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2128 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2129 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2130 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2131 * suffixes. IEC units should only be used for reporting things with
2132 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2133 * Network and storage sizes should be reported in the normal SI units.
2135 * Flags to modify the format of the string returned by g_format_size_full().
2139 * g_format_size_full:
2140 * @size: a size in bytes
2141 * @flags: #GFormatSizeFlags to modify the output
2145 * This function is similar to g_format_size() but allows for flags
2146 * that modify the output. See #GFormatSizeFlags.
2148 * Returns: a newly-allocated formatted string containing a human
2149 * readable file size
2154 g_format_size_full (guint64 size,
2155 GFormatSizeFlags flags)
2159 string = g_string_new (NULL);
2161 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2163 if (size < KIBIBYTE_FACTOR)
2165 g_string_printf (string,
2166 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2168 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2171 else if (size < MEBIBYTE_FACTOR)
2172 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2173 else if (size < GIBIBYTE_FACTOR)
2174 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2176 else if (size < TEBIBYTE_FACTOR)
2177 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2179 else if (size < PEBIBYTE_FACTOR)
2180 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2182 else if (size < EXBIBYTE_FACTOR)
2183 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2186 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2190 if (size < KILOBYTE_FACTOR)
2192 g_string_printf (string,
2193 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2195 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2198 else if (size < MEGABYTE_FACTOR)
2199 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2201 else if (size < GIGABYTE_FACTOR)
2202 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2204 else if (size < TERABYTE_FACTOR)
2205 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2206 else if (size < PETABYTE_FACTOR)
2207 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2209 else if (size < EXABYTE_FACTOR)
2210 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2213 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2216 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2218 /* First problem: we need to use the number of bytes to decide on
2219 * the plural form that is used for display, but the number of
2220 * bytes potentially exceeds the size of a guint (which is what
2221 * ngettext() takes).
2223 * From a pragmatic standpoint, it seems that all known languages
2224 * base plural forms on one or both of the following:
2226 * - the lowest digits of the number
2228 * - if the number if greater than some small value
2230 * Here's how we fake it: Draw an arbitrary line at one thousand.
2231 * If the number is below that, then fine. If it is above it,
2232 * then we take the modulus of the number by one thousand (in
2233 * order to keep the lowest digits) and add one thousand to that
2234 * (in order to ensure that 1001 is not treated the same as 1).
2236 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2238 /* Second problem: we need to translate the string "%u byte" and
2239 * "%u bytes" for pluralisation, but the correct number format to
2240 * use for a gsize is different depending on which architecture
2243 * Solution: format the number separately and use "%s bytes" on
2246 const gchar *translated_format;
2247 gchar *formatted_number;
2249 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2250 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2251 /* XXX: Windows doesn't support the "'" format modifier, so we
2252 * must not use it there. Instead, just display the number
2253 * without separation. Bug #655336 is open until a solution is
2257 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2259 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2262 g_string_append (string, " (");
2263 g_string_append_printf (string, translated_format, formatted_number);
2264 g_free (formatted_number);
2265 g_string_append (string, ")");
2268 return g_string_free (string, FALSE);
2272 * g_format_size_for_display:
2273 * @size: a size in bytes
2275 * Formats a size (for example the size of a file) into a human
2276 * readable string. Sizes are rounded to the nearest size prefix
2277 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2278 * E.g. the file size 3292528 bytes will be converted into the
2281 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2283 * This string should be freed with g_free() when not needed any longer.
2285 * Returns: a newly-allocated formatted string containing a human
2286 * readable file size
2290 * Deprecated:2.30: This function is broken due to its use of SI
2291 * suffixes to denote IEC units. Use g_format_size() instead.
2294 g_format_size_for_display (goffset size)
2296 if (size < (goffset) KIBIBYTE_FACTOR)
2297 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2300 gdouble displayed_size;
2302 if (size < (goffset) MEBIBYTE_FACTOR)
2304 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2305 return g_strdup_printf (_("%.1f KB"), displayed_size);
2307 else if (size < (goffset) GIBIBYTE_FACTOR)
2309 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2310 return g_strdup_printf (_("%.1f MB"), displayed_size);
2312 else if (size < (goffset) TEBIBYTE_FACTOR)
2314 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2315 return g_strdup_printf (_("%.1f GB"), displayed_size);
2317 else if (size < (goffset) PEBIBYTE_FACTOR)
2319 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2320 return g_strdup_printf (_("%.1f TB"), displayed_size);
2322 else if (size < (goffset) EXBIBYTE_FACTOR)
2324 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2325 return g_strdup_printf (_("%.1f PB"), displayed_size);
2329 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2330 return g_strdup_printf (_("%.1f EB"), displayed_size);
2335 #if defined (G_OS_WIN32) && !defined (_WIN64)
2337 /* Binary compatibility versions. Not for newly compiled code. */
2339 #undef g_find_program_in_path
2342 g_find_program_in_path (const gchar *program)
2344 gchar *utf8_program = g_locale_to_utf8 (program, -1, NULL, NULL, NULL);
2345 gchar *utf8_retval = g_find_program_in_path_utf8 (utf8_program);
2348 g_free (utf8_program);
2349 if (utf8_retval == NULL)
2351 retval = g_locale_from_utf8 (utf8_retval, -1, NULL, NULL, NULL);
2352 g_free (utf8_retval);
2357 #undef g_get_user_name
2360 g_get_user_name (void)
2362 g_get_any_init_locked ();
2363 return g_user_name_cp;
2366 #undef g_get_real_name
2369 g_get_real_name (void)
2371 g_get_any_init_locked ();
2372 return g_real_name_cp;
2375 #undef g_get_home_dir
2378 g_get_home_dir (void)
2380 g_get_any_init_locked ();
2381 return g_home_dir_cp;
2384 #undef g_get_tmp_dir
2387 g_get_tmp_dir (void)
2389 g_get_any_init_locked ();
2390 return g_tmp_dir_cp;