GObject: substantially rework g_object_new()
[glib.git] / glib / gutils.c
blob2d049b1ae9b524c961590b9a556dbe00e5a05d2b
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/.
27 /*
28 * MT safe for the unix part, FIXME: make the win32 part MT safe as well.
31 #include "config.h"
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <stdarg.h>
37 #include <stdlib.h>
38 #include <stdio.h>
39 #include <locale.h>
40 #include <string.h>
41 #include <ctype.h> /* For tolower() */
42 #include <errno.h>
43 #include <sys/types.h>
44 #include <sys/stat.h>
45 #ifdef HAVE_PWD_H
46 #include <pwd.h>
47 #endif
48 #include <sys/types.h>
49 #ifdef HAVE_SYS_PARAM_H
50 #include <sys/param.h>
51 #endif
52 #ifdef HAVE_CRT_EXTERNS_H
53 #include <crt_externs.h> /* for _NSGetEnviron */
54 #endif
56 /* implement gutils's inline functions
58 #define G_IMPLEMENT_INLINES 1
59 #define __G_UTILS_C__
60 #include "gutils.h"
62 #include "glib-init.h"
63 #include "glib-private.h"
64 #include "genviron.h"
65 #include "gfileutils.h"
66 #include "ggettext.h"
67 #include "ghash.h"
68 #include "gthread.h"
69 #include "gtestutils.h"
70 #include "gunicode.h"
71 #include "gstrfuncs.h"
72 #include "garray.h"
73 #include "glibintl.h"
75 #ifdef G_PLATFORM_WIN32
76 #include "gconvert.h"
77 #include "gwin32.h"
78 #endif
81 /**
82 * SECTION:misc_utils
83 * @title: Miscellaneous Utility Functions
84 * @short_description: a selection of portable utility functions
86 * These are portable utility functions.
89 #ifdef G_PLATFORM_WIN32
90 # include <windows.h>
91 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
92 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
93 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
94 # endif
95 # include <lmcons.h> /* For UNLEN */
96 #endif /* G_PLATFORM_WIN32 */
98 #ifdef G_OS_WIN32
99 # include <direct.h>
100 # include <shlobj.h>
101 /* older SDK (e.g. msvc 5.0) does not have these*/
102 # ifndef CSIDL_MYMUSIC
103 # define CSIDL_MYMUSIC 13
104 # endif
105 # ifndef CSIDL_MYVIDEO
106 # define CSIDL_MYVIDEO 14
107 # endif
108 # ifndef CSIDL_INTERNET_CACHE
109 # define CSIDL_INTERNET_CACHE 32
110 # endif
111 # ifndef CSIDL_COMMON_APPDATA
112 # define CSIDL_COMMON_APPDATA 35
113 # endif
114 # ifndef CSIDL_MYPICTURES
115 # define CSIDL_MYPICTURES 0x27
116 # endif
117 # ifndef CSIDL_COMMON_DOCUMENTS
118 # define CSIDL_COMMON_DOCUMENTS 46
119 # endif
120 # ifndef CSIDL_PROFILE
121 # define CSIDL_PROFILE 40
122 # endif
123 # include <process.h>
124 #endif
126 #ifdef HAVE_CARBON
127 #include <CoreServices/CoreServices.h>
128 #endif
130 #ifdef HAVE_CODESET
131 #include <langinfo.h>
132 #endif
134 #ifdef G_PLATFORM_WIN32
136 gchar *
137 _glib_get_dll_directory (void)
139 gchar *retval;
140 gchar *p;
141 wchar_t wc_fn[MAX_PATH];
143 #ifdef DLL_EXPORT
144 if (glib_dll == NULL)
145 return NULL;
146 #endif
148 /* This code is different from that in
149 * g_win32_get_package_installation_directory_of_module() in that
150 * here we return the actual folder where the GLib DLL is. We don't
151 * do the check for it being in a "bin" or "lib" subfolder and then
152 * returning the parent of that.
154 * In a statically built GLib, glib_dll will be NULL and we will
155 * thus look up the application's .exe file's location.
157 if (!GetModuleFileNameW (glib_dll, wc_fn, MAX_PATH))
158 return NULL;
160 retval = g_utf16_to_utf8 (wc_fn, -1, NULL, NULL, NULL);
162 p = strrchr (retval, G_DIR_SEPARATOR);
163 if (p == NULL)
165 /* Wtf? */
166 return NULL;
168 *p = '\0';
170 return retval;
173 #endif
175 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
177 * g_memmove:
178 * @dest: the destination address to copy the bytes to.
179 * @src: the source address to copy the bytes from.
180 * @len: the number of bytes to copy.
182 * Copies a block of memory @len bytes long, from @src to @dest.
183 * The source and destination areas may overlap.
185 * In order to use this function, you must include
186 * <filename>string.h</filename> yourself, because this macro will
187 * typically simply resolve to memmove() and GLib does not include
188 * <filename>string.h</filename> for you.
190 void
191 g_memmove (gpointer dest,
192 gconstpointer src,
193 gulong len)
195 gchar* destptr = dest;
196 const gchar* srcptr = src;
197 if (src + len < dest || dest + len < src)
199 bcopy (src, dest, len);
200 return;
202 else if (dest <= src)
204 while (len--)
205 *(destptr++) = *(srcptr++);
207 else
209 destptr += len;
210 srcptr += len;
211 while (len--)
212 *(--destptr) = *(--srcptr);
215 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
217 #ifdef G_OS_WIN32
218 #undef g_atexit
219 #endif
222 * g_atexit:
223 * @func: (scope async): the function to call on normal program termination.
225 * Specifies a function to be called at normal program termination.
227 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
228 * macro that maps to a call to the atexit() function in the C
229 * library. This means that in case the code that calls g_atexit(),
230 * i.e. atexit(), is in a DLL, the function will be called when the
231 * DLL is detached from the program. This typically makes more sense
232 * than that the function is called when the GLib DLL is detached,
233 * which happened earlier when g_atexit() was a function in the GLib
234 * DLL.
236 * The behaviour of atexit() in the context of dynamically loaded
237 * modules is not formally specified and varies wildly.
239 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
240 * loaded module which is unloaded before the program terminates might
241 * well cause a crash at program exit.
243 * Some POSIX systems implement atexit() like Windows, and have each
244 * dynamically loaded module maintain an own atexit chain that is
245 * called when the module is unloaded.
247 * On other POSIX systems, before a dynamically loaded module is
248 * unloaded, the registered atexit functions (if any) residing in that
249 * module are called, regardless where the code that registered them
250 * resided. This is presumably the most robust approach.
252 * As can be seen from the above, for portability it's best to avoid
253 * calling g_atexit() (or atexit()) except in the main executable of a
254 * program.
256 * Deprecated:2.32: It is best to avoid g_atexit().
258 void
259 g_atexit (GVoidFunc func)
261 gint result;
262 const gchar *error = NULL;
264 /* keep this in sync with glib.h */
266 #ifdef G_NATIVE_ATEXIT
267 result = ATEXIT (func);
268 if (result)
269 error = g_strerror (errno);
270 #elif defined (HAVE_ATEXIT)
271 # ifdef NeXT /* @#%@! NeXTStep */
272 result = !atexit ((void (*)(void)) func);
273 if (result)
274 error = g_strerror (errno);
275 # else
276 result = atexit ((void (*)(void)) func);
277 if (result)
278 error = g_strerror (errno);
279 # endif /* NeXT */
280 #elif defined (HAVE_ON_EXIT)
281 result = on_exit ((void (*)(int, void *)) func, NULL);
282 if (result)
283 error = g_strerror (errno);
284 #else
285 result = 0;
286 error = "no implementation";
287 #endif /* G_NATIVE_ATEXIT */
289 if (error)
290 g_error ("Could not register atexit() function: %s", error);
293 /* Based on execvp() from GNU Libc.
294 * Some of this code is cut-and-pasted into gspawn.c
297 static gchar*
298 my_strchrnul (const gchar *str,
299 gchar c)
301 gchar *p = (gchar*)str;
302 while (*p && (*p != c))
303 ++p;
305 return p;
308 #ifdef G_OS_WIN32
310 static gchar *inner_find_program_in_path (const gchar *program);
312 gchar*
313 g_find_program_in_path (const gchar *program)
315 const gchar *last_dot = strrchr (program, '.');
317 if (last_dot == NULL ||
318 strchr (last_dot, '\\') != NULL ||
319 strchr (last_dot, '/') != NULL)
321 const gint program_length = strlen (program);
322 gchar *pathext = g_build_path (";",
323 ".exe;.cmd;.bat;.com",
324 g_getenv ("PATHEXT"),
325 NULL);
326 gchar *p;
327 gchar *decorated_program;
328 gchar *retval;
330 p = pathext;
333 gchar *q = my_strchrnul (p, ';');
335 decorated_program = g_malloc (program_length + (q-p) + 1);
336 memcpy (decorated_program, program, program_length);
337 memcpy (decorated_program+program_length, p, q-p);
338 decorated_program [program_length + (q-p)] = '\0';
340 retval = inner_find_program_in_path (decorated_program);
341 g_free (decorated_program);
343 if (retval != NULL)
345 g_free (pathext);
346 return retval;
348 p = q;
349 } while (*p++ != '\0');
350 g_free (pathext);
351 return NULL;
353 else
354 return inner_find_program_in_path (program);
357 #endif
360 * g_find_program_in_path:
361 * @program: a program name in the GLib file name encoding
363 * Locates the first executable named @program in the user's path, in the
364 * same way that execvp() would locate it. Returns an allocated string
365 * with the absolute path name, or %NULL if the program is not found in
366 * the path. If @program is already an absolute path, returns a copy of
367 * @program if @program exists and is executable, and %NULL otherwise.
369 * On Windows, if @program does not have a file type suffix, tries
370 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
371 * the <envar>PATHEXT</envar> environment variable.
373 * On Windows, it looks for the file in the same way as CreateProcess()
374 * would. This means first in the directory where the executing
375 * program was loaded from, then in the current directory, then in the
376 * Windows 32-bit system directory, then in the Windows directory, and
377 * finally in the directories in the <envar>PATH</envar> environment
378 * variable. If the program is found, the return value contains the
379 * full name including the type suffix.
381 * Return value: a newly-allocated string with the absolute path, or %NULL
383 #ifdef G_OS_WIN32
384 static gchar *
385 inner_find_program_in_path (const gchar *program)
386 #else
387 gchar*
388 g_find_program_in_path (const gchar *program)
389 #endif
391 const gchar *path, *p;
392 gchar *name, *freeme;
393 #ifdef G_OS_WIN32
394 const gchar *path_copy;
395 gchar *filename = NULL, *appdir = NULL;
396 gchar *sysdir = NULL, *windir = NULL;
397 int n;
398 wchar_t wfilename[MAXPATHLEN], wsysdir[MAXPATHLEN],
399 wwindir[MAXPATHLEN];
400 #endif
401 gsize len;
402 gsize pathlen;
404 g_return_val_if_fail (program != NULL, NULL);
406 /* If it is an absolute path, or a relative path including subdirectories,
407 * don't look in PATH.
409 if (g_path_is_absolute (program)
410 || strchr (program, G_DIR_SEPARATOR) != NULL
411 #ifdef G_OS_WIN32
412 || strchr (program, '/') != NULL
413 #endif
416 if (g_file_test (program, G_FILE_TEST_IS_EXECUTABLE) &&
417 !g_file_test (program, G_FILE_TEST_IS_DIR))
418 return g_strdup (program);
419 else
420 return NULL;
423 path = g_getenv ("PATH");
424 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
425 if (path == NULL)
427 /* There is no `PATH' in the environment. The default
428 * search path in GNU libc is the current directory followed by
429 * the path `confstr' returns for `_CS_PATH'.
432 /* In GLib we put . last, for security, and don't use the
433 * unportable confstr(); UNIX98 does not actually specify
434 * what to search if PATH is unset. POSIX may, dunno.
437 path = "/bin:/usr/bin:.";
439 #else
440 n = GetModuleFileNameW (NULL, wfilename, MAXPATHLEN);
441 if (n > 0 && n < MAXPATHLEN)
442 filename = g_utf16_to_utf8 (wfilename, -1, NULL, NULL, NULL);
444 n = GetSystemDirectoryW (wsysdir, MAXPATHLEN);
445 if (n > 0 && n < MAXPATHLEN)
446 sysdir = g_utf16_to_utf8 (wsysdir, -1, NULL, NULL, NULL);
448 n = GetWindowsDirectoryW (wwindir, MAXPATHLEN);
449 if (n > 0 && n < MAXPATHLEN)
450 windir = g_utf16_to_utf8 (wwindir, -1, NULL, NULL, NULL);
452 if (filename)
454 appdir = g_path_get_dirname (filename);
455 g_free (filename);
458 path = g_strdup (path);
460 if (windir)
462 const gchar *tem = path;
463 path = g_strconcat (windir, ";", path, NULL);
464 g_free ((gchar *) tem);
465 g_free (windir);
468 if (sysdir)
470 const gchar *tem = path;
471 path = g_strconcat (sysdir, ";", path, NULL);
472 g_free ((gchar *) tem);
473 g_free (sysdir);
477 const gchar *tem = path;
478 path = g_strconcat (".;", path, NULL);
479 g_free ((gchar *) tem);
482 if (appdir)
484 const gchar *tem = path;
485 path = g_strconcat (appdir, ";", path, NULL);
486 g_free ((gchar *) tem);
487 g_free (appdir);
490 path_copy = path;
491 #endif
493 len = strlen (program) + 1;
494 pathlen = strlen (path);
495 freeme = name = g_malloc (pathlen + len + 1);
497 /* Copy the file name at the top, including '\0' */
498 memcpy (name + pathlen + 1, program, len);
499 name = name + pathlen;
500 /* And add the slash before the filename */
501 *name = G_DIR_SEPARATOR;
503 p = path;
506 char *startp;
508 path = p;
509 p = my_strchrnul (path, G_SEARCHPATH_SEPARATOR);
511 if (p == path)
512 /* Two adjacent colons, or a colon at the beginning or the end
513 * of `PATH' means to search the current directory.
515 startp = name + 1;
516 else
517 startp = memcpy (name - (p - path), path, p - path);
519 if (g_file_test (startp, G_FILE_TEST_IS_EXECUTABLE) &&
520 !g_file_test (startp, G_FILE_TEST_IS_DIR))
522 gchar *ret;
523 ret = g_strdup (startp);
524 g_free (freeme);
525 #ifdef G_OS_WIN32
526 g_free ((gchar *) path_copy);
527 #endif
528 return ret;
531 while (*p++ != '\0');
533 g_free (freeme);
534 #ifdef G_OS_WIN32
535 g_free ((gchar *) path_copy);
536 #endif
538 return NULL;
542 * g_bit_nth_lsf:
543 * @mask: a #gulong containing flags
544 * @nth_bit: the index of the bit to start the search from
546 * Find the position of the first bit set in @mask, searching
547 * from (but not including) @nth_bit upwards. Bits are numbered
548 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
549 * usually). To start searching from the 0th bit, set @nth_bit to -1.
551 * Returns: the index of the first bit set which is higher than @nth_bit
555 * g_bit_nth_msf:
556 * @mask: a #gulong containing flags
557 * @nth_bit: the index of the bit to start the search from
559 * Find the position of the first bit set in @mask, searching
560 * from (but not including) @nth_bit downwards. Bits are numbered
561 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
562 * usually). To start searching from the last bit, set @nth_bit to
563 * -1 or GLIB_SIZEOF_LONG * 8.
565 * Returns: the index of the first bit set which is lower than @nth_bit
569 * g_bit_storage:
570 * @number: a #guint
572 * Gets the number of bits used to hold @number,
573 * e.g. if @number is 4, 3 bits are needed.
575 * Returns: the number of bits used to hold @number
578 G_LOCK_DEFINE_STATIC (g_utils_global);
580 typedef struct
582 gchar *user_name;
583 gchar *real_name;
584 gchar *home_dir;
585 } UserDatabaseEntry;
587 static gchar *g_user_data_dir = NULL;
588 static gchar **g_system_data_dirs = NULL;
589 static gchar *g_user_cache_dir = NULL;
590 static gchar *g_user_config_dir = NULL;
591 static gchar **g_system_config_dirs = NULL;
593 static gchar **g_user_special_dirs = NULL;
595 /* fifteen minutes of fame for everybody */
596 #define G_USER_DIRS_EXPIRE 15 * 60
598 #ifdef G_OS_WIN32
600 static gchar *
601 get_special_folder (int csidl)
603 wchar_t path[MAX_PATH+1];
604 HRESULT hr;
605 LPITEMIDLIST pidl = NULL;
606 BOOL b;
607 gchar *retval = NULL;
609 hr = SHGetSpecialFolderLocation (NULL, csidl, &pidl);
610 if (hr == S_OK)
612 b = SHGetPathFromIDListW (pidl, path);
613 if (b)
614 retval = g_utf16_to_utf8 (path, -1, NULL, NULL, NULL);
615 CoTaskMemFree (pidl);
617 return retval;
620 static char *
621 get_windows_directory_root (void)
623 wchar_t wwindowsdir[MAX_PATH];
625 if (GetWindowsDirectoryW (wwindowsdir, G_N_ELEMENTS (wwindowsdir)))
627 /* Usually X:\Windows, but in terminal server environments
628 * might be an UNC path, AFAIK.
630 char *windowsdir = g_utf16_to_utf8 (wwindowsdir, -1, NULL, NULL, NULL);
631 char *p;
633 if (windowsdir == NULL)
634 return g_strdup ("C:\\");
636 p = (char *) g_path_skip_root (windowsdir);
637 if (G_IS_DIR_SEPARATOR (p[-1]) && p[-2] != ':')
638 p--;
639 *p = '\0';
640 return windowsdir;
642 else
643 return g_strdup ("C:\\");
646 #endif
648 /* HOLDS: g_utils_global_lock */
649 static UserDatabaseEntry *
650 g_get_user_database_entry (void)
652 static UserDatabaseEntry *entry;
654 if (g_once_init_enter (&entry))
656 static UserDatabaseEntry e;
658 #ifdef HAVE_PWD_H
660 struct passwd *pw = NULL;
661 gpointer buffer = NULL;
662 gint error;
663 gchar *logname;
665 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
666 struct passwd pwd;
667 # ifdef _SC_GETPW_R_SIZE_MAX
668 /* This reurns the maximum length */
669 glong bufsize = sysconf (_SC_GETPW_R_SIZE_MAX);
671 if (bufsize < 0)
672 bufsize = 64;
673 # else /* _SC_GETPW_R_SIZE_MAX */
674 glong bufsize = 64;
675 # endif /* _SC_GETPW_R_SIZE_MAX */
677 logname = (gchar *) g_getenv ("LOGNAME");
681 g_free (buffer);
682 /* we allocate 6 extra bytes to work around a bug in
683 * Mac OS < 10.3. See #156446
685 buffer = g_malloc (bufsize + 6);
686 errno = 0;
688 # ifdef HAVE_POSIX_GETPWUID_R
689 if (logname) {
690 error = getpwnam_r (logname, &pwd, buffer, bufsize, &pw);
691 if (!pw || (pw->pw_uid != getuid ())) {
692 /* LOGNAME is lying, fall back to looking up the uid */
693 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
695 } else {
696 error = getpwuid_r (getuid (), &pwd, buffer, bufsize, &pw);
698 error = error < 0 ? errno : error;
699 # else /* HAVE_NONPOSIX_GETPWUID_R */
700 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
701 # if defined(_AIX) || defined(__hpux)
702 error = getpwuid_r (getuid (), &pwd, buffer, bufsize);
703 pw = error == 0 ? &pwd : NULL;
704 # else /* !_AIX */
705 if (logname) {
706 pw = getpwnam_r (logname, &pwd, buffer, bufsize);
707 if (!pw || (pw->pw_uid != getuid ())) {
708 /* LOGNAME is lying, fall back to looking up the uid */
709 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
711 } else {
712 pw = getpwuid_r (getuid (), &pwd, buffer, bufsize);
714 error = pw ? 0 : errno;
715 # endif /* !_AIX */
716 # endif /* HAVE_NONPOSIX_GETPWUID_R */
718 if (!pw)
720 /* we bail out prematurely if the user id can't be found
721 * (should be pretty rare case actually), or if the buffer
722 * should be sufficiently big and lookups are still not
723 * successful.
725 if (error == 0 || error == ENOENT)
727 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
728 (gulong) getuid ());
729 break;
731 if (bufsize > 32 * 1024)
733 g_warning ("getpwuid_r(): failed due to: %s.",
734 g_strerror (error));
735 break;
738 bufsize *= 2;
741 while (!pw);
742 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
744 if (!pw)
746 pw = getpwuid (getuid ());
748 if (pw)
750 e.user_name = g_strdup (pw->pw_name);
752 #ifndef __BIONIC__
753 if (pw->pw_gecos && *pw->pw_gecos != '\0')
755 gchar **gecos_fields;
756 gchar **name_parts;
758 /* split the gecos field and substitute '&' */
759 gecos_fields = g_strsplit (pw->pw_gecos, ",", 0);
760 name_parts = g_strsplit (gecos_fields[0], "&", 0);
761 pw->pw_name[0] = g_ascii_toupper (pw->pw_name[0]);
762 e.real_name = g_strjoinv (pw->pw_name, name_parts);
763 g_strfreev (gecos_fields);
764 g_strfreev (name_parts);
766 #endif
768 if (!e.home_dir)
769 e.home_dir = g_strdup (pw->pw_dir);
771 g_free (buffer);
774 #else /* !HAVE_PWD_H */
776 #ifdef G_OS_WIN32
778 guint len = UNLEN+1;
779 wchar_t buffer[UNLEN+1];
781 if (GetUserNameW (buffer, (LPDWORD) &len))
783 e.user_name = g_utf16_to_utf8 (buffer, -1, NULL, NULL, NULL);
784 e.real_name = g_strdup (e.user_name);
787 #endif /* G_OS_WIN32 */
789 #endif /* !HAVE_PWD_H */
791 #ifdef __EMX__
792 /* change '\\' in %HOME% to '/' */
793 g_strdelimit (e.home_dir, "\\",'/');
794 #endif
795 if (!e.user_name)
796 e.user_name = g_strdup ("somebody");
797 if (!e.real_name)
798 e.real_name = g_strdup ("Unknown");
800 g_once_init_leave (&entry, &e);
803 return entry;
807 * g_get_user_name:
809 * Gets the user name of the current user. The encoding of the returned
810 * string is system-defined. On UNIX, it might be the preferred file name
811 * encoding, or something else, and there is no guarantee that it is even
812 * consistent on a machine. On Windows, it is always UTF-8.
814 * Returns: the user name of the current user.
816 const gchar *
817 g_get_user_name (void)
819 UserDatabaseEntry *entry;
821 entry = g_get_user_database_entry ();
823 return entry->user_name;
827 * g_get_real_name:
829 * Gets the real name of the user. This usually comes from the user's entry
830 * in the <filename>passwd</filename> file. The encoding of the returned
831 * string is system-defined. (On Windows, it is, however, always UTF-8.)
832 * If the real user name cannot be determined, the string "Unknown" is
833 * returned.
835 * Returns: the user's real name.
837 const gchar *
838 g_get_real_name (void)
840 UserDatabaseEntry *entry;
842 entry = g_get_user_database_entry ();
844 return entry->real_name;
848 * g_get_home_dir:
850 * Gets the current user's home directory.
852 * As with most UNIX tools, this function will return the value of the
853 * <envar>HOME</envar> environment variable if it is set to an existing
854 * absolute path name, falling back to the <filename>passwd</filename>
855 * file in the case that it is unset.
857 * If the path given in <envar>HOME</envar> is non-absolute, does not
858 * exist, or is not a directory, the result is undefined.
860 * <note><para>
861 * Before version 2.36 this function would ignore the
862 * <envar>HOME</envar> environment variable, taking the value from the
863 * <filename>passwd</filename> database instead. This was changed to
864 * increase the compatibility of GLib with other programs (and the XDG
865 * basedir specification) and to increase testability of programs
866 * based on GLib (by making it easier to run them from test
867 * frameworks).
868 * </para><para>
869 * If your program has a strong requirement for either the new or the
870 * old behaviour (and if you don't wish to increase your GLib
871 * dependency to ensure that the new behaviour is in effect) then you
872 * should either directly check the <envar>HOME</envar> environment
873 * variable yourself or unset it before calling any functions in GLib.
874 * </para></note>
876 * Returns: the current user's home directory
878 const gchar *
879 g_get_home_dir (void)
881 static gchar *home_dir;
883 if (g_once_init_enter (&home_dir))
885 gchar *tmp;
887 /* We first check HOME and use it if it is set */
888 tmp = g_strdup (g_getenv ("HOME"));
890 #ifdef G_OS_WIN32
891 /* Only believe HOME if it is an absolute path and exists.
893 * We only do this check on Windows for a couple of reasons.
894 * Historically, we only did it there because we used to ignore $HOME
895 * on UNIX. There are concerns about enabling it now on UNIX because
896 * of things like autofs. In short, if the user has a bogus value in
897 * $HOME then they get what they pay for...
899 if (tmp)
901 if (!(g_path_is_absolute (tmp) &&
902 g_file_test (tmp, G_FILE_TEST_IS_DIR)))
904 g_free (tmp);
905 tmp = NULL;
909 /* In case HOME is Unix-style (it happens), convert it to
910 * Windows style.
912 if (tmp)
914 gchar *p;
915 while ((p = strchr (tmp, '/')) != NULL)
916 *p = '\\';
919 if (!tmp)
921 /* USERPROFILE is probably the closest equivalent to $HOME? */
922 if (g_getenv ("USERPROFILE") != NULL)
923 tmp = g_strdup (g_getenv ("USERPROFILE"));
926 if (!tmp)
927 tmp = get_special_folder (CSIDL_PROFILE);
929 if (!tmp)
930 tmp = get_windows_directory_root ();
931 #endif /* G_OS_WIN32 */
933 if (!tmp)
935 /* If we didn't get it from any of those methods, we will have
936 * to read the user database entry.
938 UserDatabaseEntry *entry;
940 entry = g_get_user_database_entry ();
942 /* Strictly speaking, we should copy this, but we know that
943 * neither will ever be freed, so don't bother...
945 tmp = entry->home_dir;
948 g_once_init_leave (&home_dir, tmp);
951 return home_dir;
955 * g_get_tmp_dir:
957 * Gets the directory to use for temporary files. This is found from
958 * inspecting the environment variables <envar>TMPDIR</envar>,
959 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
960 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
961 * The encoding of the returned string is system-defined. On Windows,
962 * it is always UTF-8. The return value is never %NULL or the empty string.
964 * Returns: the directory to use for temporary files.
966 const gchar *
967 g_get_tmp_dir (void)
969 static gchar *tmp_dir;
971 if (g_once_init_enter (&tmp_dir))
973 gchar *tmp;
975 tmp = g_strdup (g_getenv ("TMPDIR"));
977 if (tmp == NULL || *tmp == '\0')
979 g_free (tmp);
980 tmp = g_strdup (g_getenv ("TMP"));
983 if (tmp == NULL || *tmp == '\0')
985 g_free (tmp);
986 tmp = g_strdup (g_getenv ("TEMP"));
989 #ifdef G_OS_WIN32
990 if (tmp == NULL || *tmp == '\0')
992 g_free (tmp);
993 tmp = get_windows_directory_root ();
995 #else
997 #ifdef P_tmpdir
998 if (tmp == NULL || *tmp == '\0')
1000 gsize k;
1001 g_free (tmp);
1002 tmp = g_strdup (P_tmpdir);
1003 k = strlen (tmp);
1004 if (k > 1 && G_IS_DIR_SEPARATOR (tmp[k - 1]))
1005 tmp[k - 1] = '\0';
1007 #endif
1009 if (tmp == NULL || *tmp == '\0')
1011 g_free (tmp);
1012 tmp = g_strdup ("/tmp");
1014 #endif /* !G_OS_WIN32 */
1016 g_once_init_leave (&tmp_dir, tmp);
1019 return tmp_dir;
1023 * g_get_host_name:
1025 * Return a name for the machine.
1027 * The returned name is not necessarily a fully-qualified domain name,
1028 * or even present in DNS or some other name service at all. It need
1029 * not even be unique on your local network or site, but usually it
1030 * is. Callers should not rely on the return value having any specific
1031 * properties like uniqueness for security purposes. Even if the name
1032 * of the machine is changed while an application is running, the
1033 * return value from this function does not change. The returned
1034 * string is owned by GLib and should not be modified or freed. If no
1035 * name can be determined, a default fixed string "localhost" is
1036 * returned.
1038 * Returns: the host name of the machine.
1040 * Since: 2.8
1042 const gchar *
1043 g_get_host_name (void)
1045 static gchar *hostname;
1047 if (g_once_init_enter (&hostname))
1049 gboolean failed;
1050 gchar tmp[100];
1052 #ifndef G_OS_WIN32
1053 failed = (gethostname (tmp, sizeof (tmp)) == -1);
1054 #else
1055 DWORD size = sizeof (tmp);
1056 failed = (!GetComputerName (tmp, &size));
1057 #endif
1059 g_once_init_leave (&hostname, g_strdup (failed ? "localhost" : tmp));
1062 return hostname;
1065 G_LOCK_DEFINE_STATIC (g_prgname);
1066 static gchar *g_prgname = NULL;
1069 * g_get_prgname:
1071 * Gets the name of the program. This name should <emphasis>not</emphasis>
1072 * be localized, contrast with g_get_application_name().
1073 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1074 * which is called by gtk_init(). The program name is found by taking
1075 * the last component of <literal>argv[0]</literal>.)
1077 * Returns: the name of the program. The returned string belongs
1078 * to GLib and must not be modified or freed.
1080 const gchar*
1081 g_get_prgname (void)
1083 gchar* retval;
1085 G_LOCK (g_prgname);
1086 #ifdef G_OS_WIN32
1087 if (g_prgname == NULL)
1089 static gboolean beenhere = FALSE;
1091 if (!beenhere)
1093 gchar *utf8_buf = NULL;
1094 wchar_t buf[MAX_PATH+1];
1096 beenhere = TRUE;
1097 if (GetModuleFileNameW (GetModuleHandle (NULL),
1098 buf, G_N_ELEMENTS (buf)) > 0)
1099 utf8_buf = g_utf16_to_utf8 (buf, -1, NULL, NULL, NULL);
1101 if (utf8_buf)
1103 g_prgname = g_path_get_basename (utf8_buf);
1104 g_free (utf8_buf);
1108 #endif
1109 retval = g_prgname;
1110 G_UNLOCK (g_prgname);
1112 return retval;
1116 * g_set_prgname:
1117 * @prgname: the name of the program.
1119 * Sets the name of the program. This name should <emphasis>not</emphasis>
1120 * be localized, contrast with g_set_application_name(). Note that for
1121 * thread-safety reasons this function can only be called once.
1123 void
1124 g_set_prgname (const gchar *prgname)
1126 G_LOCK (g_prgname);
1127 g_free (g_prgname);
1128 g_prgname = g_strdup (prgname);
1129 G_UNLOCK (g_prgname);
1132 G_LOCK_DEFINE_STATIC (g_application_name);
1133 static gchar *g_application_name = NULL;
1136 * g_get_application_name:
1138 * Gets a human-readable name for the application, as set by
1139 * g_set_application_name(). This name should be localized if
1140 * possible, and is intended for display to the user. Contrast with
1141 * g_get_prgname(), which gets a non-localized name. If
1142 * g_set_application_name() has not been called, returns the result of
1143 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1144 * been called).
1146 * Return value: human-readable application name. may return %NULL
1148 * Since: 2.2
1150 const gchar *
1151 g_get_application_name (void)
1153 gchar* retval;
1155 G_LOCK (g_application_name);
1156 retval = g_application_name;
1157 G_UNLOCK (g_application_name);
1159 if (retval == NULL)
1160 return g_get_prgname ();
1162 return retval;
1166 * g_set_application_name:
1167 * @application_name: localized name of the application
1169 * Sets a human-readable name for the application. This name should be
1170 * localized if possible, and is intended for display to the user.
1171 * Contrast with g_set_prgname(), which sets a non-localized name.
1172 * g_set_prgname() will be called automatically by gtk_init(),
1173 * but g_set_application_name() will not.
1175 * Note that for thread safety reasons, this function can only
1176 * be called once.
1178 * The application name will be used in contexts such as error messages,
1179 * or when displaying an application's name in the task list.
1181 * Since: 2.2
1183 void
1184 g_set_application_name (const gchar *application_name)
1186 gboolean already_set = FALSE;
1188 G_LOCK (g_application_name);
1189 if (g_application_name)
1190 already_set = TRUE;
1191 else
1192 g_application_name = g_strdup (application_name);
1193 G_UNLOCK (g_application_name);
1195 if (already_set)
1196 g_warning ("g_set_application_name() called multiple times");
1200 * g_get_user_data_dir:
1202 * Returns a base directory in which to access application data such
1203 * as icons that is customized for a particular user.
1205 * On UNIX platforms this is determined using the mechanisms described in
1206 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1207 * XDG Base Directory Specification</ulink>.
1208 * In this case the directory retrieved will be XDG_DATA_HOME.
1210 * On Windows this is the folder to use for local (as opposed to
1211 * roaming) application data. See documentation for
1212 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1213 * what g_get_user_config_dir() returns.
1215 * Return value: a string owned by GLib that must not be modified
1216 * or freed.
1217 * Since: 2.6
1219 const gchar *
1220 g_get_user_data_dir (void)
1222 gchar *data_dir;
1224 G_LOCK (g_utils_global);
1226 if (!g_user_data_dir)
1228 #ifdef G_OS_WIN32
1229 data_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1230 #else
1231 data_dir = (gchar *) g_getenv ("XDG_DATA_HOME");
1233 if (data_dir && data_dir[0])
1234 data_dir = g_strdup (data_dir);
1235 #endif
1236 if (!data_dir || !data_dir[0])
1238 const gchar *home_dir = g_get_home_dir ();
1240 if (home_dir)
1241 data_dir = g_build_filename (home_dir, ".local", "share", NULL);
1242 else
1243 data_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".local", "share", NULL);
1246 g_user_data_dir = data_dir;
1248 else
1249 data_dir = g_user_data_dir;
1251 G_UNLOCK (g_utils_global);
1253 return data_dir;
1256 static void
1257 g_init_user_config_dir (void)
1259 gchar *config_dir;
1261 if (!g_user_config_dir)
1263 #ifdef G_OS_WIN32
1264 config_dir = get_special_folder (CSIDL_LOCAL_APPDATA);
1265 #else
1266 config_dir = (gchar *) g_getenv ("XDG_CONFIG_HOME");
1268 if (config_dir && config_dir[0])
1269 config_dir = g_strdup (config_dir);
1270 #endif
1271 if (!config_dir || !config_dir[0])
1273 const gchar *home_dir = g_get_home_dir ();
1275 if (home_dir)
1276 config_dir = g_build_filename (home_dir, ".config", NULL);
1277 else
1278 config_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".config", NULL);
1281 g_user_config_dir = config_dir;
1286 * g_get_user_config_dir:
1288 * Returns a base directory in which to store user-specific application
1289 * configuration information such as user preferences and settings.
1291 * On UNIX platforms this is determined using the mechanisms described in
1292 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1293 * XDG Base Directory Specification</ulink>.
1294 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1296 * On Windows this is the folder to use for local (as opposed to
1297 * roaming) application data. See documentation for
1298 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1299 * what g_get_user_data_dir() returns.
1301 * Return value: a string owned by GLib that must not be modified
1302 * or freed.
1303 * Since: 2.6
1305 const gchar *
1306 g_get_user_config_dir (void)
1308 G_LOCK (g_utils_global);
1310 g_init_user_config_dir ();
1312 G_UNLOCK (g_utils_global);
1314 return g_user_config_dir;
1318 * g_get_user_cache_dir:
1320 * Returns a base directory in which to store non-essential, cached
1321 * data specific to particular user.
1323 * On UNIX platforms this is determined using the mechanisms described in
1324 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1325 * XDG Base Directory Specification</ulink>.
1326 * In this case the directory retrieved will be XDG_CACHE_HOME.
1328 * On Windows is the directory that serves as a common repository for
1329 * temporary Internet files. A typical path is
1330 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1331 * See documentation for CSIDL_INTERNET_CACHE.
1333 * Return value: a string owned by GLib that must not be modified
1334 * or freed.
1335 * Since: 2.6
1337 const gchar *
1338 g_get_user_cache_dir (void)
1340 gchar *cache_dir;
1342 G_LOCK (g_utils_global);
1344 if (!g_user_cache_dir)
1346 #ifdef G_OS_WIN32
1347 cache_dir = get_special_folder (CSIDL_INTERNET_CACHE); /* XXX correct? */
1348 #else
1349 cache_dir = (gchar *) g_getenv ("XDG_CACHE_HOME");
1351 if (cache_dir && cache_dir[0])
1352 cache_dir = g_strdup (cache_dir);
1353 #endif
1354 if (!cache_dir || !cache_dir[0])
1356 const gchar *home_dir = g_get_home_dir ();
1358 if (home_dir)
1359 cache_dir = g_build_filename (home_dir, ".cache", NULL);
1360 else
1361 cache_dir = g_build_filename (g_get_tmp_dir (), g_get_user_name (), ".cache", NULL);
1363 g_user_cache_dir = cache_dir;
1365 else
1366 cache_dir = g_user_cache_dir;
1368 G_UNLOCK (g_utils_global);
1370 return cache_dir;
1374 * g_get_user_runtime_dir:
1376 * Returns a directory that is unique to the current user on the local
1377 * system.
1379 * On UNIX platforms this is determined using the mechanisms described in
1380 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1381 * XDG Base Directory Specification</ulink>. This is the directory
1382 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1383 * In the case that this variable is not set, GLib will issue a warning
1384 * message to stderr and return the value of g_get_user_cache_dir().
1386 * On Windows this is the folder to use for local (as opposed to
1387 * roaming) application data. See documentation for
1388 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1389 * what g_get_user_config_dir() returns.
1391 * Returns: a string owned by GLib that must not be modified or freed.
1393 * Since: 2.28
1395 const gchar *
1396 g_get_user_runtime_dir (void)
1398 #ifndef G_OS_WIN32
1399 static const gchar *runtime_dir;
1400 static gsize initialised;
1402 if (g_once_init_enter (&initialised))
1404 runtime_dir = g_strdup (getenv ("XDG_RUNTIME_DIR"));
1406 g_once_init_leave (&initialised, 1);
1409 if (runtime_dir)
1410 return runtime_dir;
1412 /* Both fallback for UNIX and the default
1413 * in Windows: use the user cache directory.
1415 #endif
1417 return g_get_user_cache_dir ();
1420 #ifdef HAVE_CARBON
1422 static gchar *
1423 find_folder (OSType type)
1425 gchar *filename = NULL;
1426 FSRef found;
1428 if (FSFindFolder (kUserDomain, type, kDontCreateFolder, &found) == noErr)
1430 CFURLRef url = CFURLCreateFromFSRef (kCFAllocatorSystemDefault, &found);
1432 if (url)
1434 CFStringRef path = CFURLCopyFileSystemPath (url, kCFURLPOSIXPathStyle);
1436 if (path)
1438 filename = g_strdup (CFStringGetCStringPtr (path, kCFStringEncodingUTF8));
1440 if (! filename)
1442 filename = g_new0 (gchar, CFStringGetLength (path) * 3 + 1);
1444 CFStringGetCString (path, filename,
1445 CFStringGetLength (path) * 3 + 1,
1446 kCFStringEncodingUTF8);
1449 CFRelease (path);
1452 CFRelease (url);
1456 return filename;
1459 static void
1460 load_user_special_dirs (void)
1462 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = find_folder (kDesktopFolderType);
1463 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = find_folder (kDocumentsFolderType);
1464 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = find_folder (kDesktopFolderType); /* XXX correct ? */
1465 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = find_folder (kMusicDocumentsFolderType);
1466 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = find_folder (kPictureDocumentsFolderType);
1467 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = NULL;
1468 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = NULL;
1469 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = find_folder (kMovieDocumentsFolderType);
1472 #endif /* HAVE_CARBON */
1474 #if defined(G_OS_WIN32)
1475 static void
1476 load_user_special_dirs (void)
1478 typedef HRESULT (WINAPI *t_SHGetKnownFolderPath) (const GUID *rfid,
1479 DWORD dwFlags,
1480 HANDLE hToken,
1481 PWSTR *ppszPath);
1482 t_SHGetKnownFolderPath p_SHGetKnownFolderPath;
1484 static const GUID FOLDERID_Downloads =
1485 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1486 static const GUID FOLDERID_Public =
1487 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1489 wchar_t *wcp;
1491 p_SHGetKnownFolderPath = (t_SHGetKnownFolderPath) GetProcAddress (GetModuleHandle ("shell32.dll"),
1492 "SHGetKnownFolderPath");
1494 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1495 g_user_special_dirs[G_USER_DIRECTORY_DOCUMENTS] = get_special_folder (CSIDL_PERSONAL);
1497 if (p_SHGetKnownFolderPath == NULL)
1499 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1501 else
1503 wcp = NULL;
1504 (*p_SHGetKnownFolderPath) (&FOLDERID_Downloads, 0, NULL, &wcp);
1505 if (wcp)
1507 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1508 if (g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] == NULL)
1509 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1510 CoTaskMemFree (wcp);
1512 else
1513 g_user_special_dirs[G_USER_DIRECTORY_DOWNLOAD] = get_special_folder (CSIDL_DESKTOPDIRECTORY);
1516 g_user_special_dirs[G_USER_DIRECTORY_MUSIC] = get_special_folder (CSIDL_MYMUSIC);
1517 g_user_special_dirs[G_USER_DIRECTORY_PICTURES] = get_special_folder (CSIDL_MYPICTURES);
1519 if (p_SHGetKnownFolderPath == NULL)
1521 /* XXX */
1522 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1524 else
1526 wcp = NULL;
1527 (*p_SHGetKnownFolderPath) (&FOLDERID_Public, 0, NULL, &wcp);
1528 if (wcp)
1530 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = g_utf16_to_utf8 (wcp, -1, NULL, NULL, NULL);
1531 if (g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] == NULL)
1532 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1533 CoTaskMemFree (wcp);
1535 else
1536 g_user_special_dirs[G_USER_DIRECTORY_PUBLIC_SHARE] = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1539 g_user_special_dirs[G_USER_DIRECTORY_TEMPLATES] = get_special_folder (CSIDL_TEMPLATES);
1540 g_user_special_dirs[G_USER_DIRECTORY_VIDEOS] = get_special_folder (CSIDL_MYVIDEO);
1542 #endif /* G_OS_WIN32 */
1544 static void g_init_user_config_dir (void);
1546 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1548 /* adapted from xdg-user-dir-lookup.c
1550 * Copyright (C) 2007 Red Hat Inc.
1552 * Permission is hereby granted, free of charge, to any person
1553 * obtaining a copy of this software and associated documentation files
1554 * (the "Software"), to deal in the Software without restriction,
1555 * including without limitation the rights to use, copy, modify, merge,
1556 * publish, distribute, sublicense, and/or sell copies of the Software,
1557 * and to permit persons to whom the Software is furnished to do so,
1558 * subject to the following conditions:
1560 * The above copyright notice and this permission notice shall be
1561 * included in all copies or substantial portions of the Software.
1563 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1564 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1565 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1566 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1567 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1568 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1569 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1570 * SOFTWARE.
1572 static void
1573 load_user_special_dirs (void)
1575 gchar *config_file;
1576 gchar *data;
1577 gchar **lines;
1578 gint n_lines, i;
1580 g_init_user_config_dir ();
1581 config_file = g_build_filename (g_user_config_dir,
1582 "user-dirs.dirs",
1583 NULL);
1585 if (!g_file_get_contents (config_file, &data, NULL, NULL))
1587 g_free (config_file);
1588 return;
1591 lines = g_strsplit (data, "\n", -1);
1592 n_lines = g_strv_length (lines);
1593 g_free (data);
1595 for (i = 0; i < n_lines; i++)
1597 gchar *buffer = lines[i];
1598 gchar *d, *p;
1599 gint len;
1600 gboolean is_relative = FALSE;
1601 GUserDirectory directory;
1603 /* Remove newline at end */
1604 len = strlen (buffer);
1605 if (len > 0 && buffer[len - 1] == '\n')
1606 buffer[len - 1] = 0;
1608 p = buffer;
1609 while (*p == ' ' || *p == '\t')
1610 p++;
1612 if (strncmp (p, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
1614 directory = G_USER_DIRECTORY_DESKTOP;
1615 p += strlen ("XDG_DESKTOP_DIR");
1617 else if (strncmp (p, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
1619 directory = G_USER_DIRECTORY_DOCUMENTS;
1620 p += strlen ("XDG_DOCUMENTS_DIR");
1622 else if (strncmp (p, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
1624 directory = G_USER_DIRECTORY_DOWNLOAD;
1625 p += strlen ("XDG_DOWNLOAD_DIR");
1627 else if (strncmp (p, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
1629 directory = G_USER_DIRECTORY_MUSIC;
1630 p += strlen ("XDG_MUSIC_DIR");
1632 else if (strncmp (p, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
1634 directory = G_USER_DIRECTORY_PICTURES;
1635 p += strlen ("XDG_PICTURES_DIR");
1637 else if (strncmp (p, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
1639 directory = G_USER_DIRECTORY_PUBLIC_SHARE;
1640 p += strlen ("XDG_PUBLICSHARE_DIR");
1642 else if (strncmp (p, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
1644 directory = G_USER_DIRECTORY_TEMPLATES;
1645 p += strlen ("XDG_TEMPLATES_DIR");
1647 else if (strncmp (p, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
1649 directory = G_USER_DIRECTORY_VIDEOS;
1650 p += strlen ("XDG_VIDEOS_DIR");
1652 else
1653 continue;
1655 while (*p == ' ' || *p == '\t')
1656 p++;
1658 if (*p != '=')
1659 continue;
1660 p++;
1662 while (*p == ' ' || *p == '\t')
1663 p++;
1665 if (*p != '"')
1666 continue;
1667 p++;
1669 if (strncmp (p, "$HOME", 5) == 0)
1671 p += 5;
1672 is_relative = TRUE;
1674 else if (*p != '/')
1675 continue;
1677 d = strrchr (p, '"');
1678 if (!d)
1679 continue;
1680 *d = 0;
1682 d = p;
1684 /* remove trailing slashes */
1685 len = strlen (d);
1686 if (d[len - 1] == '/')
1687 d[len - 1] = 0;
1689 if (is_relative)
1691 g_user_special_dirs[directory] = g_build_filename (g_get_home_dir (), d, NULL);
1693 else
1694 g_user_special_dirs[directory] = g_strdup (d);
1697 g_strfreev (lines);
1698 g_free (config_file);
1701 #endif /* G_OS_UNIX && !HAVE_CARBON */
1705 * g_reload_user_special_dirs_cache:
1707 * Resets the cache used for g_get_user_special_dir(), so
1708 * that the latest on-disk version is used. Call this only
1709 * if you just changed the data on disk yourself.
1711 * Due to threadsafety issues this may cause leaking of strings
1712 * that were previously returned from g_get_user_special_dir()
1713 * that can't be freed. We ensure to only leak the data for
1714 * the directories that actually changed value though.
1716 * Since: 2.22
1718 void
1719 g_reload_user_special_dirs_cache (void)
1721 int i;
1723 G_LOCK (g_utils_global);
1725 if (g_user_special_dirs != NULL)
1727 /* save a copy of the pointer, to check if some memory can be preserved */
1728 char **old_g_user_special_dirs = g_user_special_dirs;
1729 char *old_val;
1731 /* recreate and reload our cache */
1732 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1733 load_user_special_dirs ();
1735 /* only leak changed directories */
1736 for (i = 0; i < G_USER_N_DIRECTORIES; i++)
1738 old_val = old_g_user_special_dirs[i];
1739 if (g_user_special_dirs[i] == NULL)
1741 g_user_special_dirs[i] = old_val;
1743 else if (g_strcmp0 (old_val, g_user_special_dirs[i]) == 0)
1745 /* don't leak */
1746 g_free (g_user_special_dirs[i]);
1747 g_user_special_dirs[i] = old_val;
1749 else
1750 g_free (old_val);
1753 /* free the old array */
1754 g_free (old_g_user_special_dirs);
1757 G_UNLOCK (g_utils_global);
1761 * g_get_user_special_dir:
1762 * @directory: the logical id of special directory
1764 * Returns the full path of a special directory using its logical id.
1766 * On Unix this is done using the XDG special user directories.
1767 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
1768 * falls back to <filename>$HOME/Desktop</filename> when XDG special
1769 * user directories have not been set up.
1771 * Depending on the platform, the user might be able to change the path
1772 * of the special directory without requiring the session to restart; GLib
1773 * will not reflect any change once the special directories are loaded.
1775 * Return value: the path to the specified special directory, or %NULL
1776 * if the logical id was not found. The returned string is owned by
1777 * GLib and should not be modified or freed.
1779 * Since: 2.14
1781 const gchar *
1782 g_get_user_special_dir (GUserDirectory directory)
1784 g_return_val_if_fail (directory >= G_USER_DIRECTORY_DESKTOP &&
1785 directory < G_USER_N_DIRECTORIES, NULL);
1787 G_LOCK (g_utils_global);
1789 if (G_UNLIKELY (g_user_special_dirs == NULL))
1791 g_user_special_dirs = g_new0 (gchar *, G_USER_N_DIRECTORIES);
1793 load_user_special_dirs ();
1795 /* Special-case desktop for historical compatibility */
1796 if (g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] == NULL)
1797 g_user_special_dirs[G_USER_DIRECTORY_DESKTOP] = g_build_filename (g_get_home_dir (), "Desktop", NULL);
1800 G_UNLOCK (g_utils_global);
1802 return g_user_special_dirs[directory];
1805 #ifdef G_OS_WIN32
1807 #undef g_get_system_data_dirs
1809 static HMODULE
1810 get_module_for_address (gconstpointer address)
1812 /* Holds the g_utils_global lock */
1814 static gboolean beenhere = FALSE;
1815 typedef BOOL (WINAPI *t_GetModuleHandleExA) (DWORD, LPCTSTR, HMODULE *);
1816 static t_GetModuleHandleExA p_GetModuleHandleExA = NULL;
1817 HMODULE hmodule = NULL;
1819 if (!address)
1820 return NULL;
1822 if (!beenhere)
1824 p_GetModuleHandleExA =
1825 (t_GetModuleHandleExA) GetProcAddress (GetModuleHandle ("kernel32.dll"),
1826 "GetModuleHandleExA");
1827 beenhere = TRUE;
1830 if (p_GetModuleHandleExA == NULL ||
1831 !(*p_GetModuleHandleExA) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT |
1832 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
1833 address, &hmodule))
1835 MEMORY_BASIC_INFORMATION mbi;
1836 VirtualQuery (address, &mbi, sizeof (mbi));
1837 hmodule = (HMODULE) mbi.AllocationBase;
1840 return hmodule;
1843 static gchar *
1844 get_module_share_dir (gconstpointer address)
1846 HMODULE hmodule;
1847 gchar *filename;
1848 gchar *retval;
1850 hmodule = get_module_for_address (address);
1851 if (hmodule == NULL)
1852 return NULL;
1854 filename = g_win32_get_package_installation_directory_of_module (hmodule);
1855 retval = g_build_filename (filename, "share", NULL);
1856 g_free (filename);
1858 return retval;
1861 const gchar * const *
1862 g_win32_get_system_data_dirs_for_module (void (*address_of_function)(void))
1864 GArray *data_dirs;
1865 HMODULE hmodule;
1866 static GHashTable *per_module_data_dirs = NULL;
1867 gchar **retval;
1868 gchar *p;
1869 gchar *exe_root;
1871 if (address_of_function)
1873 G_LOCK (g_utils_global);
1874 hmodule = get_module_for_address (address_of_function);
1875 if (hmodule != NULL)
1877 if (per_module_data_dirs == NULL)
1878 per_module_data_dirs = g_hash_table_new (NULL, NULL);
1879 else
1881 retval = g_hash_table_lookup (per_module_data_dirs, hmodule);
1883 if (retval != NULL)
1885 G_UNLOCK (g_utils_global);
1886 return (const gchar * const *) retval;
1892 data_dirs = g_array_new (TRUE, TRUE, sizeof (char *));
1894 /* Documents and Settings\All Users\Application Data */
1895 p = get_special_folder (CSIDL_COMMON_APPDATA);
1896 if (p)
1897 g_array_append_val (data_dirs, p);
1899 /* Documents and Settings\All Users\Documents */
1900 p = get_special_folder (CSIDL_COMMON_DOCUMENTS);
1901 if (p)
1902 g_array_append_val (data_dirs, p);
1904 /* Using the above subfolders of Documents and Settings perhaps
1905 * makes sense from a Windows perspective.
1907 * But looking at the actual use cases of this function in GTK+
1908 * and GNOME software, what we really want is the "share"
1909 * subdirectory of the installation directory for the package
1910 * our caller is a part of.
1912 * The address_of_function parameter, if non-NULL, points to a
1913 * function in the calling module. Use that to determine that
1914 * module's installation folder, and use its "share" subfolder.
1916 * Additionally, also use the "share" subfolder of the installation
1917 * locations of GLib and the .exe file being run.
1919 * To guard against none of the above being what is really wanted,
1920 * callers of this function should have Win32-specific code to look
1921 * up their installation folder themselves, and handle a subfolder
1922 * "share" of it in the same way as the folders returned from this
1923 * function.
1926 p = get_module_share_dir (address_of_function);
1927 if (p)
1928 g_array_append_val (data_dirs, p);
1930 if (glib_dll != NULL)
1932 gchar *glib_root = g_win32_get_package_installation_directory_of_module (glib_dll);
1933 p = g_build_filename (glib_root, "share", NULL);
1934 if (p)
1935 g_array_append_val (data_dirs, p);
1936 g_free (glib_root);
1939 exe_root = g_win32_get_package_installation_directory_of_module (NULL);
1940 p = g_build_filename (exe_root, "share", NULL);
1941 if (p)
1942 g_array_append_val (data_dirs, p);
1943 g_free (exe_root);
1945 retval = (gchar **) g_array_free (data_dirs, FALSE);
1947 if (address_of_function)
1949 if (hmodule != NULL)
1950 g_hash_table_insert (per_module_data_dirs, hmodule, retval);
1951 G_UNLOCK (g_utils_global);
1954 return (const gchar * const *) retval;
1957 #endif
1960 * g_get_system_data_dirs:
1962 * Returns an ordered list of base directories in which to access
1963 * system-wide application data.
1965 * On UNIX platforms this is determined using the mechanisms described in
1966 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1967 * XDG Base Directory Specification</ulink>
1968 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
1970 * On Windows the first elements in the list are the Application Data
1971 * and Documents folders for All Users. (These can be determined only
1972 * on Windows 2000 or later and are not present in the list on other
1973 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
1974 * CSIDL_COMMON_DOCUMENTS.
1976 * Then follows the "share" subfolder in the installation folder for
1977 * the package containing the DLL that calls this function, if it can
1978 * be determined.
1980 * Finally the list contains the "share" subfolder in the installation
1981 * folder for GLib, and in the installation folder for the package the
1982 * application's .exe file belongs to.
1984 * The installation folders above are determined by looking up the
1985 * folder where the module (DLL or EXE) in question is located. If the
1986 * folder's name is "bin", its parent is used, otherwise the folder
1987 * itself.
1989 * Note that on Windows the returned list can vary depending on where
1990 * this function is called.
1992 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
1993 * not be modified or freed.
1994 * Since: 2.6
1996 const gchar * const *
1997 g_get_system_data_dirs (void)
1999 gchar **data_dir_vector;
2001 G_LOCK (g_utils_global);
2003 if (!g_system_data_dirs)
2005 #ifdef G_OS_WIN32
2006 data_dir_vector = (gchar **) g_win32_get_system_data_dirs_for_module (NULL);
2007 #else
2008 gchar *data_dirs = (gchar *) g_getenv ("XDG_DATA_DIRS");
2010 if (!data_dirs || !data_dirs[0])
2011 data_dirs = "/usr/local/share/:/usr/share/";
2013 data_dir_vector = g_strsplit (data_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2014 #endif
2016 g_system_data_dirs = data_dir_vector;
2018 else
2019 data_dir_vector = g_system_data_dirs;
2021 G_UNLOCK (g_utils_global);
2023 return (const gchar * const *) data_dir_vector;
2027 * g_get_system_config_dirs:
2029 * Returns an ordered list of base directories in which to access
2030 * system-wide configuration information.
2032 * On UNIX platforms this is determined using the mechanisms described in
2033 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2034 * XDG Base Directory Specification</ulink>.
2035 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2037 * On Windows is the directory that contains application data for all users.
2038 * A typical path is C:\Documents and Settings\All Users\Application Data.
2039 * This folder is used for application data that is not user specific.
2040 * For example, an application can store a spell-check dictionary, a database
2041 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2042 * This information will not roam and is available to anyone using the computer.
2044 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2045 * not be modified or freed.
2046 * Since: 2.6
2048 const gchar * const *
2049 g_get_system_config_dirs (void)
2051 gchar *conf_dirs, **conf_dir_vector;
2053 G_LOCK (g_utils_global);
2055 if (!g_system_config_dirs)
2057 #ifdef G_OS_WIN32
2058 conf_dirs = get_special_folder (CSIDL_COMMON_APPDATA);
2059 if (conf_dirs)
2061 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2062 g_free (conf_dirs);
2064 else
2066 /* Return empty list */
2067 conf_dir_vector = g_strsplit ("", G_SEARCHPATH_SEPARATOR_S, 0);
2069 #else
2070 conf_dirs = (gchar *) g_getenv ("XDG_CONFIG_DIRS");
2072 if (!conf_dirs || !conf_dirs[0])
2073 conf_dirs = "/etc/xdg";
2075 conf_dir_vector = g_strsplit (conf_dirs, G_SEARCHPATH_SEPARATOR_S, 0);
2076 #endif
2078 g_system_config_dirs = conf_dir_vector;
2080 else
2081 conf_dir_vector = g_system_config_dirs;
2082 G_UNLOCK (g_utils_global);
2084 return (const gchar * const *) conf_dir_vector;
2088 * g_nullify_pointer:
2089 * @nullify_location: the memory address of the pointer.
2091 * Set the pointer at the specified location to %NULL.
2093 void
2094 g_nullify_pointer (gpointer *nullify_location)
2096 g_return_if_fail (nullify_location != NULL);
2098 *nullify_location = NULL;
2101 #define KILOBYTE_FACTOR (G_GOFFSET_CONSTANT (1000))
2102 #define MEGABYTE_FACTOR (KILOBYTE_FACTOR * KILOBYTE_FACTOR)
2103 #define GIGABYTE_FACTOR (MEGABYTE_FACTOR * KILOBYTE_FACTOR)
2104 #define TERABYTE_FACTOR (GIGABYTE_FACTOR * KILOBYTE_FACTOR)
2105 #define PETABYTE_FACTOR (TERABYTE_FACTOR * KILOBYTE_FACTOR)
2106 #define EXABYTE_FACTOR (PETABYTE_FACTOR * KILOBYTE_FACTOR)
2108 #define KIBIBYTE_FACTOR (G_GOFFSET_CONSTANT (1024))
2109 #define MEBIBYTE_FACTOR (KIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2110 #define GIBIBYTE_FACTOR (MEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2111 #define TEBIBYTE_FACTOR (GIBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2112 #define PEBIBYTE_FACTOR (TEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2113 #define EXBIBYTE_FACTOR (PEBIBYTE_FACTOR * KIBIBYTE_FACTOR)
2116 * g_format_size:
2117 * @size: a size in bytes
2119 * Formats a size (for example the size of a file) into a human readable
2120 * string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
2121 * and are displayed rounded to the nearest tenth. E.g. the file size
2122 * 3292528 bytes will be converted into the string "3.2 MB".
2124 * The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
2126 * This string should be freed with g_free() when not needed any longer.
2128 * See g_format_size_full() for more options about how the size might be
2129 * formatted.
2131 * Returns: a newly-allocated formatted string containing a human readable
2132 * file size
2134 * Since: 2.30
2136 gchar *
2137 g_format_size (guint64 size)
2139 return g_format_size_full (size, G_FORMAT_SIZE_DEFAULT);
2143 * GFormatSizeFlags:
2144 * @G_FORMAT_SIZE_DEFAULT: behave the same as g_format_size()
2145 * @G_FORMAT_SIZE_LONG_FORMAT: include the exact number of bytes as part
2146 * of the returned string. For example, "45.6 kB (45,612 bytes)".
2147 * @G_FORMAT_SIZE_IEC_UNITS: use IEC (base 1024) units with "KiB"-style
2148 * suffixes. IEC units should only be used for reporting things with
2149 * a strong "power of 2" basis, like RAM sizes or RAID stripe sizes.
2150 * Network and storage sizes should be reported in the normal SI units.
2152 * Flags to modify the format of the string returned by g_format_size_full().
2156 * g_format_size_full:
2157 * @size: a size in bytes
2158 * @flags: #GFormatSizeFlags to modify the output
2160 * Formats a size.
2162 * This function is similar to g_format_size() but allows for flags
2163 * that modify the output. See #GFormatSizeFlags.
2165 * Returns: a newly-allocated formatted string containing a human
2166 * readable file size
2168 * Since: 2.30
2170 gchar *
2171 g_format_size_full (guint64 size,
2172 GFormatSizeFlags flags)
2174 GString *string;
2176 string = g_string_new (NULL);
2178 if (flags & G_FORMAT_SIZE_IEC_UNITS)
2180 if (size < KIBIBYTE_FACTOR)
2182 g_string_printf (string,
2183 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2184 (guint) size);
2185 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2188 else if (size < MEBIBYTE_FACTOR)
2189 g_string_printf (string, _("%.1f KiB"), (gdouble) size / (gdouble) KIBIBYTE_FACTOR);
2190 else if (size < GIBIBYTE_FACTOR)
2191 g_string_printf (string, _("%.1f MiB"), (gdouble) size / (gdouble) MEBIBYTE_FACTOR);
2193 else if (size < TEBIBYTE_FACTOR)
2194 g_string_printf (string, _("%.1f GiB"), (gdouble) size / (gdouble) GIBIBYTE_FACTOR);
2196 else if (size < PEBIBYTE_FACTOR)
2197 g_string_printf (string, _("%.1f TiB"), (gdouble) size / (gdouble) TEBIBYTE_FACTOR);
2199 else if (size < EXBIBYTE_FACTOR)
2200 g_string_printf (string, _("%.1f PiB"), (gdouble) size / (gdouble) PEBIBYTE_FACTOR);
2202 else
2203 g_string_printf (string, _("%.1f EiB"), (gdouble) size / (gdouble) EXBIBYTE_FACTOR);
2205 else
2207 if (size < KILOBYTE_FACTOR)
2209 g_string_printf (string,
2210 g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes", (guint) size),
2211 (guint) size);
2212 flags &= ~G_FORMAT_SIZE_LONG_FORMAT;
2215 else if (size < MEGABYTE_FACTOR)
2216 g_string_printf (string, _("%.1f kB"), (gdouble) size / (gdouble) KILOBYTE_FACTOR);
2218 else if (size < GIGABYTE_FACTOR)
2219 g_string_printf (string, _("%.1f MB"), (gdouble) size / (gdouble) MEGABYTE_FACTOR);
2221 else if (size < TERABYTE_FACTOR)
2222 g_string_printf (string, _("%.1f GB"), (gdouble) size / (gdouble) GIGABYTE_FACTOR);
2223 else if (size < PETABYTE_FACTOR)
2224 g_string_printf (string, _("%.1f TB"), (gdouble) size / (gdouble) TERABYTE_FACTOR);
2226 else if (size < EXABYTE_FACTOR)
2227 g_string_printf (string, _("%.1f PB"), (gdouble) size / (gdouble) PETABYTE_FACTOR);
2229 else
2230 g_string_printf (string, _("%.1f EB"), (gdouble) size / (gdouble) EXABYTE_FACTOR);
2233 if (flags & G_FORMAT_SIZE_LONG_FORMAT)
2235 /* First problem: we need to use the number of bytes to decide on
2236 * the plural form that is used for display, but the number of
2237 * bytes potentially exceeds the size of a guint (which is what
2238 * ngettext() takes).
2240 * From a pragmatic standpoint, it seems that all known languages
2241 * base plural forms on one or both of the following:
2243 * - the lowest digits of the number
2245 * - if the number if greater than some small value
2247 * Here's how we fake it: Draw an arbitrary line at one thousand.
2248 * If the number is below that, then fine. If it is above it,
2249 * then we take the modulus of the number by one thousand (in
2250 * order to keep the lowest digits) and add one thousand to that
2251 * (in order to ensure that 1001 is not treated the same as 1).
2253 guint plural_form = size < 1000 ? size : size % 1000 + 1000;
2255 /* Second problem: we need to translate the string "%u byte" and
2256 * "%u bytes" for pluralisation, but the correct number format to
2257 * use for a gsize is different depending on which architecture
2258 * we're on.
2260 * Solution: format the number separately and use "%s bytes" on
2261 * all platforms.
2263 const gchar *translated_format;
2264 gchar *formatted_number;
2266 /* Translators: the %s in "%s bytes" will always be replaced by a number. */
2267 translated_format = g_dngettext(GETTEXT_PACKAGE, "%s byte", "%s bytes", plural_form);
2268 /* XXX: Windows doesn't support the "'" format modifier, so we
2269 * must not use it there. Instead, just display the number
2270 * without separation. Bug #655336 is open until a solution is
2271 * found.
2273 #ifndef G_OS_WIN32
2274 formatted_number = g_strdup_printf ("%'"G_GUINT64_FORMAT, size);
2275 #else
2276 formatted_number = g_strdup_printf ("%"G_GUINT64_FORMAT, size);
2277 #endif
2279 g_string_append (string, " (");
2280 g_string_append_printf (string, translated_format, formatted_number);
2281 g_free (formatted_number);
2282 g_string_append (string, ")");
2285 return g_string_free (string, FALSE);
2289 * g_format_size_for_display:
2290 * @size: a size in bytes
2292 * Formats a size (for example the size of a file) into a human
2293 * readable string. Sizes are rounded to the nearest size prefix
2294 * (KB, MB, GB) and are displayed rounded to the nearest tenth.
2295 * E.g. the file size 3292528 bytes will be converted into the
2296 * string "3.1 MB".
2298 * The prefix units base is 1024 (i.e. 1 KB is 1024 bytes).
2300 * This string should be freed with g_free() when not needed any longer.
2302 * Returns: a newly-allocated formatted string containing a human
2303 * readable file size
2305 * Since: 2.16
2307 * Deprecated:2.30: This function is broken due to its use of SI
2308 * suffixes to denote IEC units. Use g_format_size() instead.
2310 gchar *
2311 g_format_size_for_display (goffset size)
2313 if (size < (goffset) KIBIBYTE_FACTOR)
2314 return g_strdup_printf (g_dngettext(GETTEXT_PACKAGE, "%u byte", "%u bytes",(guint) size), (guint) size);
2315 else
2317 gdouble displayed_size;
2319 if (size < (goffset) MEBIBYTE_FACTOR)
2321 displayed_size = (gdouble) size / (gdouble) KIBIBYTE_FACTOR;
2322 /* Translators: this is from the deprecated function g_format_size_for_display() which uses 'KB' to
2323 * mean 1024 bytes. I am aware that 'KB' is not correct, but it has been preserved for reasons of
2324 * compatibility. Users will not see this string unless a program is using this deprecated function.
2325 * Please translate as literally as possible.
2327 return g_strdup_printf (_("%.1f KB"), displayed_size);
2329 else if (size < (goffset) GIBIBYTE_FACTOR)
2331 displayed_size = (gdouble) size / (gdouble) MEBIBYTE_FACTOR;
2332 return g_strdup_printf (_("%.1f MB"), displayed_size);
2334 else if (size < (goffset) TEBIBYTE_FACTOR)
2336 displayed_size = (gdouble) size / (gdouble) GIBIBYTE_FACTOR;
2337 return g_strdup_printf (_("%.1f GB"), displayed_size);
2339 else if (size < (goffset) PEBIBYTE_FACTOR)
2341 displayed_size = (gdouble) size / (gdouble) TEBIBYTE_FACTOR;
2342 return g_strdup_printf (_("%.1f TB"), displayed_size);
2344 else if (size < (goffset) EXBIBYTE_FACTOR)
2346 displayed_size = (gdouble) size / (gdouble) PEBIBYTE_FACTOR;
2347 return g_strdup_printf (_("%.1f PB"), displayed_size);
2349 else
2351 displayed_size = (gdouble) size / (gdouble) EXBIBYTE_FACTOR;
2352 return g_strdup_printf (_("%.1f EB"), displayed_size);
2357 #if defined (G_OS_WIN32) && !defined (_WIN64)
2359 /* Binary compatibility versions. Not for newly compiled code. */
2361 _GLIB_EXTERN const gchar *g_get_user_name_utf8 (void);
2362 _GLIB_EXTERN const gchar *g_get_real_name_utf8 (void);
2363 _GLIB_EXTERN const gchar *g_get_home_dir_utf8 (void);
2364 _GLIB_EXTERN const gchar *g_get_tmp_dir_utf8 (void);
2365 _GLIB_EXTERN gchar *g_find_program_in_path_utf8 (const gchar *program);
2367 gchar *
2368 g_find_program_in_path_utf8 (const gchar *program)
2370 return g_find_program_in_path (program);
2373 const gchar *g_get_user_name_utf8 (void) { return g_get_user_name (); }
2374 const gchar *g_get_real_name_utf8 (void) { return g_get_real_name (); }
2375 const gchar *g_get_home_dir_utf8 (void) { return g_get_home_dir (); }
2376 const gchar *g_get_tmp_dir_utf8 (void) { return g_get_tmp_dir (); }
2378 #endif
2380 /* Private API:
2382 * Returns %TRUE if the current process was executed as setuid (or an
2383 * equivalent __libc_enable_secure is available). See:
2384 * http://osdir.com/ml/linux.lfs.hardened/2007-04/msg00032.html
2386 gboolean
2387 g_check_setuid (void)
2389 /* TODO: get __libc_enable_secure exported from glibc.
2390 * See http://www.openwall.com/lists/owl-dev/2012/08/14/1
2392 #if 0 && defined(HAVE_LIBC_ENABLE_SECURE)
2394 /* See glibc/include/unistd.h */
2395 extern int __libc_enable_secure;
2396 return __libc_enable_secure;
2398 #elif defined(HAVE_ISSETUGID)
2399 /* BSD: http://www.freebsd.org/cgi/man.cgi?query=issetugid&sektion=2 */
2400 return issetugid ();
2401 #elif defined(G_OS_UNIX)
2402 uid_t ruid, euid, suid; /* Real, effective and saved user ID's */
2403 gid_t rgid, egid, sgid; /* Real, effective and saved group ID's */
2405 static gsize check_setuid_initialised;
2406 static gboolean is_setuid;
2408 if (g_once_init_enter (&check_setuid_initialised))
2410 #ifdef HAVE_GETRESUID
2411 /* These aren't in the header files, so we prototype them here.
2413 int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid);
2414 int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid);
2416 if (getresuid (&ruid, &euid, &suid) != 0 ||
2417 getresgid (&rgid, &egid, &sgid) != 0)
2418 #endif /* HAVE_GETRESUID */
2420 suid = ruid = getuid ();
2421 sgid = rgid = getgid ();
2422 euid = geteuid ();
2423 egid = getegid ();
2426 is_setuid = (ruid != euid || ruid != suid ||
2427 rgid != egid || rgid != sgid);
2429 g_once_init_leave (&check_setuid_initialised, 1);
2431 return is_setuid;
2432 #else
2433 return FALSE;
2434 #endif