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"
67 #include "gprintfint.h"
69 #include "gthreadprivate.h"
70 #include "gtestutils.h"
72 #include "gstrfuncs.h"
76 #ifdef G_PLATFORM_WIN32
85 * @title: Miscellaneous Utility Functions
86 * @short_description: a selection of portable utility functions
88 * These are portable utility functions.
92 #define G_PATH_LENGTH MAXPATHLEN
93 #elif defined (PATH_MAX)
94 #define G_PATH_LENGTH PATH_MAX
95 #elif defined (_PC_PATH_MAX)
96 #define G_PATH_LENGTH sysconf(_PC_PATH_MAX)
98 #define G_PATH_LENGTH 2048
101 #ifdef G_PLATFORM_WIN32
102 # include <windows.h>
103 # ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
104 # define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
105 # define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
107 # include <lmcons.h> /* For UNLEN */
108 #endif /* G_PLATFORM_WIN32 */
113 /* older SDK (e.g. msvc 5.0) does not have these*/
114 # ifndef CSIDL_MYMUSIC
115 # define CSIDL_MYMUSIC 13
117 # ifndef CSIDL_MYVIDEO
118 # define CSIDL_MYVIDEO 14
120 # ifndef CSIDL_INTERNET_CACHE
121 # define CSIDL_INTERNET_CACHE 32
123 # ifndef CSIDL_COMMON_APPDATA
124 # define CSIDL_COMMON_APPDATA 35
126 # ifndef CSIDL_MYPICTURES
127 # define CSIDL_MYPICTURES 0x27
129 # ifndef CSIDL_COMMON_DOCUMENTS
130 # define CSIDL_COMMON_DOCUMENTS 46
132 # ifndef CSIDL_PROFILE
133 # define CSIDL_PROFILE 40
135 # include <process.h>
139 #include <CoreServices/CoreServices.h>
143 #include <langinfo.h>
146 #ifdef G_PLATFORM_WIN32
149 _glib_get_dll_directory (void)
153 wchar_t wc_fn
[MAX_PATH
];
156 if (glib_dll
== NULL
)
160 /* This code is different from that in
161 * g_win32_get_package_installation_directory_of_module() in that
162 * here we return the actual folder where the GLib DLL is. We don't
163 * do the check for it being in a "bin" or "lib" subfolder and then
164 * returning the parent of that.
166 * In a statically built GLib, glib_dll will be NULL and we will
167 * thus look up the application's .exe file's location.
169 if (!GetModuleFileNameW (glib_dll
, wc_fn
, MAX_PATH
))
172 retval
= g_utf16_to_utf8 (wc_fn
, -1, NULL
, NULL
, NULL
);
174 p
= strrchr (retval
, G_DIR_SEPARATOR
);
187 #if !defined (HAVE_MEMMOVE) && !defined (HAVE_WORKING_BCOPY)
190 * @dest: the destination address to copy the bytes to.
191 * @src: the source address to copy the bytes from.
192 * @len: the number of bytes to copy.
194 * Copies a block of memory @len bytes long, from @src to @dest.
195 * The source and destination areas may overlap.
197 * In order to use this function, you must include
198 * <filename>string.h</filename> yourself, because this macro will
199 * typically simply resolve to memmove() and GLib does not include
200 * <filename>string.h</filename> for you.
203 g_memmove (gpointer dest
,
207 gchar
* destptr
= dest
;
208 const gchar
* srcptr
= src
;
209 if (src
+ len
< dest
|| dest
+ len
< src
)
211 bcopy (src
, dest
, len
);
214 else if (dest
<= src
)
217 *(destptr
++) = *(srcptr
++);
224 *(--destptr
) = *(--srcptr
);
227 #endif /* !HAVE_MEMMOVE && !HAVE_WORKING_BCOPY */
235 * @func: (scope async): the function to call on normal program termination.
237 * Specifies a function to be called at normal program termination.
239 * Since GLib 2.8.2, on Windows g_atexit() actually is a preprocessor
240 * macro that maps to a call to the atexit() function in the C
241 * library. This means that in case the code that calls g_atexit(),
242 * i.e. atexit(), is in a DLL, the function will be called when the
243 * DLL is detached from the program. This typically makes more sense
244 * than that the function is called when the GLib DLL is detached,
245 * which happened earlier when g_atexit() was a function in the GLib
248 * The behaviour of atexit() in the context of dynamically loaded
249 * modules is not formally specified and varies wildly.
251 * On POSIX systems, calling g_atexit() (or atexit()) in a dynamically
252 * loaded module which is unloaded before the program terminates might
253 * well cause a crash at program exit.
255 * Some POSIX systems implement atexit() like Windows, and have each
256 * dynamically loaded module maintain an own atexit chain that is
257 * called when the module is unloaded.
259 * On other POSIX systems, before a dynamically loaded module is
260 * unloaded, the registered atexit functions (if any) residing in that
261 * module are called, regardless where the code that registered them
262 * resided. This is presumably the most robust approach.
264 * As can be seen from the above, for portability it's best to avoid
265 * calling g_atexit() (or atexit()) except in the main executable of a
269 g_atexit (GVoidFunc func
)
272 const gchar
*error
= NULL
;
274 /* keep this in sync with glib.h */
276 #ifdef G_NATIVE_ATEXIT
277 result
= ATEXIT (func
);
279 error
= g_strerror (errno
);
280 #elif defined (HAVE_ATEXIT)
281 # ifdef NeXT /* @#%@! NeXTStep */
282 result
= !atexit ((void (*)(void)) func
);
284 error
= g_strerror (errno
);
286 result
= atexit ((void (*)(void)) func
);
288 error
= g_strerror (errno
);
290 #elif defined (HAVE_ON_EXIT)
291 result
= on_exit ((void (*)(int, void *)) func
, NULL
);
293 error
= g_strerror (errno
);
296 error
= "no implementation";
297 #endif /* G_NATIVE_ATEXIT */
300 g_error ("Could not register atexit() function: %s", error
);
303 /* Based on execvp() from GNU Libc.
304 * Some of this code is cut-and-pasted into gspawn.c
308 my_strchrnul (const gchar
*str
,
311 gchar
*p
= (gchar
*)str
;
312 while (*p
&& (*p
!= c
))
320 static gchar
*inner_find_program_in_path (const gchar
*program
);
323 g_find_program_in_path (const gchar
*program
)
325 const gchar
*last_dot
= strrchr (program
, '.');
327 if (last_dot
== NULL
||
328 strchr (last_dot
, '\\') != NULL
||
329 strchr (last_dot
, '/') != NULL
)
331 const gint program_length
= strlen (program
);
332 gchar
*pathext
= g_build_path (";",
333 ".exe;.cmd;.bat;.com",
334 g_getenv ("PATHEXT"),
337 gchar
*decorated_program
;
343 gchar
*q
= my_strchrnul (p
, ';');
345 decorated_program
= g_malloc (program_length
+ (q
-p
) + 1);
346 memcpy (decorated_program
, program
, program_length
);
347 memcpy (decorated_program
+program_length
, p
, q
-p
);
348 decorated_program
[program_length
+ (q
-p
)] = '\0';
350 retval
= inner_find_program_in_path (decorated_program
);
351 g_free (decorated_program
);
359 } while (*p
++ != '\0');
364 return inner_find_program_in_path (program
);
370 * g_find_program_in_path:
371 * @program: a program name in the GLib file name encoding
373 * Locates the first executable named @program in the user's path, in the
374 * same way that execvp() would locate it. Returns an allocated string
375 * with the absolute path name, or %NULL if the program is not found in
376 * the path. If @program is already an absolute path, returns a copy of
377 * @program if @program exists and is executable, and %NULL otherwise.
379 * On Windows, if @program does not have a file type suffix, tries
380 * with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
381 * the <envar>PATHEXT</envar> environment variable.
383 * On Windows, it looks for the file in the same way as CreateProcess()
384 * would. This means first in the directory where the executing
385 * program was loaded from, then in the current directory, then in the
386 * Windows 32-bit system directory, then in the Windows directory, and
387 * finally in the directories in the <envar>PATH</envar> environment
388 * variable. If the program is found, the return value contains the
389 * full name including the type suffix.
391 * Return value: absolute path, or %NULL
395 inner_find_program_in_path (const gchar
*program
)
398 g_find_program_in_path (const gchar
*program
)
401 const gchar
*path
, *p
;
402 gchar
*name
, *freeme
;
404 const gchar
*path_copy
;
405 gchar
*filename
= NULL
, *appdir
= NULL
;
406 gchar
*sysdir
= NULL
, *windir
= NULL
;
408 wchar_t wfilename
[MAXPATHLEN
], wsysdir
[MAXPATHLEN
],
414 g_return_val_if_fail (program
!= NULL
, NULL
);
416 /* If it is an absolute path, or a relative path including subdirectories,
417 * don't look in PATH.
419 if (g_path_is_absolute (program
)
420 || strchr (program
, G_DIR_SEPARATOR
) != NULL
422 || strchr (program
, '/') != NULL
426 if (g_file_test (program
, G_FILE_TEST_IS_EXECUTABLE
) &&
427 !g_file_test (program
, G_FILE_TEST_IS_DIR
))
428 return g_strdup (program
);
433 path
= g_getenv ("PATH");
434 #if defined(G_OS_UNIX) || defined(G_OS_BEOS)
437 /* There is no `PATH' in the environment. The default
438 * search path in GNU libc is the current directory followed by
439 * the path `confstr' returns for `_CS_PATH'.
442 /* In GLib we put . last, for security, and don't use the
443 * unportable confstr(); UNIX98 does not actually specify
444 * what to search if PATH is unset. POSIX may, dunno.
447 path
= "/bin:/usr/bin:.";
450 n
= GetModuleFileNameW (NULL
, wfilename
, MAXPATHLEN
);
451 if (n
> 0 && n
< MAXPATHLEN
)
452 filename
= g_utf16_to_utf8 (wfilename
, -1, NULL
, NULL
, NULL
);
454 n
= GetSystemDirectoryW (wsysdir
, MAXPATHLEN
);
455 if (n
> 0 && n
< MAXPATHLEN
)
456 sysdir
= g_utf16_to_utf8 (wsysdir
, -1, NULL
, NULL
, NULL
);
458 n
= GetWindowsDirectoryW (wwindir
, MAXPATHLEN
);
459 if (n
> 0 && n
< MAXPATHLEN
)
460 windir
= g_utf16_to_utf8 (wwindir
, -1, NULL
, NULL
, NULL
);
464 appdir
= g_path_get_dirname (filename
);
468 path
= g_strdup (path
);
472 const gchar
*tem
= path
;
473 path
= g_strconcat (windir
, ";", path
, NULL
);
474 g_free ((gchar
*) tem
);
480 const gchar
*tem
= path
;
481 path
= g_strconcat (sysdir
, ";", path
, NULL
);
482 g_free ((gchar
*) tem
);
487 const gchar
*tem
= path
;
488 path
= g_strconcat (".;", path
, NULL
);
489 g_free ((gchar
*) tem
);
494 const gchar
*tem
= path
;
495 path
= g_strconcat (appdir
, ";", path
, NULL
);
496 g_free ((gchar
*) tem
);
503 len
= strlen (program
) + 1;
504 pathlen
= strlen (path
);
505 freeme
= name
= g_malloc (pathlen
+ len
+ 1);
507 /* Copy the file name at the top, including '\0' */
508 memcpy (name
+ pathlen
+ 1, program
, len
);
509 name
= name
+ pathlen
;
510 /* And add the slash before the filename */
511 *name
= G_DIR_SEPARATOR
;
519 p
= my_strchrnul (path
, G_SEARCHPATH_SEPARATOR
);
522 /* Two adjacent colons, or a colon at the beginning or the end
523 * of `PATH' means to search the current directory.
527 startp
= memcpy (name
- (p
- path
), path
, p
- path
);
529 if (g_file_test (startp
, G_FILE_TEST_IS_EXECUTABLE
) &&
530 !g_file_test (startp
, G_FILE_TEST_IS_DIR
))
533 ret
= g_strdup (startp
);
536 g_free ((gchar
*) path_copy
);
541 while (*p
++ != '\0');
545 g_free ((gchar
*) path_copy
);
553 * @file_name: the name of the file.
555 * Gets the name of the file without any leading directory components.
556 * It returns a pointer into the given file name string.
558 * Return value: the name of the file without any leading directory components.
560 * Deprecated:2.2: Use g_path_get_basename() instead, but notice that
561 * g_path_get_basename() allocates new memory for the returned string, unlike
562 * this function which returns a pointer into the argument.
565 g_basename (const gchar
*file_name
)
567 register gchar
*base
;
569 g_return_val_if_fail (file_name
!= NULL
, NULL
);
571 base
= strrchr (file_name
, G_DIR_SEPARATOR
);
575 gchar
*q
= strrchr (file_name
, '/');
576 if (base
== NULL
|| (q
!= NULL
&& q
> base
))
585 if (g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
586 return (gchar
*) file_name
+ 2;
587 #endif /* G_OS_WIN32 */
589 return (gchar
*) file_name
;
593 * g_path_get_basename:
594 * @file_name: the name of the file.
596 * Gets the last component of the filename. If @file_name ends with a
597 * directory separator it gets the component before the last slash. If
598 * @file_name consists only of directory separators (and on Windows,
599 * possibly a drive letter), a single separator is returned. If
600 * @file_name is empty, it gets ".".
602 * Return value: a newly allocated string containing the last component of
606 g_path_get_basename (const gchar
*file_name
)
608 register gssize base
;
609 register gssize last_nonslash
;
613 g_return_val_if_fail (file_name
!= NULL
, NULL
);
615 if (file_name
[0] == '\0')
617 return g_strdup (".");
619 last_nonslash
= strlen (file_name
) - 1;
621 while (last_nonslash
>= 0 && G_IS_DIR_SEPARATOR (file_name
[last_nonslash
]))
624 if (last_nonslash
== -1)
625 /* string only containing slashes */
626 return g_strdup (G_DIR_SEPARATOR_S
);
629 if (last_nonslash
== 1 && g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
630 /* string only containing slashes and a drive */
631 return g_strdup (G_DIR_SEPARATOR_S
);
632 #endif /* G_OS_WIN32 */
634 base
= last_nonslash
;
636 while (base
>=0 && !G_IS_DIR_SEPARATOR (file_name
[base
]))
640 if (base
== -1 && g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
642 #endif /* G_OS_WIN32 */
644 len
= last_nonslash
- base
;
645 retval
= g_malloc (len
+ 1);
646 memcpy (retval
, file_name
+ base
+ 1, len
);
652 * g_path_is_absolute:
653 * @file_name: a file name.
655 * Returns %TRUE if the given @file_name is an absolute file name.
656 * Note that this is a somewhat vague concept on Windows.
658 * On POSIX systems, an absolute file name is well-defined. It always
659 * starts from the single root directory. For example "/usr/local".
661 * On Windows, the concepts of current drive and drive-specific
662 * current directory introduce vagueness. This function interprets as
663 * an absolute file name one that either begins with a directory
664 * separator such as "\Users\tml" or begins with the root on a drive,
665 * for example "C:\Windows". The first case also includes UNC paths
666 * such as "\\myserver\docs\foo". In all cases, either slashes or
667 * backslashes are accepted.
669 * Note that a file name relative to the current drive root does not
670 * truly specify a file uniquely over time and across processes, as
671 * the current drive is a per-process value and can be changed.
673 * File names relative the current directory on some specific drive,
674 * such as "D:foo/bar", are not interpreted as absolute by this
675 * function, but they obviously are not relative to the normal current
676 * directory as returned by getcwd() or g_get_current_dir()
677 * either. Such paths should be avoided, or need to be handled using
678 * Windows-specific code.
680 * Returns: %TRUE if @file_name is absolute.
683 g_path_is_absolute (const gchar
*file_name
)
685 g_return_val_if_fail (file_name
!= NULL
, FALSE
);
687 if (G_IS_DIR_SEPARATOR (file_name
[0]))
691 /* Recognize drive letter on native Windows */
692 if (g_ascii_isalpha (file_name
[0]) &&
693 file_name
[1] == ':' && G_IS_DIR_SEPARATOR (file_name
[2]))
695 #endif /* G_OS_WIN32 */
702 * @file_name: a file name.
704 * Returns a pointer into @file_name after the root component, i.e. after
705 * the "/" in UNIX or "C:\" under Windows. If @file_name is not an absolute
706 * path it returns %NULL.
708 * Returns: a pointer into @file_name after the root component.
711 g_path_skip_root (const gchar
*file_name
)
713 g_return_val_if_fail (file_name
!= NULL
, NULL
);
715 #ifdef G_PLATFORM_WIN32
716 /* Skip \\server\share or //server/share */
717 if (G_IS_DIR_SEPARATOR (file_name
[0]) &&
718 G_IS_DIR_SEPARATOR (file_name
[1]) &&
720 !G_IS_DIR_SEPARATOR (file_name
[2]))
724 p
= strchr (file_name
+ 2, G_DIR_SEPARATOR
);
727 gchar
*q
= strchr (file_name
+ 2, '/');
728 if (p
== NULL
|| (q
!= NULL
&& q
< p
))
738 while (file_name
[0] && !G_IS_DIR_SEPARATOR (file_name
[0]))
741 /* Possibly skip a backslash after the share name */
742 if (G_IS_DIR_SEPARATOR (file_name
[0]))
745 return (gchar
*)file_name
;
750 /* Skip initial slashes */
751 if (G_IS_DIR_SEPARATOR (file_name
[0]))
753 while (G_IS_DIR_SEPARATOR (file_name
[0]))
755 return (gchar
*)file_name
;
760 if (g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':' && G_IS_DIR_SEPARATOR (file_name
[2]))
761 return (gchar
*)file_name
+ 3;
769 * @mask: a #gulong containing flags
770 * @nth_bit: the index of the bit to start the search from
772 * Find the position of the first bit set in @mask, searching
773 * from (but not including) @nth_bit upwards. Bits are numbered
774 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
775 * usually). To start searching from the 0th bit, set @nth_bit to -1.
777 * Returns: the index of the first bit set which is higher than @nth_bit
782 * @mask: a #gulong containing flags
783 * @nth_bit: the index of the bit to start the search from
785 * Find the position of the first bit set in @mask, searching
786 * from (but not including) @nth_bit downwards. Bits are numbered
787 * from 0 (least significant) to sizeof(#gulong) * 8 - 1 (31 or 63,
788 * usually). To start searching from the last bit, set @nth_bit to
789 * -1 or GLIB_SIZEOF_LONG * 8.
791 * Returns: the index of the first bit set which is lower than @nth_bit
798 * Gets the number of bits used to hold @number,
799 * e.g. if @number is 4, 3 bits are needed.
801 * Returns: the number of bits used to hold @number
806 * @file_name: the name of the file
808 * Gets the directory components of a file name.
809 * If the file name has no directory components "." is returned.
810 * The returned string should be freed when no longer needed.
812 * Returns: the directory components of the file
814 * Deprecated: use g_path_get_dirname() instead
818 * g_path_get_dirname:
819 * @file_name: the name of the file.
821 * Gets the directory components of a file name. If the file name has no
822 * directory components "." is returned. The returned string should be
823 * freed when no longer needed.
825 * Returns: the directory components of the file.
828 g_path_get_dirname (const gchar
*file_name
)
830 register gchar
*base
;
833 g_return_val_if_fail (file_name
!= NULL
, NULL
);
835 base
= strrchr (file_name
, G_DIR_SEPARATOR
);
838 gchar
*q
= strrchr (file_name
, '/');
839 if (base
== NULL
|| (q
!= NULL
&& q
> base
))
846 if (g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
848 gchar drive_colon_dot
[4];
850 drive_colon_dot
[0] = file_name
[0];
851 drive_colon_dot
[1] = ':';
852 drive_colon_dot
[2] = '.';
853 drive_colon_dot
[3] = '\0';
855 return g_strdup (drive_colon_dot
);
858 return g_strdup (".");
861 while (base
> file_name
&& G_IS_DIR_SEPARATOR (*base
))
865 /* base points to the char before the last slash.
867 * In case file_name is the root of a drive (X:\) or a child of the
868 * root of a drive (X:\foo), include the slash.
870 * In case file_name is the root share of an UNC path
871 * (\\server\share), add a slash, returning \\server\share\ .
873 * In case file_name is a direct child of a share in an UNC path
874 * (\\server\share\foo), include the slash after the share name,
875 * returning \\server\share\ .
877 if (base
== file_name
+ 1 && g_ascii_isalpha (file_name
[0]) && file_name
[1] == ':')
879 else if (G_IS_DIR_SEPARATOR (file_name
[0]) &&
880 G_IS_DIR_SEPARATOR (file_name
[1]) &&
882 !G_IS_DIR_SEPARATOR (file_name
[2]) &&
883 base
>= file_name
+ 2)
885 const gchar
*p
= file_name
+ 2;
886 while (*p
&& !G_IS_DIR_SEPARATOR (*p
))
890 len
= (guint
) strlen (file_name
) + 1;
891 base
= g_new (gchar
, len
+ 1);
892 strcpy (base
, file_name
);
893 base
[len
-1] = G_DIR_SEPARATOR
;
897 if (G_IS_DIR_SEPARATOR (*p
))
900 while (*p
&& !G_IS_DIR_SEPARATOR (*p
))
908 len
= (guint
) 1 + base
- file_name
;
910 base
= g_new (gchar
, len
+ 1);
911 g_memmove (base
, file_name
, len
);
920 * Gets the current directory.
921 * The returned string should be freed when no longer needed. The encoding
922 * of the returned string is system defined. On Windows, it is always UTF-8.
924 * Returns: the current directory.
927 g_get_current_dir (void)
932 wchar_t dummy
[2], *wdir
;
935 len
= GetCurrentDirectoryW (2, dummy
);
936 wdir
= g_new (wchar_t, len
);
938 if (GetCurrentDirectoryW (len
, wdir
) == len
- 1)
939 dir
= g_utf16_to_utf8 (wdir
, -1, NULL
, NULL
, NULL
);
944 dir
= g_strdup ("\\");
950 gchar
*buffer
= NULL
;
952 static gulong max_len
= 0;
955 max_len
= (G_PATH_LENGTH
== -1) ? 2048 : G_PATH_LENGTH
;
957 /* We don't use getcwd(3) on SUNOS, because, it does a popen("pwd")
958 * and, if that wasn't bad enough, hangs in doing so.
960 #if (defined (sun) && !defined (__SVR4)) || !defined(HAVE_GETCWD)
961 buffer
= g_new (gchar
, max_len
+ 1);
963 dir
= getwd (buffer
);
964 #else /* !sun || !HAVE_GETCWD */
965 while (max_len
< G_MAXULONG
/ 2)
968 buffer
= g_new (gchar
, max_len
+ 1);
970 dir
= getcwd (buffer
, max_len
);
972 if (dir
|| errno
!= ERANGE
)
977 #endif /* !sun || !HAVE_GETCWD */
979 if (!dir
|| !*buffer
)
981 /* hm, should we g_error() out here?
982 * this can happen if e.g. "./" has mode \0000
984 buffer
[0] = G_DIR_SEPARATOR
;
988 dir
= g_strdup (buffer
);
995 G_LOCK_DEFINE_STATIC (g_utils_global
);
997 static gchar
*g_tmp_dir
= NULL
;
998 static gchar
*g_user_name
= NULL
;
999 static gchar
*g_real_name
= NULL
;
1000 static gchar
*g_home_dir
= NULL
;
1001 static gchar
*g_host_name
= NULL
;
1004 /* System codepage versions of the above, kept at file level so that they,
1005 * too, are produced only once.
1007 static gchar
*g_tmp_dir_cp
= NULL
;
1008 static gchar
*g_user_name_cp
= NULL
;
1009 static gchar
*g_real_name_cp
= NULL
;
1010 static gchar
*g_home_dir_cp
= NULL
;
1013 static gchar
*g_user_data_dir
= NULL
;
1014 static gchar
**g_system_data_dirs
= NULL
;
1015 static gchar
*g_user_cache_dir
= NULL
;
1016 static gchar
*g_user_config_dir
= NULL
;
1017 static gchar
**g_system_config_dirs
= NULL
;
1019 static gchar
**g_user_special_dirs
= NULL
;
1021 /* fifteen minutes of fame for everybody */
1022 #define G_USER_DIRS_EXPIRE 15 * 60
1027 get_special_folder (int csidl
)
1029 wchar_t path
[MAX_PATH
+1];
1031 LPITEMIDLIST pidl
= NULL
;
1033 gchar
*retval
= NULL
;
1035 hr
= SHGetSpecialFolderLocation (NULL
, csidl
, &pidl
);
1038 b
= SHGetPathFromIDListW (pidl
, path
);
1040 retval
= g_utf16_to_utf8 (path
, -1, NULL
, NULL
, NULL
);
1041 CoTaskMemFree (pidl
);
1047 get_windows_directory_root (void)
1049 wchar_t wwindowsdir
[MAX_PATH
];
1051 if (GetWindowsDirectoryW (wwindowsdir
, G_N_ELEMENTS (wwindowsdir
)))
1053 /* Usually X:\Windows, but in terminal server environments
1054 * might be an UNC path, AFAIK.
1056 char *windowsdir
= g_utf16_to_utf8 (wwindowsdir
, -1, NULL
, NULL
, NULL
);
1059 if (windowsdir
== NULL
)
1060 return g_strdup ("C:\\");
1062 p
= (char *) g_path_skip_root (windowsdir
);
1063 if (G_IS_DIR_SEPARATOR (p
[-1]) && p
[-2] != ':')
1069 return g_strdup ("C:\\");
1074 /* HOLDS: g_utils_global_lock */
1076 g_get_any_init_do (void)
1078 gchar hostname
[100];
1080 g_tmp_dir
= g_strdup (g_getenv ("TMPDIR"));
1081 if (g_tmp_dir
== NULL
|| *g_tmp_dir
== '\0')
1082 g_tmp_dir
= g_strdup (g_getenv ("TMP"));
1083 if (g_tmp_dir
== NULL
|| *g_tmp_dir
== '\0')
1084 g_tmp_dir
= g_strdup (g_getenv ("TEMP"));
1087 if (g_tmp_dir
== NULL
|| *g_tmp_dir
== '\0')
1088 g_tmp_dir
= get_windows_directory_root ();
1091 if (g_tmp_dir
== NULL
|| *g_tmp_dir
== '\0')
1094 g_tmp_dir
= g_strdup (P_tmpdir
);
1095 k
= strlen (g_tmp_dir
);
1096 if (k
> 1 && G_IS_DIR_SEPARATOR (g_tmp_dir
[k
- 1]))
1097 g_tmp_dir
[k
- 1] = '\0';
1101 if (g_tmp_dir
== NULL
|| *g_tmp_dir
== '\0')
1103 g_tmp_dir
= g_strdup ("/tmp");
1105 #endif /* !G_OS_WIN32 */
1108 /* We check $HOME first for Win32, though it is a last resort for Unix
1109 * where we prefer the results of getpwuid().
1111 g_home_dir
= g_strdup (g_getenv ("HOME"));
1113 /* Only believe HOME if it is an absolute path and exists */
1116 if (!(g_path_is_absolute (g_home_dir
) &&
1117 g_file_test (g_home_dir
, G_FILE_TEST_IS_DIR
)))
1119 g_free (g_home_dir
);
1124 /* In case HOME is Unix-style (it happens), convert it to
1130 while ((p
= strchr (g_home_dir
, '/')) != NULL
)
1136 /* USERPROFILE is probably the closest equivalent to $HOME? */
1137 if (g_getenv ("USERPROFILE") != NULL
)
1138 g_home_dir
= g_strdup (g_getenv ("USERPROFILE"));
1142 g_home_dir
= get_special_folder (CSIDL_PROFILE
);
1145 g_home_dir
= get_windows_directory_root ();
1146 #endif /* G_OS_WIN32 */
1150 struct passwd
*pw
= NULL
;
1151 gpointer buffer
= NULL
;
1155 # if defined (HAVE_POSIX_GETPWUID_R) || defined (HAVE_NONPOSIX_GETPWUID_R)
1157 # ifdef _SC_GETPW_R_SIZE_MAX
1158 /* This reurns the maximum length */
1159 glong bufsize
= sysconf (_SC_GETPW_R_SIZE_MAX
);
1163 # else /* _SC_GETPW_R_SIZE_MAX */
1165 # endif /* _SC_GETPW_R_SIZE_MAX */
1167 logname
= (gchar
*) g_getenv ("LOGNAME");
1172 /* we allocate 6 extra bytes to work around a bug in
1173 * Mac OS < 10.3. See #156446
1175 buffer
= g_malloc (bufsize
+ 6);
1178 # ifdef HAVE_POSIX_GETPWUID_R
1180 error
= getpwnam_r (logname
, &pwd
, buffer
, bufsize
, &pw
);
1181 if (!pw
|| (pw
->pw_uid
!= getuid ())) {
1182 /* LOGNAME is lying, fall back to looking up the uid */
1183 error
= getpwuid_r (getuid (), &pwd
, buffer
, bufsize
, &pw
);
1186 error
= getpwuid_r (getuid (), &pwd
, buffer
, bufsize
, &pw
);
1188 error
= error
< 0 ? errno
: error
;
1189 # else /* HAVE_NONPOSIX_GETPWUID_R */
1190 /* HPUX 11 falls into the HAVE_POSIX_GETPWUID_R case */
1191 # if defined(_AIX) || defined(__hpux)
1192 error
= getpwuid_r (getuid (), &pwd
, buffer
, bufsize
);
1193 pw
= error
== 0 ? &pwd
: NULL
;
1196 pw
= getpwnam_r (logname
, &pwd
, buffer
, bufsize
);
1197 if (!pw
|| (pw
->pw_uid
!= getuid ())) {
1198 /* LOGNAME is lying, fall back to looking up the uid */
1199 pw
= getpwuid_r (getuid (), &pwd
, buffer
, bufsize
);
1202 pw
= getpwuid_r (getuid (), &pwd
, buffer
, bufsize
);
1204 error
= pw
? 0 : errno
;
1206 # endif /* HAVE_NONPOSIX_GETPWUID_R */
1210 /* we bail out prematurely if the user id can't be found
1211 * (should be pretty rare case actually), or if the buffer
1212 * should be sufficiently big and lookups are still not
1215 if (error
== 0 || error
== ENOENT
)
1217 g_warning ("getpwuid_r(): failed due to unknown user id (%lu)",
1218 (gulong
) getuid ());
1221 if (bufsize
> 32 * 1024)
1223 g_warning ("getpwuid_r(): failed due to: %s.",
1224 g_strerror (error
));
1232 # endif /* HAVE_POSIX_GETPWUID_R || HAVE_NONPOSIX_GETPWUID_R */
1237 pw
= getpwuid (getuid ());
1242 g_user_name
= g_strdup (pw
->pw_name
);
1244 if (pw
->pw_gecos
&& *pw
->pw_gecos
!= '\0')
1246 gchar
**gecos_fields
;
1249 /* split the gecos field and substitute '&' */
1250 gecos_fields
= g_strsplit (pw
->pw_gecos
, ",", 0);
1251 name_parts
= g_strsplit (gecos_fields
[0], "&", 0);
1252 pw
->pw_name
[0] = g_ascii_toupper (pw
->pw_name
[0]);
1253 g_real_name
= g_strjoinv (pw
->pw_name
, name_parts
);
1254 g_strfreev (gecos_fields
);
1255 g_strfreev (name_parts
);
1259 g_home_dir
= g_strdup (pw
->pw_dir
);
1264 #else /* !HAVE_PWD_H */
1268 guint len
= UNLEN
+1;
1269 wchar_t buffer
[UNLEN
+1];
1271 if (GetUserNameW (buffer
, (LPDWORD
) &len
))
1273 g_user_name
= g_utf16_to_utf8 (buffer
, -1, NULL
, NULL
, NULL
);
1274 g_real_name
= g_strdup (g_user_name
);
1277 #endif /* G_OS_WIN32 */
1279 #endif /* !HAVE_PWD_H */
1283 g_home_dir
= g_strdup (g_getenv ("HOME"));
1287 /* change '\\' in %HOME% to '/' */
1288 g_strdelimit (g_home_dir
, "\\",'/');
1291 g_user_name
= g_strdup ("somebody");
1293 g_real_name
= g_strdup ("Unknown");
1297 gboolean hostname_fail
= (gethostname (hostname
, sizeof (hostname
)) == -1);
1299 DWORD size
= sizeof (hostname
);
1300 gboolean hostname_fail
= (!GetComputerName (hostname
, &size
));
1302 g_host_name
= g_strdup (hostname_fail
? "localhost" : hostname
);
1306 g_tmp_dir_cp
= g_locale_from_utf8 (g_tmp_dir
, -1, NULL
, NULL
, NULL
);
1307 g_user_name_cp
= g_locale_from_utf8 (g_user_name
, -1, NULL
, NULL
, NULL
);
1308 g_real_name_cp
= g_locale_from_utf8 (g_real_name
, -1, NULL
, NULL
, NULL
);
1311 g_tmp_dir_cp
= g_strdup ("\\");
1312 if (!g_user_name_cp
)
1313 g_user_name_cp
= g_strdup ("somebody");
1314 if (!g_real_name_cp
)
1315 g_real_name_cp
= g_strdup ("Unknown");
1317 /* home_dir might be NULL, unlike tmp_dir, user_name and
1321 g_home_dir_cp
= g_locale_from_utf8 (g_home_dir
, -1, NULL
, NULL
, NULL
);
1323 g_home_dir_cp
= NULL
;
1324 #endif /* G_OS_WIN32 */
1328 g_get_any_init (void)
1331 g_get_any_init_do ();
1335 g_get_any_init_locked (void)
1337 G_LOCK (g_utils_global
);
1339 G_UNLOCK (g_utils_global
);
1346 * Gets the user name of the current user. The encoding of the returned
1347 * string is system-defined. On UNIX, it might be the preferred file name
1348 * encoding, or something else, and there is no guarantee that it is even
1349 * consistent on a machine. On Windows, it is always UTF-8.
1351 * Returns: the user name of the current user.
1354 g_get_user_name (void)
1356 g_get_any_init_locked ();
1363 * Gets the real name of the user. This usually comes from the user's entry
1364 * in the <filename>passwd</filename> file. The encoding of the returned
1365 * string is system-defined. (On Windows, it is, however, always UTF-8.)
1366 * If the real user name cannot be determined, the string "Unknown" is
1369 * Returns: the user's real name.
1372 g_get_real_name (void)
1374 g_get_any_init_locked ();
1381 * Gets the current user's home directory as defined in the
1382 * password database.
1384 * Note that in contrast to traditional UNIX tools, this function
1385 * prefers <filename>passwd</filename> entries over the <envar>HOME</envar>
1386 * environment variable.
1388 * One of the reasons for this decision is that applications in many
1389 * cases need special handling to deal with the case where
1390 * <envar>HOME</envar> is
1392 * <member>Not owned by the user</member>
1393 * <member>Not writeable</member>
1394 * <member>Not even readable</member>
1396 * Since applications are in general <emphasis>not</emphasis> written
1397 * to deal with these situations it was considered better to make
1398 * g_get_home_dir() not pay attention to <envar>HOME</envar> and to
1399 * return the real home directory for the user. If applications
1400 * want to pay attention to <envar>HOME</envar>, they can do:
1402 * const char *homedir = g_getenv ("HOME");
1404 * homedir = g_get_home_dir (<!-- -->);
1407 * Returns: the current user's home directory
1410 g_get_home_dir (void)
1412 g_get_any_init_locked ();
1419 * Gets the directory to use for temporary files. This is found from
1420 * inspecting the environment variables <envar>TMPDIR</envar>,
1421 * <envar>TMP</envar>, and <envar>TEMP</envar> in that order. If none
1422 * of those are defined "/tmp" is returned on UNIX and "C:\" on Windows.
1423 * The encoding of the returned string is system-defined. On Windows,
1424 * it is always UTF-8. The return value is never %NULL or the empty string.
1426 * Returns: the directory to use for temporary files.
1429 g_get_tmp_dir (void)
1431 g_get_any_init_locked ();
1438 * Return a name for the machine.
1440 * The returned name is not necessarily a fully-qualified domain name,
1441 * or even present in DNS or some other name service at all. It need
1442 * not even be unique on your local network or site, but usually it
1443 * is. Callers should not rely on the return value having any specific
1444 * properties like uniqueness for security purposes. Even if the name
1445 * of the machine is changed while an application is running, the
1446 * return value from this function does not change. The returned
1447 * string is owned by GLib and should not be modified or freed. If no
1448 * name can be determined, a default fixed string "localhost" is
1451 * Returns: the host name of the machine.
1456 g_get_host_name (void)
1458 g_get_any_init_locked ();
1462 G_LOCK_DEFINE_STATIC (g_prgname
);
1463 static gchar
*g_prgname
= NULL
;
1468 * Gets the name of the program. This name should <emphasis>not</emphasis>
1469 * be localized, contrast with g_get_application_name().
1470 * (If you are using GDK or GTK+ the program name is set in gdk_init(),
1471 * which is called by gtk_init(). The program name is found by taking
1472 * the last component of <literal>argv[0]</literal>.)
1474 * Returns: the name of the program. The returned string belongs
1475 * to GLib and must not be modified or freed.
1478 g_get_prgname (void)
1484 if (g_prgname
== NULL
)
1486 static gboolean beenhere
= FALSE
;
1490 gchar
*utf8_buf
= NULL
;
1491 wchar_t buf
[MAX_PATH
+1];
1494 if (GetModuleFileNameW (GetModuleHandle (NULL
),
1495 buf
, G_N_ELEMENTS (buf
)) > 0)
1496 utf8_buf
= g_utf16_to_utf8 (buf
, -1, NULL
, NULL
, NULL
);
1500 g_prgname
= g_path_get_basename (utf8_buf
);
1507 G_UNLOCK (g_prgname
);
1514 * @prgname: the name of the program.
1516 * Sets the name of the program. This name should <emphasis>not</emphasis>
1517 * be localized, contrast with g_set_application_name(). Note that for
1518 * thread-safety reasons this function can only be called once.
1521 g_set_prgname (const gchar
*prgname
)
1525 g_prgname
= g_strdup (prgname
);
1526 G_UNLOCK (g_prgname
);
1529 G_LOCK_DEFINE_STATIC (g_application_name
);
1530 static gchar
*g_application_name
= NULL
;
1533 * g_get_application_name:
1535 * Gets a human-readable name for the application, as set by
1536 * g_set_application_name(). This name should be localized if
1537 * possible, and is intended for display to the user. Contrast with
1538 * g_get_prgname(), which gets a non-localized name. If
1539 * g_set_application_name() has not been called, returns the result of
1540 * g_get_prgname() (which may be %NULL if g_set_prgname() has also not
1543 * Return value: human-readable application name. may return %NULL
1548 g_get_application_name (void)
1552 G_LOCK (g_application_name
);
1553 retval
= g_application_name
;
1554 G_UNLOCK (g_application_name
);
1557 return g_get_prgname ();
1563 * g_set_application_name:
1564 * @application_name: localized name of the application
1566 * Sets a human-readable name for the application. This name should be
1567 * localized if possible, and is intended for display to the user.
1568 * Contrast with g_set_prgname(), which sets a non-localized name.
1569 * g_set_prgname() will be called automatically by gtk_init(),
1570 * but g_set_application_name() will not.
1572 * Note that for thread safety reasons, this function can only
1575 * The application name will be used in contexts such as error messages,
1576 * or when displaying an application's name in the task list.
1581 g_set_application_name (const gchar
*application_name
)
1583 gboolean already_set
= FALSE
;
1585 G_LOCK (g_application_name
);
1586 if (g_application_name
)
1589 g_application_name
= g_strdup (application_name
);
1590 G_UNLOCK (g_application_name
);
1593 g_warning ("g_set_application_name() called multiple times");
1597 * g_get_user_data_dir:
1599 * Returns a base directory in which to access application data such
1600 * as icons that is customized for a particular user.
1602 * On UNIX platforms this is determined using the mechanisms described in
1603 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1604 * XDG Base Directory Specification</ulink>.
1605 * In this case the directory retrieved will be XDG_DATA_HOME.
1607 * On Windows this is the folder to use for local (as opposed to
1608 * roaming) application data. See documentation for
1609 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1610 * what g_get_user_config_dir() returns.
1612 * Return value: a string owned by GLib that must not be modified
1617 g_get_user_data_dir (void)
1621 G_LOCK (g_utils_global
);
1623 if (!g_user_data_dir
)
1626 data_dir
= get_special_folder (CSIDL_LOCAL_APPDATA
);
1628 data_dir
= (gchar
*) g_getenv ("XDG_DATA_HOME");
1630 if (data_dir
&& data_dir
[0])
1631 data_dir
= g_strdup (data_dir
);
1633 if (!data_dir
|| !data_dir
[0])
1638 data_dir
= g_build_filename (g_home_dir
, ".local",
1641 data_dir
= g_build_filename (g_tmp_dir
, g_user_name
, ".local",
1645 g_user_data_dir
= data_dir
;
1648 data_dir
= g_user_data_dir
;
1650 G_UNLOCK (g_utils_global
);
1656 g_init_user_config_dir (void)
1660 if (!g_user_config_dir
)
1663 config_dir
= get_special_folder (CSIDL_LOCAL_APPDATA
);
1665 config_dir
= (gchar
*) g_getenv ("XDG_CONFIG_HOME");
1667 if (config_dir
&& config_dir
[0])
1668 config_dir
= g_strdup (config_dir
);
1670 if (!config_dir
|| !config_dir
[0])
1675 config_dir
= g_build_filename (g_home_dir
, ".config", NULL
);
1677 config_dir
= g_build_filename (g_tmp_dir
, g_user_name
, ".config", NULL
);
1680 g_user_config_dir
= config_dir
;
1685 * g_get_user_config_dir:
1687 * Returns a base directory in which to store user-specific application
1688 * configuration information such as user preferences and settings.
1690 * On UNIX platforms this is determined using the mechanisms described in
1691 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1692 * XDG Base Directory Specification</ulink>.
1693 * In this case the directory retrieved will be XDG_CONFIG_HOME.
1695 * On Windows this is the folder to use for local (as opposed to
1696 * roaming) application data. See documentation for
1697 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1698 * what g_get_user_data_dir() returns.
1700 * Return value: a string owned by GLib that must not be modified
1705 g_get_user_config_dir (void)
1707 G_LOCK (g_utils_global
);
1709 g_init_user_config_dir ();
1711 G_UNLOCK (g_utils_global
);
1713 return g_user_config_dir
;
1717 * g_get_user_cache_dir:
1719 * Returns a base directory in which to store non-essential, cached
1720 * data specific to particular user.
1722 * On UNIX platforms this is determined using the mechanisms described in
1723 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1724 * XDG Base Directory Specification</ulink>.
1725 * In this case the directory retrieved will be XDG_CACHE_HOME.
1727 * On Windows is the directory that serves as a common repository for
1728 * temporary Internet files. A typical path is
1729 * C:\Documents and Settings\username\Local Settings\Temporary Internet Files.
1730 * See documentation for CSIDL_INTERNET_CACHE.
1732 * Return value: a string owned by GLib that must not be modified
1737 g_get_user_cache_dir (void)
1741 G_LOCK (g_utils_global
);
1743 if (!g_user_cache_dir
)
1746 cache_dir
= get_special_folder (CSIDL_INTERNET_CACHE
); /* XXX correct? */
1748 cache_dir
= (gchar
*) g_getenv ("XDG_CACHE_HOME");
1750 if (cache_dir
&& cache_dir
[0])
1751 cache_dir
= g_strdup (cache_dir
);
1753 if (!cache_dir
|| !cache_dir
[0])
1758 cache_dir
= g_build_filename (g_home_dir
, ".cache", NULL
);
1760 cache_dir
= g_build_filename (g_tmp_dir
, g_user_name
, ".cache", NULL
);
1762 g_user_cache_dir
= cache_dir
;
1765 cache_dir
= g_user_cache_dir
;
1767 G_UNLOCK (g_utils_global
);
1773 * g_get_user_runtime_dir:
1775 * Returns a directory that is unique to the current user on the local
1778 * On UNIX platforms this is determined using the mechanisms described in
1779 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
1780 * XDG Base Directory Specification</ulink>. This is the directory
1781 * specified in the <envar>XDG_RUNTIME_DIR</envar> environment variable.
1782 * In the case that this variable is not set, GLib will issue a warning
1783 * message to stderr and return the value of g_get_user_cache_dir().
1785 * On Windows this is the folder to use for local (as opposed to
1786 * roaming) application data. See documentation for
1787 * CSIDL_LOCAL_APPDATA. Note that on Windows it thus is the same as
1788 * what g_get_user_config_dir() returns.
1790 * Returns: a string owned by GLib that must not be modified or freed.
1795 g_get_user_runtime_dir (void)
1798 static const gchar
*runtime_dir
;
1799 static gsize initialised
;
1801 if (g_once_init_enter (&initialised
))
1803 runtime_dir
= g_strdup (getenv ("XDG_RUNTIME_DIR"));
1805 g_once_init_leave (&initialised
, 1);
1811 /* Both fallback for UNIX and the default
1812 * in Windows: use the user cache directory.
1816 return g_get_user_cache_dir ();
1822 find_folder (OSType type
)
1824 gchar
*filename
= NULL
;
1827 if (FSFindFolder (kUserDomain
, type
, kDontCreateFolder
, &found
) == noErr
)
1829 CFURLRef url
= CFURLCreateFromFSRef (kCFAllocatorSystemDefault
, &found
);
1833 CFStringRef path
= CFURLCopyFileSystemPath (url
, kCFURLPOSIXPathStyle
);
1837 filename
= g_strdup (CFStringGetCStringPtr (path
, kCFStringEncodingUTF8
));
1841 filename
= g_new0 (gchar
, CFStringGetLength (path
) * 3 + 1);
1843 CFStringGetCString (path
, filename
,
1844 CFStringGetLength (path
) * 3 + 1,
1845 kCFStringEncodingUTF8
);
1859 load_user_special_dirs (void)
1861 g_user_special_dirs
[G_USER_DIRECTORY_DESKTOP
] = find_folder (kDesktopFolderType
);
1862 g_user_special_dirs
[G_USER_DIRECTORY_DOCUMENTS
] = find_folder (kDocumentsFolderType
);
1863 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = find_folder (kDesktopFolderType
); /* XXX correct ? */
1864 g_user_special_dirs
[G_USER_DIRECTORY_MUSIC
] = find_folder (kMusicDocumentsFolderType
);
1865 g_user_special_dirs
[G_USER_DIRECTORY_PICTURES
] = find_folder (kPictureDocumentsFolderType
);
1866 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = NULL
;
1867 g_user_special_dirs
[G_USER_DIRECTORY_TEMPLATES
] = NULL
;
1868 g_user_special_dirs
[G_USER_DIRECTORY_VIDEOS
] = find_folder (kMovieDocumentsFolderType
);
1871 #endif /* HAVE_CARBON */
1873 #if defined(G_OS_WIN32)
1875 load_user_special_dirs (void)
1877 typedef HRESULT (WINAPI
*t_SHGetKnownFolderPath
) (const GUID
*rfid
,
1881 t_SHGetKnownFolderPath p_SHGetKnownFolderPath
;
1883 static const GUID FOLDERID_Downloads
=
1884 { 0x374de290, 0x123f, 0x4565, { 0x91, 0x64, 0x39, 0xc4, 0x92, 0x5e, 0x46, 0x7b } };
1885 static const GUID FOLDERID_Public
=
1886 { 0xDFDF76A2, 0xC82A, 0x4D63, { 0x90, 0x6A, 0x56, 0x44, 0xAC, 0x45, 0x73, 0x85 } };
1890 p_SHGetKnownFolderPath
= (t_SHGetKnownFolderPath
) GetProcAddress (GetModuleHandle ("shell32.dll"),
1891 "SHGetKnownFolderPath");
1893 g_user_special_dirs
[G_USER_DIRECTORY_DESKTOP
] = get_special_folder (CSIDL_DESKTOPDIRECTORY
);
1894 g_user_special_dirs
[G_USER_DIRECTORY_DOCUMENTS
] = get_special_folder (CSIDL_PERSONAL
);
1896 if (p_SHGetKnownFolderPath
== NULL
)
1898 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = get_special_folder (CSIDL_DESKTOPDIRECTORY
);
1903 (*p_SHGetKnownFolderPath
) (&FOLDERID_Downloads
, 0, NULL
, &wcp
);
1906 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = g_utf16_to_utf8 (wcp
, -1, NULL
, NULL
, NULL
);
1907 if (g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] == NULL
)
1908 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = get_special_folder (CSIDL_DESKTOPDIRECTORY
);
1909 CoTaskMemFree (wcp
);
1912 g_user_special_dirs
[G_USER_DIRECTORY_DOWNLOAD
] = get_special_folder (CSIDL_DESKTOPDIRECTORY
);
1915 g_user_special_dirs
[G_USER_DIRECTORY_MUSIC
] = get_special_folder (CSIDL_MYMUSIC
);
1916 g_user_special_dirs
[G_USER_DIRECTORY_PICTURES
] = get_special_folder (CSIDL_MYPICTURES
);
1918 if (p_SHGetKnownFolderPath
== NULL
)
1921 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = get_special_folder (CSIDL_COMMON_DOCUMENTS
);
1926 (*p_SHGetKnownFolderPath
) (&FOLDERID_Public
, 0, NULL
, &wcp
);
1929 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = g_utf16_to_utf8 (wcp
, -1, NULL
, NULL
, NULL
);
1930 if (g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] == NULL
)
1931 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = get_special_folder (CSIDL_COMMON_DOCUMENTS
);
1932 CoTaskMemFree (wcp
);
1935 g_user_special_dirs
[G_USER_DIRECTORY_PUBLIC_SHARE
] = get_special_folder (CSIDL_COMMON_DOCUMENTS
);
1938 g_user_special_dirs
[G_USER_DIRECTORY_TEMPLATES
] = get_special_folder (CSIDL_TEMPLATES
);
1939 g_user_special_dirs
[G_USER_DIRECTORY_VIDEOS
] = get_special_folder (CSIDL_MYVIDEO
);
1941 #endif /* G_OS_WIN32 */
1943 static void g_init_user_config_dir (void);
1945 #if defined(G_OS_UNIX) && !defined(HAVE_CARBON)
1947 /* adapted from xdg-user-dir-lookup.c
1949 * Copyright (C) 2007 Red Hat Inc.
1951 * Permission is hereby granted, free of charge, to any person
1952 * obtaining a copy of this software and associated documentation files
1953 * (the "Software"), to deal in the Software without restriction,
1954 * including without limitation the rights to use, copy, modify, merge,
1955 * publish, distribute, sublicense, and/or sell copies of the Software,
1956 * and to permit persons to whom the Software is furnished to do so,
1957 * subject to the following conditions:
1959 * The above copyright notice and this permission notice shall be
1960 * included in all copies or substantial portions of the Software.
1962 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1963 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
1964 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1965 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
1966 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
1967 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1968 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1972 load_user_special_dirs (void)
1979 g_init_user_config_dir ();
1980 config_file
= g_build_filename (g_user_config_dir
,
1984 if (!g_file_get_contents (config_file
, &data
, NULL
, NULL
))
1986 g_free (config_file
);
1990 lines
= g_strsplit (data
, "\n", -1);
1991 n_lines
= g_strv_length (lines
);
1994 for (i
= 0; i
< n_lines
; i
++)
1996 gchar
*buffer
= lines
[i
];
1999 gboolean is_relative
= FALSE
;
2000 GUserDirectory directory
;
2002 /* Remove newline at end */
2003 len
= strlen (buffer
);
2004 if (len
> 0 && buffer
[len
- 1] == '\n')
2005 buffer
[len
- 1] = 0;
2008 while (*p
== ' ' || *p
== '\t')
2011 if (strncmp (p
, "XDG_DESKTOP_DIR", strlen ("XDG_DESKTOP_DIR")) == 0)
2013 directory
= G_USER_DIRECTORY_DESKTOP
;
2014 p
+= strlen ("XDG_DESKTOP_DIR");
2016 else if (strncmp (p
, "XDG_DOCUMENTS_DIR", strlen ("XDG_DOCUMENTS_DIR")) == 0)
2018 directory
= G_USER_DIRECTORY_DOCUMENTS
;
2019 p
+= strlen ("XDG_DOCUMENTS_DIR");
2021 else if (strncmp (p
, "XDG_DOWNLOAD_DIR", strlen ("XDG_DOWNLOAD_DIR")) == 0)
2023 directory
= G_USER_DIRECTORY_DOWNLOAD
;
2024 p
+= strlen ("XDG_DOWNLOAD_DIR");
2026 else if (strncmp (p
, "XDG_MUSIC_DIR", strlen ("XDG_MUSIC_DIR")) == 0)
2028 directory
= G_USER_DIRECTORY_MUSIC
;
2029 p
+= strlen ("XDG_MUSIC_DIR");
2031 else if (strncmp (p
, "XDG_PICTURES_DIR", strlen ("XDG_PICTURES_DIR")) == 0)
2033 directory
= G_USER_DIRECTORY_PICTURES
;
2034 p
+= strlen ("XDG_PICTURES_DIR");
2036 else if (strncmp (p
, "XDG_PUBLICSHARE_DIR", strlen ("XDG_PUBLICSHARE_DIR")) == 0)
2038 directory
= G_USER_DIRECTORY_PUBLIC_SHARE
;
2039 p
+= strlen ("XDG_PUBLICSHARE_DIR");
2041 else if (strncmp (p
, "XDG_TEMPLATES_DIR", strlen ("XDG_TEMPLATES_DIR")) == 0)
2043 directory
= G_USER_DIRECTORY_TEMPLATES
;
2044 p
+= strlen ("XDG_TEMPLATES_DIR");
2046 else if (strncmp (p
, "XDG_VIDEOS_DIR", strlen ("XDG_VIDEOS_DIR")) == 0)
2048 directory
= G_USER_DIRECTORY_VIDEOS
;
2049 p
+= strlen ("XDG_VIDEOS_DIR");
2054 while (*p
== ' ' || *p
== '\t')
2061 while (*p
== ' ' || *p
== '\t')
2068 if (strncmp (p
, "$HOME", 5) == 0)
2076 d
= strrchr (p
, '"');
2083 /* remove trailing slashes */
2085 if (d
[len
- 1] == '/')
2091 g_user_special_dirs
[directory
] = g_build_filename (g_home_dir
, d
, NULL
);
2094 g_user_special_dirs
[directory
] = g_strdup (d
);
2098 g_free (config_file
);
2101 #endif /* G_OS_UNIX && !HAVE_CARBON */
2105 * g_reload_user_special_dirs_cache:
2107 * Resets the cache used for g_get_user_special_dir(), so
2108 * that the latest on-disk version is used. Call this only
2109 * if you just changed the data on disk yourself.
2111 * Due to threadsafety issues this may cause leaking of strings
2112 * that were previously returned from g_get_user_special_dir()
2113 * that can't be freed. We ensure to only leak the data for
2114 * the directories that actually changed value though.
2119 g_reload_user_special_dirs_cache (void)
2123 G_LOCK (g_utils_global
);
2125 if (g_user_special_dirs
!= NULL
)
2127 /* save a copy of the pointer, to check if some memory can be preserved */
2128 char **old_g_user_special_dirs
= g_user_special_dirs
;
2131 /* recreate and reload our cache */
2132 g_user_special_dirs
= g_new0 (gchar
*, G_USER_N_DIRECTORIES
);
2133 load_user_special_dirs ();
2135 /* only leak changed directories */
2136 for (i
= 0; i
< G_USER_N_DIRECTORIES
; i
++)
2138 old_val
= old_g_user_special_dirs
[i
];
2139 if (g_strcmp0 (old_val
, g_user_special_dirs
[i
]) == 0)
2142 g_free (g_user_special_dirs
[i
]);
2143 g_user_special_dirs
[i
] = old_val
;
2149 /* free the old array */
2150 g_free (old_g_user_special_dirs
);
2153 G_UNLOCK (g_utils_global
);
2157 * g_get_user_special_dir:
2158 * @directory: the logical id of special directory
2160 * Returns the full path of a special directory using its logical id.
2162 * On Unix this is done using the XDG special user directories.
2163 * For compatibility with existing practise, %G_USER_DIRECTORY_DESKTOP
2164 * falls back to <filename>$HOME/Desktop</filename> when XDG special
2165 * user directories have not been set up.
2167 * Depending on the platform, the user might be able to change the path
2168 * of the special directory without requiring the session to restart; GLib
2169 * will not reflect any change once the special directories are loaded.
2171 * Return value: the path to the specified special directory, or %NULL
2172 * if the logical id was not found. The returned string is owned by
2173 * GLib and should not be modified or freed.
2178 g_get_user_special_dir (GUserDirectory directory
)
2180 g_return_val_if_fail (directory
>= G_USER_DIRECTORY_DESKTOP
&&
2181 directory
< G_USER_N_DIRECTORIES
, NULL
);
2183 G_LOCK (g_utils_global
);
2185 if (G_UNLIKELY (g_user_special_dirs
== NULL
))
2187 g_user_special_dirs
= g_new0 (gchar
*, G_USER_N_DIRECTORIES
);
2189 load_user_special_dirs ();
2191 /* Special-case desktop for historical compatibility */
2192 if (g_user_special_dirs
[G_USER_DIRECTORY_DESKTOP
] == NULL
)
2196 g_user_special_dirs
[G_USER_DIRECTORY_DESKTOP
] =
2197 g_build_filename (g_home_dir
, "Desktop", NULL
);
2201 G_UNLOCK (g_utils_global
);
2203 return g_user_special_dirs
[directory
];
2208 #undef g_get_system_data_dirs
2211 get_module_for_address (gconstpointer address
)
2213 /* Holds the g_utils_global lock */
2215 static gboolean beenhere
= FALSE
;
2216 typedef BOOL (WINAPI
*t_GetModuleHandleExA
) (DWORD
, LPCTSTR
, HMODULE
*);
2217 static t_GetModuleHandleExA p_GetModuleHandleExA
= NULL
;
2218 HMODULE hmodule
= NULL
;
2225 p_GetModuleHandleExA
=
2226 (t_GetModuleHandleExA
) GetProcAddress (GetModuleHandle ("kernel32.dll"),
2227 "GetModuleHandleExA");
2231 if (p_GetModuleHandleExA
== NULL
||
2232 !(*p_GetModuleHandleExA
) (GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
|
2233 GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
,
2236 MEMORY_BASIC_INFORMATION mbi
;
2237 VirtualQuery (address
, &mbi
, sizeof (mbi
));
2238 hmodule
= (HMODULE
) mbi
.AllocationBase
;
2245 get_module_share_dir (gconstpointer address
)
2251 hmodule
= get_module_for_address (address
);
2252 if (hmodule
== NULL
)
2255 filename
= g_win32_get_package_installation_directory_of_module (hmodule
);
2256 retval
= g_build_filename (filename
, "share", NULL
);
2262 const gchar
* const *
2263 g_win32_get_system_data_dirs_for_module (void (*address_of_function
)())
2267 static GHashTable
*per_module_data_dirs
= NULL
;
2272 if (address_of_function
)
2274 G_LOCK (g_utils_global
);
2275 hmodule
= get_module_for_address (address_of_function
);
2276 if (hmodule
!= NULL
)
2278 if (per_module_data_dirs
== NULL
)
2279 per_module_data_dirs
= g_hash_table_new (NULL
, NULL
);
2282 retval
= g_hash_table_lookup (per_module_data_dirs
, hmodule
);
2286 G_UNLOCK (g_utils_global
);
2287 return (const gchar
* const *) retval
;
2293 data_dirs
= g_array_new (TRUE
, TRUE
, sizeof (char *));
2295 /* Documents and Settings\All Users\Application Data */
2296 p
= get_special_folder (CSIDL_COMMON_APPDATA
);
2298 g_array_append_val (data_dirs
, p
);
2300 /* Documents and Settings\All Users\Documents */
2301 p
= get_special_folder (CSIDL_COMMON_DOCUMENTS
);
2303 g_array_append_val (data_dirs
, p
);
2305 /* Using the above subfolders of Documents and Settings perhaps
2306 * makes sense from a Windows perspective.
2308 * But looking at the actual use cases of this function in GTK+
2309 * and GNOME software, what we really want is the "share"
2310 * subdirectory of the installation directory for the package
2311 * our caller is a part of.
2313 * The address_of_function parameter, if non-NULL, points to a
2314 * function in the calling module. Use that to determine that
2315 * module's installation folder, and use its "share" subfolder.
2317 * Additionally, also use the "share" subfolder of the installation
2318 * locations of GLib and the .exe file being run.
2320 * To guard against none of the above being what is really wanted,
2321 * callers of this function should have Win32-specific code to look
2322 * up their installation folder themselves, and handle a subfolder
2323 * "share" of it in the same way as the folders returned from this
2327 p
= get_module_share_dir (address_of_function
);
2329 g_array_append_val (data_dirs
, p
);
2331 if (glib_dll
!= NULL
)
2333 gchar
*glib_root
= g_win32_get_package_installation_directory_of_module (glib_dll
);
2334 p
= g_build_filename (glib_root
, "share", NULL
);
2336 g_array_append_val (data_dirs
, p
);
2340 exe_root
= g_win32_get_package_installation_directory_of_module (NULL
);
2341 p
= g_build_filename (exe_root
, "share", NULL
);
2343 g_array_append_val (data_dirs
, p
);
2346 retval
= (gchar
**) g_array_free (data_dirs
, FALSE
);
2348 if (address_of_function
)
2350 if (hmodule
!= NULL
)
2351 g_hash_table_insert (per_module_data_dirs
, hmodule
, retval
);
2352 G_UNLOCK (g_utils_global
);
2355 return (const gchar
* const *) retval
;
2361 * g_get_system_data_dirs:
2363 * Returns an ordered list of base directories in which to access
2364 * system-wide application data.
2366 * On UNIX platforms this is determined using the mechanisms described in
2367 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2368 * XDG Base Directory Specification</ulink>
2369 * In this case the list of directories retrieved will be XDG_DATA_DIRS.
2371 * On Windows the first elements in the list are the Application Data
2372 * and Documents folders for All Users. (These can be determined only
2373 * on Windows 2000 or later and are not present in the list on other
2374 * Windows versions.) See documentation for CSIDL_COMMON_APPDATA and
2375 * CSIDL_COMMON_DOCUMENTS.
2377 * Then follows the "share" subfolder in the installation folder for
2378 * the package containing the DLL that calls this function, if it can
2381 * Finally the list contains the "share" subfolder in the installation
2382 * folder for GLib, and in the installation folder for the package the
2383 * application's .exe file belongs to.
2385 * The installation folders above are determined by looking up the
2386 * folder where the module (DLL or EXE) in question is located. If the
2387 * folder's name is "bin", its parent is used, otherwise the folder
2390 * Note that on Windows the returned list can vary depending on where
2391 * this function is called.
2393 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2394 * not be modified or freed.
2397 const gchar
* const *
2398 g_get_system_data_dirs (void)
2400 gchar
**data_dir_vector
;
2402 G_LOCK (g_utils_global
);
2404 if (!g_system_data_dirs
)
2407 data_dir_vector
= (gchar
**) g_win32_get_system_data_dirs_for_module (NULL
);
2409 gchar
*data_dirs
= (gchar
*) g_getenv ("XDG_DATA_DIRS");
2411 if (!data_dirs
|| !data_dirs
[0])
2412 data_dirs
= "/usr/local/share/:/usr/share/";
2414 data_dir_vector
= g_strsplit (data_dirs
, G_SEARCHPATH_SEPARATOR_S
, 0);
2417 g_system_data_dirs
= data_dir_vector
;
2420 data_dir_vector
= g_system_data_dirs
;
2422 G_UNLOCK (g_utils_global
);
2424 return (const gchar
* const *) data_dir_vector
;
2428 * g_get_system_config_dirs:
2430 * Returns an ordered list of base directories in which to access
2431 * system-wide configuration information.
2433 * On UNIX platforms this is determined using the mechanisms described in
2434 * the <ulink url="http://www.freedesktop.org/Standards/basedir-spec">
2435 * XDG Base Directory Specification</ulink>.
2436 * In this case the list of directories retrieved will be XDG_CONFIG_DIRS.
2438 * On Windows is the directory that contains application data for all users.
2439 * A typical path is C:\Documents and Settings\All Users\Application Data.
2440 * This folder is used for application data that is not user specific.
2441 * For example, an application can store a spell-check dictionary, a database
2442 * of clip art, or a log file in the CSIDL_COMMON_APPDATA folder.
2443 * This information will not roam and is available to anyone using the computer.
2445 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib that must
2446 * not be modified or freed.
2449 const gchar
* const *
2450 g_get_system_config_dirs (void)
2452 gchar
*conf_dirs
, **conf_dir_vector
;
2454 G_LOCK (g_utils_global
);
2456 if (!g_system_config_dirs
)
2459 conf_dirs
= get_special_folder (CSIDL_COMMON_APPDATA
);
2462 conf_dir_vector
= g_strsplit (conf_dirs
, G_SEARCHPATH_SEPARATOR_S
, 0);
2467 /* Return empty list */
2468 conf_dir_vector
= g_strsplit ("", G_SEARCHPATH_SEPARATOR_S
, 0);
2471 conf_dirs
= (gchar
*) g_getenv ("XDG_CONFIG_DIRS");
2473 if (!conf_dirs
|| !conf_dirs
[0])
2474 conf_dirs
= "/etc/xdg";
2476 conf_dir_vector
= g_strsplit (conf_dirs
, G_SEARCHPATH_SEPARATOR_S
, 0);
2479 g_system_config_dirs
= conf_dir_vector
;
2482 conf_dir_vector
= g_system_config_dirs
;
2483 G_UNLOCK (g_utils_global
);
2485 return (const gchar
* const *) conf_dir_vector
;
2490 static GHashTable
*alias_table
= NULL
;
2492 /* read an alias file for the locales */
2494 read_aliases (gchar
*file
)
2500 alias_table
= g_hash_table_new (g_str_hash
, g_str_equal
);
2501 fp
= fopen (file
,"r");
2504 while (fgets (buf
, 256, fp
))
2510 /* Line is a comment */
2511 if ((buf
[0] == '#') || (buf
[0] == '\0'))
2514 /* Reads first column */
2515 for (p
= buf
, q
= NULL
; *p
; p
++) {
2516 if ((*p
== '\t') || (*p
== ' ') || (*p
== ':')) {
2519 while ((*q
== '\t') || (*q
== ' ')) {
2525 /* The line only had one column */
2526 if (!q
|| *q
== '\0')
2529 /* Read second column */
2530 for (p
= q
; *p
; p
++) {
2531 if ((*p
== '\t') || (*p
== ' ')) {
2537 /* Add to alias table if necessary */
2538 if (!g_hash_table_lookup (alias_table
, buf
)) {
2539 g_hash_table_insert (alias_table
, g_strdup (buf
), g_strdup (q
));
2548 unalias_lang (char *lang
)
2555 read_aliases ("/usr/share/locale/locale.alias");
2558 while ((p
= g_hash_table_lookup (alias_table
, lang
)) && (strcmp (p
, lang
) != 0))
2563 static gboolean said_before
= FALSE
;
2565 g_warning ("Too many alias levels for a locale, "
2566 "may indicate a loop");
2575 /* Mask for components of locale spec. The ordering here is from
2576 * least significant to most significant
2580 COMPONENT_CODESET
= 1 << 0,
2581 COMPONENT_TERRITORY
= 1 << 1,
2582 COMPONENT_MODIFIER
= 1 << 2
2585 /* Break an X/Open style locale specification into components
2588 explode_locale (const gchar
*locale
,
2594 const gchar
*uscore_pos
;
2595 const gchar
*at_pos
;
2596 const gchar
*dot_pos
;
2600 uscore_pos
= strchr (locale
, '_');
2601 dot_pos
= strchr (uscore_pos
? uscore_pos
: locale
, '.');
2602 at_pos
= strchr (dot_pos
? dot_pos
: (uscore_pos
? uscore_pos
: locale
), '@');
2606 mask
|= COMPONENT_MODIFIER
;
2607 *modifier
= g_strdup (at_pos
);
2610 at_pos
= locale
+ strlen (locale
);
2614 mask
|= COMPONENT_CODESET
;
2615 *codeset
= g_strndup (dot_pos
, at_pos
- dot_pos
);
2622 mask
|= COMPONENT_TERRITORY
;
2623 *territory
= g_strndup (uscore_pos
, dot_pos
- uscore_pos
);
2626 uscore_pos
= dot_pos
;
2628 *language
= g_strndup (locale
, uscore_pos
- locale
);
2634 * Compute all interesting variants for a given locale name -
2635 * by stripping off different components of the value.
2637 * For simplicity, we assume that the locale is in
2638 * X/Open format: language[_territory][.codeset][@modifier]
2640 * TODO: Extend this to handle the CEN format (see the GNUlibc docs)
2641 * as well. We could just copy the code from glibc wholesale
2642 * but it is big, ugly, and complicated, so I'm reluctant
2643 * to do so when this should handle 99% of the time...
2646 append_locale_variants (GPtrArray
*array
,
2647 const gchar
*locale
)
2649 gchar
*language
= NULL
;
2650 gchar
*territory
= NULL
;
2651 gchar
*codeset
= NULL
;
2652 gchar
*modifier
= NULL
;
2657 g_return_if_fail (locale
!= NULL
);
2659 mask
= explode_locale (locale
, &language
, &territory
, &codeset
, &modifier
);
2661 /* Iterate through all possible combinations, from least attractive
2662 * to most attractive.
2664 for (j
= 0; j
<= mask
; ++j
)
2668 if ((i
& ~mask
) == 0)
2670 gchar
*val
= g_strconcat (language
,
2671 (i
& COMPONENT_TERRITORY
) ? territory
: "",
2672 (i
& COMPONENT_CODESET
) ? codeset
: "",
2673 (i
& COMPONENT_MODIFIER
) ? modifier
: "",
2675 g_ptr_array_add (array
, val
);
2680 if (mask
& COMPONENT_CODESET
)
2682 if (mask
& COMPONENT_TERRITORY
)
2684 if (mask
& COMPONENT_MODIFIER
)
2689 * g_get_locale_variants:
2690 * @locale: a locale identifier
2692 * Returns a list of derived variants of @locale, which can be used to
2693 * e.g. construct locale-dependent filenames or search paths. The returned
2694 * list is sorted from most desirable to least desirable.
2695 * This function handles territory, charset and extra locale modifiers.
2697 * For example, if @locale is "fr_BE", then the returned list
2700 * If you need the list of variants for the <emphasis>current locale</emphasis>,
2701 * use g_get_language_names().
2703 * Returns: (transfer full) (array zero-terminated=1) (element-type utf8): a newly
2704 * allocated array of newly allocated strings with the locale variants. Free with
2710 g_get_locale_variants (const gchar
*locale
)
2714 g_return_val_if_fail (locale
!= NULL
, NULL
);
2716 array
= g_ptr_array_sized_new (8);
2717 append_locale_variants (array
, locale
);
2718 g_ptr_array_add (array
, NULL
);
2720 return (gchar
**) g_ptr_array_free (array
, FALSE
);
2723 /* The following is (partly) taken from the gettext package.
2724 Copyright (C) 1995, 1996, 1997, 1998 Free Software Foundation, Inc. */
2726 static const gchar
*
2727 guess_category_value (const gchar
*category_name
)
2729 const gchar
*retval
;
2731 /* The highest priority value is the `LANGUAGE' environment
2732 variable. This is a GNU extension. */
2733 retval
= g_getenv ("LANGUAGE");
2734 if ((retval
!= NULL
) && (retval
[0] != '\0'))
2737 /* `LANGUAGE' is not set. So we have to proceed with the POSIX
2738 methods of looking to `LC_ALL', `LC_xxx', and `LANG'. On some
2739 systems this can be done by the `setlocale' function itself. */
2741 /* Setting of LC_ALL overwrites all other. */
2742 retval
= g_getenv ("LC_ALL");
2743 if ((retval
!= NULL
) && (retval
[0] != '\0'))
2746 /* Next comes the name of the desired category. */
2747 retval
= g_getenv (category_name
);
2748 if ((retval
!= NULL
) && (retval
[0] != '\0'))
2751 /* Last possibility is the LANG environment variable. */
2752 retval
= g_getenv ("LANG");
2753 if ((retval
!= NULL
) && (retval
[0] != '\0'))
2756 #ifdef G_PLATFORM_WIN32
2757 /* g_win32_getlocale() first checks for LC_ALL, LC_MESSAGES and
2758 * LANG, which we already did above. Oh well. The main point of
2759 * calling g_win32_getlocale() is to get the thread's locale as used
2760 * by Windows and the Microsoft C runtime (in the "English_United
2761 * States" format) translated into the Unixish format.
2764 char *locale
= g_win32_getlocale ();
2765 retval
= g_intern_string (locale
);
2774 typedef struct _GLanguageNamesCache GLanguageNamesCache
;
2776 struct _GLanguageNamesCache
{
2778 gchar
**language_names
;
2782 language_names_cache_free (gpointer data
)
2784 GLanguageNamesCache
*cache
= data
;
2785 g_free (cache
->languages
);
2786 g_strfreev (cache
->language_names
);
2791 * g_get_language_names:
2793 * Computes a list of applicable locale names, which can be used to
2794 * e.g. construct locale-dependent filenames or search paths. The returned
2795 * list is sorted from most desirable to least desirable and always contains
2796 * the default locale "C".
2798 * For example, if LANGUAGE=de:en_US, then the returned list is
2799 * "de", "en_US", "en", "C".
2801 * This function consults the environment variables <envar>LANGUAGE</envar>,
2802 * <envar>LC_ALL</envar>, <envar>LC_MESSAGES</envar> and <envar>LANG</envar>
2803 * to find the list of locales specified by the user.
2805 * Return value: (array zero-terminated=1) (transfer none): a %NULL-terminated array of strings owned by GLib
2806 * that must not be modified or freed.
2810 const gchar
* const *
2811 g_get_language_names (void)
2813 static GPrivate cache_private
= G_PRIVATE_INIT (language_names_cache_free
);
2814 GLanguageNamesCache
*cache
= g_private_get (&cache_private
);
2819 cache
= g_new0 (GLanguageNamesCache
, 1);
2820 g_private_set (&cache_private
, cache
);
2823 value
= guess_category_value ("LC_MESSAGES");
2827 if (!(cache
->languages
&& strcmp (cache
->languages
, value
) == 0))
2832 g_free (cache
->languages
);
2833 g_strfreev (cache
->language_names
);
2834 cache
->languages
= g_strdup (value
);
2836 array
= g_ptr_array_sized_new (8);
2838 alist
= g_strsplit (value
, ":", 0);
2839 for (a
= alist
; *a
; a
++)
2840 append_locale_variants (array
, unalias_lang (*a
));
2842 g_ptr_array_add (array
, g_strdup ("C"));
2843 g_ptr_array_add (array
, NULL
);
2845 cache
->language_names
= (gchar
**) g_ptr_array_free (array
, FALSE
);
2848 return (const gchar
* const *) cache
->language_names
;
2852 * g_nullify_pointer:
2853 * @nullify_location: the memory address of the pointer.
2855 * Set the pointer at the specified location to %NULL.
2858 g_nullify_pointer (gpointer
*nullify_location
)
2860 g_return_if_fail (nullify_location
!= NULL
);
2862 *nullify_location
= NULL
;
2868 * _glib_get_locale_dir:
2870 * Return the path to the share\locale or lib\locale subfolder of the
2871 * GLib installation folder. The path is in the system codepage. We
2872 * have to use system codepage as bindtextdomain() doesn't have a
2876 _glib_get_locale_dir (void)
2878 gchar
*install_dir
= NULL
, *locale_dir
;
2879 gchar
*retval
= NULL
;
2881 if (glib_dll
!= NULL
)
2882 install_dir
= g_win32_get_package_installation_directory_of_module (glib_dll
);
2887 * Append "/share/locale" or "/lib/locale" depending on whether
2888 * autoconfigury detected GNU gettext or not.
2890 const char *p
= GLIB_LOCALE_DIR
+ strlen (GLIB_LOCALE_DIR
);
2896 locale_dir
= g_build_filename (install_dir
, p
, NULL
);
2898 retval
= g_win32_locale_filename_from_utf8 (locale_dir
);
2900 g_free (install_dir
);
2901 g_free (locale_dir
);
2907 return g_strdup ("");
2910 #undef GLIB_LOCALE_DIR
2912 #endif /* G_OS_WIN32 */
2915 ensure_gettext_initialized (void)
2917 static gsize initialised
;
2919 if (g_once_init_enter (&initialised
))
2922 gchar
*tmp
= _glib_get_locale_dir ();
2923 bindtextdomain (GETTEXT_PACKAGE
, tmp
);
2926 bindtextdomain (GETTEXT_PACKAGE
, GLIB_LOCALE_DIR
);
2928 # ifdef HAVE_BIND_TEXTDOMAIN_CODESET
2929 bind_textdomain_codeset (GETTEXT_PACKAGE
, "UTF-8");
2931 g_once_init_leave (&initialised
, TRUE
);
2937 * @str: The string to be translated
2939 * Returns the translated string from the glib translations.
2940 * This is an internal function and should only be used by
2941 * the internals of glib (such as libgio).
2943 * Returns: the transation of @str to the current locale
2946 glib_gettext (const gchar
*str
)
2948 ensure_gettext_initialized();
2950 return g_dgettext (GETTEXT_PACKAGE
, str
);
2955 * @msgctxtid: a combined message context and message id, separated
2956 * by a \004 character
2957 * @msgidoffset: the offset of the message id in @msgctxid
2959 * This function is a variant of glib_gettext() which supports
2960 * a disambiguating message context. See g_dpgettext() for full
2963 * This is an internal function and should only be used by
2964 * the internals of glib (such as libgio).
2966 * Returns: the transation of @str to the current locale
2969 glib_pgettext(const gchar
*msgctxtid
,
2972 ensure_gettext_initialized();
2974 return g_dpgettext (GETTEXT_PACKAGE
, msgctxtid
, msgidoffset
);
2977 #if defined (G_OS_WIN32) && !defined (_WIN64)
2979 /* Binary compatibility versions. Not for newly compiled code. */
2981 #undef g_find_program_in_path
2984 g_find_program_in_path (const gchar
*program
)
2986 gchar
*utf8_program
= g_locale_to_utf8 (program
, -1, NULL
, NULL
, NULL
);
2987 gchar
*utf8_retval
= g_find_program_in_path_utf8 (utf8_program
);
2990 g_free (utf8_program
);
2991 if (utf8_retval
== NULL
)
2993 retval
= g_locale_from_utf8 (utf8_retval
, -1, NULL
, NULL
, NULL
);
2994 g_free (utf8_retval
);
2999 #undef g_get_current_dir
3002 g_get_current_dir (void)
3004 gchar
*utf8_dir
= g_get_current_dir_utf8 ();
3005 gchar
*dir
= g_locale_from_utf8 (utf8_dir
, -1, NULL
, NULL
, NULL
);
3013 g_getenv (const gchar
*variable
)
3015 gchar
*utf8_variable
= g_locale_to_utf8 (variable
, -1, NULL
, NULL
, NULL
);
3016 const gchar
*utf8_value
= g_getenv_utf8 (utf8_variable
);
3020 g_free (utf8_variable
);
3023 value
= g_locale_from_utf8 (utf8_value
, -1, NULL
, NULL
, NULL
);
3024 quark
= g_quark_from_string (value
);
3027 return g_quark_to_string (quark
);
3033 g_setenv (const gchar
*variable
,
3037 gchar
*utf8_variable
= g_locale_to_utf8 (variable
, -1, NULL
, NULL
, NULL
);
3038 gchar
*utf8_value
= g_locale_to_utf8 (value
, -1, NULL
, NULL
, NULL
);
3039 gboolean retval
= g_setenv_utf8 (utf8_variable
, utf8_value
, overwrite
);
3041 g_free (utf8_variable
);
3042 g_free (utf8_value
);
3050 g_unsetenv (const gchar
*variable
)
3052 gchar
*utf8_variable
= g_locale_to_utf8 (variable
, -1, NULL
, NULL
, NULL
);
3054 g_unsetenv_utf8 (utf8_variable
);
3056 g_free (utf8_variable
);
3059 #undef g_get_user_name
3062 g_get_user_name (void)
3064 g_get_any_init_locked ();
3065 return g_user_name_cp
;
3068 #undef g_get_real_name
3071 g_get_real_name (void)
3073 g_get_any_init_locked ();
3074 return g_real_name_cp
;
3077 #undef g_get_home_dir
3080 g_get_home_dir (void)
3082 g_get_any_init_locked ();
3083 return g_home_dir_cp
;
3086 #undef g_get_tmp_dir
3089 g_get_tmp_dir (void)
3091 g_get_any_init_locked ();
3092 return g_tmp_dir_cp
;