Skip to main content

glib/auto/
functions.rs

1// This file was generated by gir (https://github.com/gtk-rs/gir)
2// from gir-files (https://github.com/gtk-rs/gir-files)
3// DO NOT EDIT
4
5#[cfg(feature = "v2_66")]
6#[cfg_attr(docsrs, doc(cfg(feature = "v2_66")))]
7use crate::FileSetContentsFlags;
8use crate::{
9    Bytes, ChecksumType, Error, FileTest, FormatSizeFlags, Pid, Source, SpawnFlags, UserDirectory,
10    ffi, translate::*,
11};
12use std::boxed::Box as Box_;
13
14/// A wrapper for the POSIX access() function. This function is used to
15/// test a pathname for one or several of read, write or execute
16/// permissions, or just existence.
17///
18/// On Windows, the file protection mechanism is not at all POSIX-like,
19/// and the underlying function in the C library only checks the
20/// FAT-style READONLY attribute, and does not look at the ACL of a
21/// file at all. This function is this in practise almost useless on
22/// Windows. Software that needs to handle file permissions on Windows
23/// more exactly should use the Win32 API.
24///
25/// See your C library manual for more details about access().
26/// ## `filename`
27/// a pathname in the GLib file name encoding
28///     (UTF-8 on Windows)
29/// ## `mode`
30/// as in access()
31///
32/// # Returns
33///
34/// zero if the pathname refers to an existing file system
35///     object that has all the tested permissions, or -1 otherwise
36///     or on error.
37#[doc(alias = "g_access")]
38pub fn access(filename: impl AsRef<std::path::Path>, mode: i32) -> i32 {
39    unsafe { ffi::g_access(filename.as_ref().to_glib_none().0, mode) }
40}
41
42/// Decode a sequence of Base-64 encoded text into binary data.  Note
43/// that the returned binary data is not necessarily zero-terminated,
44/// so it should not be used as a character string.
45/// ## `text`
46/// zero-terminated string with base64 text to decode
47///
48/// # Returns
49///
50///
51///               newly allocated buffer containing the binary data
52///               that @text represents. The returned buffer must
53///               be freed with g_free().
54#[doc(alias = "g_base64_decode")]
55pub fn base64_decode(text: &str) -> Vec<u8> {
56    unsafe {
57        let mut out_len = std::mem::MaybeUninit::uninit();
58        let ret = FromGlibContainer::from_glib_full_num(
59            ffi::g_base64_decode(text.to_glib_none().0, out_len.as_mut_ptr()),
60            out_len.assume_init() as _,
61        );
62        ret
63    }
64}
65
66//#[doc(alias = "g_base64_decode_inplace")]
67//pub fn base64_decode_inplace(text: /*Unimplemented*/Vec<u8>) -> u8 {
68//    unsafe { TODO: call ffi:g_base64_decode_inplace() }
69//}
70
71//#[doc(alias = "g_base64_decode_step")]
72//pub fn base64_decode_step(in_: &[&str], out: Vec<u8>, state: &mut i32, save: &mut u32) -> usize {
73//    unsafe { TODO: call ffi:g_base64_decode_step() }
74//}
75
76/// Encode a sequence of binary data into its Base-64 stringified
77/// representation.
78/// ## `data`
79/// the binary data to encode
80///
81/// # Returns
82///
83/// a newly allocated, zero-terminated Base-64
84///               encoded string representing @data. The returned string must
85///               be freed with g_free().
86#[doc(alias = "g_base64_encode")]
87pub fn base64_encode(data: &[u8]) -> crate::GString {
88    let len = data.len() as _;
89    unsafe { from_glib_full(ffi::g_base64_encode(data.to_glib_none().0, len)) }
90}
91
92//#[doc(alias = "g_base64_encode_close")]
93//pub fn base64_encode_close(break_lines: bool, out: Vec<u8>, state: &mut i32, save: &mut i32) -> usize {
94//    unsafe { TODO: call ffi:g_base64_encode_close() }
95//}
96
97//#[doc(alias = "g_base64_encode_step")]
98//pub fn base64_encode_step(in_: &[u8], break_lines: bool, out: Vec<u8>, state: &mut i32, save: &mut i32) -> usize {
99//    unsafe { TODO: call ffi:g_base64_encode_step() }
100//}
101
102/// Checks that the GLib library in use is compatible with the
103/// given version.
104///
105/// Generally you would pass in the constants `GLIB_MAJOR_VERSION`,
106/// `GLIB_MINOR_VERSION`, `GLIB_MICRO_VERSION` as the three arguments
107/// to this function; that produces a check that the library in use
108/// is compatible with the version of GLib the application or module
109/// was compiled against.
110///
111/// Compatibility is defined by two things: first the version
112/// of the running library is newer than the version
113/// `@required_major.required_minor.@required_micro`. Second
114/// the running library must be binary compatible with the
115/// version `@required_major.@required_minor.@required_micro`
116/// (same major version.)
117/// ## `required_major`
118/// the required major version
119/// ## `required_minor`
120/// the required minor version
121/// ## `required_micro`
122/// the required micro version
123///
124/// # Returns
125///
126/// [`None`] if the GLib library is
127///   compatible with the given version, or a string describing the
128///   version mismatch. The returned string is owned by GLib and must
129///   not be modified or freed.
130#[doc(alias = "glib_check_version")]
131pub fn check_version(
132    required_major: u32,
133    required_minor: u32,
134    required_micro: u32,
135) -> Option<crate::GString> {
136    unsafe {
137        from_glib_none(ffi::glib_check_version(
138            required_major,
139            required_minor,
140            required_micro,
141        ))
142    }
143}
144
145/// Computes the checksum for a binary @data. This is a
146/// convenience wrapper for g_checksum_new(), g_checksum_get_string()
147/// and g_checksum_free().
148///
149/// The hexadecimal string returned will be in lower case.
150/// ## `checksum_type`
151/// a #GChecksumType
152/// ## `data`
153/// binary blob to compute the digest of
154///
155/// # Returns
156///
157/// the digest of the binary data as a
158///   string in hexadecimal, or [`None`] if g_checksum_new() fails for
159///   @checksum_type. The returned string should be freed with g_free() when
160///   done using it.
161#[doc(alias = "g_compute_checksum_for_bytes")]
162pub fn compute_checksum_for_bytes(
163    checksum_type: ChecksumType,
164    data: &Bytes,
165) -> Option<crate::GString> {
166    unsafe {
167        from_glib_full(ffi::g_compute_checksum_for_bytes(
168            checksum_type.into_glib(),
169            data.to_glib_none().0,
170        ))
171    }
172}
173
174/// Computes the checksum for a binary @data of @length. This is a
175/// convenience wrapper for g_checksum_new(), g_checksum_get_string()
176/// and g_checksum_free().
177///
178/// The hexadecimal string returned will be in lower case.
179/// ## `checksum_type`
180/// a #GChecksumType
181/// ## `data`
182/// binary blob to compute the digest of
183///
184/// # Returns
185///
186/// the digest of the binary data as a
187///   string in hexadecimal, or [`None`] if g_checksum_new() fails for
188///   @checksum_type. The returned string should be freed with g_free() when
189///   done using it.
190#[doc(alias = "g_compute_checksum_for_data")]
191pub fn compute_checksum_for_data(
192    checksum_type: ChecksumType,
193    data: &[u8],
194) -> Option<crate::GString> {
195    let length = data.len() as _;
196    unsafe {
197        from_glib_full(ffi::g_compute_checksum_for_data(
198            checksum_type.into_glib(),
199            data.to_glib_none().0,
200            length,
201        ))
202    }
203}
204
205/// Computes the HMAC for a binary @data. This is a
206/// convenience wrapper for g_hmac_new(), g_hmac_get_string()
207/// and g_hmac_unref().
208///
209/// The hexadecimal string returned will be in lower case.
210/// ## `digest_type`
211/// a #GChecksumType to use for the HMAC
212/// ## `key`
213/// the key to use in the HMAC
214/// ## `data`
215/// binary blob to compute the HMAC of
216///
217/// # Returns
218///
219/// the HMAC of the binary data as a string in hexadecimal.
220///   The returned string should be freed with g_free() when done using it.
221#[doc(alias = "g_compute_hmac_for_bytes")]
222pub fn compute_hmac_for_bytes(
223    digest_type: ChecksumType,
224    key: &Bytes,
225    data: &Bytes,
226) -> crate::GString {
227    unsafe {
228        from_glib_full(ffi::g_compute_hmac_for_bytes(
229            digest_type.into_glib(),
230            key.to_glib_none().0,
231            data.to_glib_none().0,
232        ))
233    }
234}
235
236/// Computes the HMAC for a binary @data of @length. This is a
237/// convenience wrapper for g_hmac_new(), g_hmac_get_string()
238/// and g_hmac_unref().
239///
240/// The hexadecimal string returned will be in lower case.
241/// ## `digest_type`
242/// a #GChecksumType to use for the HMAC
243/// ## `key`
244/// the key to use in the HMAC
245/// ## `data`
246/// binary blob to compute the HMAC of
247///
248/// # Returns
249///
250/// the HMAC of the binary data as a string in hexadecimal.
251///   The returned string should be freed with g_free() when done using it.
252#[doc(alias = "g_compute_hmac_for_data")]
253pub fn compute_hmac_for_data(digest_type: ChecksumType, key: &[u8], data: &[u8]) -> crate::GString {
254    let key_len = key.len() as _;
255    let length = data.len() as _;
256    unsafe {
257        from_glib_full(ffi::g_compute_hmac_for_data(
258            digest_type.into_glib(),
259            key.to_glib_none().0,
260            key_len,
261            data.to_glib_none().0,
262            length,
263        ))
264    }
265}
266
267/// This is a variant of g_dgettext() that allows specifying a locale
268/// category instead of always using `LC_MESSAGES`. See g_dgettext() for
269/// more information about how this functions differs from calling
270/// dcgettext() directly.
271/// ## `domain`
272/// the translation domain to use, or [`None`] to use
273///   the domain set with textdomain()
274/// ## `msgid`
275/// message to translate
276/// ## `category`
277/// a locale category
278///
279/// # Returns
280///
281/// the translated string for the given locale category
282#[doc(alias = "g_dcgettext")]
283pub fn dcgettext(domain: Option<&str>, msgid: &str, category: i32) -> crate::GString {
284    unsafe {
285        from_glib_none(ffi::g_dcgettext(
286            domain.to_glib_none().0,
287            msgid.to_glib_none().0,
288            category,
289        ))
290    }
291}
292
293/// This function is a wrapper of dgettext() which does not translate
294/// the message if the default domain as set with textdomain() has no
295/// translations for the current locale.
296///
297/// The advantage of using this function over dgettext() proper is that
298/// libraries using this function (like GTK) will not use translations
299/// if the application using the library does not have translations for
300/// the current locale.  This results in a consistent English-only
301/// interface instead of one having partial translations.  For this
302/// feature to work, the call to textdomain() and setlocale() should
303/// precede any g_dgettext() invocations.  For GTK, it means calling
304/// textdomain() before gtk_init or its variants.
305///
306/// This function disables translations if and only if upon its first
307/// call all the following conditions hold:
308///
309/// - @domain is not [`None`]
310///
311/// - textdomain() has been called to set a default text domain
312///
313/// - there is no translations available for the default text domain
314///   and the current locale
315///
316/// - current locale is not "C" or any English locales (those
317///   starting with "en_")
318///
319/// Note that this behavior may not be desired for example if an application
320/// has its untranslated messages in a language other than English. In those
321/// cases the application should call textdomain() after initializing GTK.
322///
323/// Applications should normally not use this function directly,
324/// but use the _() macro for translations.
325/// ## `domain`
326/// the translation domain to use, or [`None`] to use
327///   the domain set with textdomain()
328/// ## `msgid`
329/// message to translate
330///
331/// # Returns
332///
333/// The translated string
334#[doc(alias = "g_dgettext")]
335pub fn dgettext(domain: Option<&str>, msgid: &str) -> crate::GString {
336    unsafe {
337        from_glib_none(ffi::g_dgettext(
338            domain.to_glib_none().0,
339            msgid.to_glib_none().0,
340        ))
341    }
342}
343
344/// This function is a wrapper of dngettext() which does not translate
345/// the message if the default domain as set with textdomain() has no
346/// translations for the current locale.
347///
348/// See g_dgettext() for details of how this differs from dngettext()
349/// proper.
350/// ## `domain`
351/// the translation domain to use, or [`None`] to use
352///   the domain set with textdomain()
353/// ## `msgid`
354/// message to translate
355/// ## `msgid_plural`
356/// plural form of the message
357/// ## `n`
358/// the quantity for which translation is needed
359///
360/// # Returns
361///
362/// The translated string
363#[doc(alias = "g_dngettext")]
364pub fn dngettext(
365    domain: Option<&str>,
366    msgid: &str,
367    msgid_plural: &str,
368    n: libc::c_ulong,
369) -> crate::GString {
370    unsafe {
371        from_glib_none(ffi::g_dngettext(
372            domain.to_glib_none().0,
373            msgid.to_glib_none().0,
374            msgid_plural.to_glib_none().0,
375            n,
376        ))
377    }
378}
379
380/// This function is a variant of g_dgettext() which supports
381/// a disambiguating message context. GNU gettext uses the
382/// '\004' character to separate the message context and
383/// message id in @msgctxtid.
384/// If 0 is passed as @msgidoffset, this function will fall back to
385/// trying to use the deprecated convention of using "|" as a separation
386/// character.
387///
388/// This uses g_dgettext() internally. See that functions for differences
389/// with dgettext() proper.
390///
391/// Applications should normally not use this function directly,
392/// but use the C_() macro for translations with context.
393/// ## `domain`
394/// the translation domain to use, or [`None`] to use
395///   the domain set with textdomain()
396/// ## `msgctxtid`
397/// a combined message context and message id, separated
398///   by a \004 character
399/// ## `msgidoffset`
400/// the offset of the message id in @msgctxid
401///
402/// # Returns
403///
404/// The translated string
405#[doc(alias = "g_dpgettext")]
406pub fn dpgettext(domain: Option<&str>, msgctxtid: &str, msgidoffset: usize) -> crate::GString {
407    unsafe {
408        from_glib_none(ffi::g_dpgettext(
409            domain.to_glib_none().0,
410            msgctxtid.to_glib_none().0,
411            msgidoffset,
412        ))
413    }
414}
415
416/// This function is a variant of g_dgettext() which supports
417/// a disambiguating message context. GNU gettext uses the
418/// '\004' character to separate the message context and
419/// message id in @msgctxtid.
420///
421/// This uses g_dgettext() internally. See that functions for differences
422/// with dgettext() proper.
423///
424/// This function differs from C_() in that it is not a macro and
425/// thus you may use non-string-literals as context and msgid arguments.
426/// ## `domain`
427/// the translation domain to use, or [`None`] to use
428///   the domain set with textdomain()
429/// ## `context`
430/// the message context
431/// ## `msgid`
432/// the message
433///
434/// # Returns
435///
436/// The translated string
437#[doc(alias = "g_dpgettext2")]
438pub fn dpgettext2(domain: Option<&str>, context: &str, msgid: &str) -> crate::GString {
439    unsafe {
440        from_glib_none(ffi::g_dpgettext2(
441            domain.to_glib_none().0,
442            context.to_glib_none().0,
443            msgid.to_glib_none().0,
444        ))
445    }
446}
447
448/// Writes all of @contents to a file named @filename. This is a convenience
449/// wrapper around calling g_file_set_contents_full() with `flags` set to
450/// `G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING` and
451/// `mode` set to `0666`.
452/// ## `filename`
453/// name of a file to write @contents to, in the GLib file name
454///   encoding
455/// ## `contents`
456/// string to write to the file
457///
458/// # Returns
459///
460/// [`true`] on success, [`false`] if an error occurred
461#[doc(alias = "g_file_set_contents")]
462pub fn file_set_contents(
463    filename: impl AsRef<std::path::Path>,
464    contents: &[u8],
465) -> Result<(), crate::Error> {
466    let length = contents.len() as _;
467    unsafe {
468        let mut error = std::ptr::null_mut();
469        let is_ok = ffi::g_file_set_contents(
470            filename.as_ref().to_glib_none().0,
471            contents.to_glib_none().0,
472            length,
473            &mut error,
474        );
475        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
476        if error.is_null() {
477            Ok(())
478        } else {
479            Err(from_glib_full(error))
480        }
481    }
482}
483
484/// Writes all of @contents to a file named @filename, with good error checking.
485/// If a file called @filename already exists it will be overwritten.
486///
487/// @flags control the properties of the write operation: whether it’s atomic,
488/// and what the tradeoff is between returning quickly or being resilient to
489/// system crashes.
490///
491/// As this function performs file I/O, it is recommended to not call it anywhere
492/// where blocking would cause problems, such as in the main loop of a graphical
493/// application. In particular, if @flags has any value other than
494/// [`FileSetContentsFlags::NONE`][crate::FileSetContentsFlags::NONE] then this function may call `fsync()`.
495///
496/// If [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] is set in @flags, the operation is atomic
497/// in the sense that it is first written to a temporary file which is then
498/// renamed to the final name.
499///
500/// Notes:
501///
502/// - On UNIX, if @filename already exists hard links to @filename will break.
503///   Also since the file is recreated, existing permissions, access control
504///   lists, metadata etc. may be lost. If @filename is a symbolic link,
505///   the link itself will be replaced, not the linked file.
506///
507/// - On UNIX, if @filename already exists and is non-empty, and if the system
508///   supports it (via a journalling filesystem or equivalent), and if
509///   [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] is set in @flags, the `fsync()` call (or
510///   equivalent) will be used to ensure atomic replacement: @filename
511///   will contain either its old contents or @contents, even in the face of
512///   system power loss, the disk being unsafely removed, etc.
513///
514/// - On UNIX, if @filename does not already exist or is empty, there is a
515///   possibility that system power loss etc. after calling this function will
516///   leave @filename empty or full of NUL bytes, depending on the underlying
517///   filesystem, unless [`FileSetContentsFlags::DURABLE`][crate::FileSetContentsFlags::DURABLE] and
518///   [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] are set in @flags.
519///
520/// - On Windows renaming a file will not remove an existing file with the
521///   new name, so on Windows there is a race condition between the existing
522///   file being removed and the temporary file being renamed.
523///
524/// - On Windows there is no way to remove a file that is open to some
525///   process, or mapped into memory. Thus, this function will fail if
526///   @filename already exists and is open.
527///
528/// If the call was successful, it returns [`true`]. If the call was not successful,
529/// it returns [`false`] and sets @error. The error domain is `G_FILE_ERROR`.
530/// Possible error codes are those in the #GFileError enumeration.
531///
532/// Note that the name for the temporary file is constructed by appending up
533/// to 7 characters to @filename.
534///
535/// If the file didn’t exist before and is created, it will be given the
536/// permissions from @mode. Otherwise, the permissions of the existing file will
537/// remain unchanged.
538/// ## `filename`
539/// name of a file to write @contents to, in the GLib file name
540///   encoding
541/// ## `contents`
542/// string to write to the file
543/// ## `flags`
544/// flags controlling the safety vs speed of the operation
545/// ## `mode`
546/// file mode, as passed to `open()`; typically this will be `0666`
547///
548/// # Returns
549///
550/// [`true`] on success, [`false`] if an error occurred
551#[cfg(feature = "v2_66")]
552#[cfg_attr(docsrs, doc(cfg(feature = "v2_66")))]
553#[doc(alias = "g_file_set_contents_full")]
554pub fn file_set_contents_full(
555    filename: impl AsRef<std::path::Path>,
556    contents: &[u8],
557    flags: FileSetContentsFlags,
558    mode: i32,
559) -> Result<(), crate::Error> {
560    let length = contents.len() as _;
561    unsafe {
562        let mut error = std::ptr::null_mut();
563        let is_ok = ffi::g_file_set_contents_full(
564            filename.as_ref().to_glib_none().0,
565            contents.to_glib_none().0,
566            length,
567            flags.into_glib(),
568            mode,
569            &mut error,
570        );
571        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
572        if error.is_null() {
573            Ok(())
574        } else {
575            Err(from_glib_full(error))
576        }
577    }
578}
579
580///
581///  // DON'T DO THIS
582///  if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
583///    {
584///      fd = g_open (filename, O_WRONLY);
585///      // write to fd
586///    }
587///
588///  // DO THIS INSTEAD
589///  fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
590///  if (fd == -1)
591///    {
592///      // check error
593///      if (errno == ELOOP)
594///        // file is a symlink and can be ignored
595///      else
596///        // handle errors as before
597///    }
598///  else
599///    {
600///      // write to fd
601///    }
602/// ]|
603///
604/// Another thing to note is that [`FileTest::EXISTS`][crate::FileTest::EXISTS] and
605/// [`FileTest::IS_EXECUTABLE`][crate::FileTest::IS_EXECUTABLE] are implemented using the access()
606/// system call. This usually doesn't matter, but if your program
607/// is setuid or setgid it means that these tests will give you
608/// the answer for the real user ID and group ID, rather than the
609/// effective user ID and group ID.
610///
611/// On Windows, there are no symlinks, so testing for
612/// [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] will always return [`false`]. Testing for
613/// [`FileTest::IS_EXECUTABLE`][crate::FileTest::IS_EXECUTABLE] will just check that the file exists and
614/// its name indicates that it is executable, checking for well-known
615/// extensions and those listed in the `PATHEXT` environment variable.
616/// ## `filename`
617/// a filename to test in the
618///     GLib file name encoding
619/// ## `test`
620/// bitfield of #GFileTest flags
621///
622/// # Returns
623///
624/// whether a test was [`true`]
625#[doc(alias = "g_file_test")]
626#[allow(dead_code)]
627pub(crate) fn file_test(filename: impl AsRef<std::path::Path>, test: FileTest) -> bool {
628    unsafe {
629        from_glib(ffi::g_file_test(
630            filename.as_ref().to_glib_none().0,
631            test.into_glib(),
632        ))
633    }
634}
635
636/// Returns the display basename for the particular filename, guaranteed
637/// to be valid UTF-8. The display name might not be identical to the filename,
638/// for instance there might be problems converting it to UTF-8, and some files
639/// can be translated in the display.
640///
641/// If GLib cannot make sense of the encoding of @filename, as a last resort it
642/// replaces unknown characters with U+FFFD, the Unicode replacement character.
643/// You can search the result for the UTF-8 encoding of this character (which is
644/// "\357\277\275" in octal notation) to find out if @filename was in an invalid
645/// encoding.
646///
647/// You must pass the whole absolute pathname to this functions so that
648/// translation of well known locations can be done.
649///
650/// This function is preferred over g_filename_display_name() if you know the
651/// whole path, as it allows translation.
652/// ## `filename`
653/// an absolute pathname in the
654///     GLib file name encoding
655///
656/// # Returns
657///
658/// a newly allocated string containing
659///   a rendition of the basename of the filename in valid UTF-8
660#[doc(alias = "g_filename_display_basename")]
661pub fn filename_display_basename(filename: impl AsRef<std::path::Path>) -> crate::GString {
662    unsafe {
663        from_glib_full(ffi::g_filename_display_basename(
664            filename.as_ref().to_glib_none().0,
665        ))
666    }
667}
668
669/// Converts a filename into a valid UTF-8 string. The conversion is
670/// not necessarily reversible, so you should keep the original around
671/// and use the return value of this function only for display purposes.
672/// Unlike g_filename_to_utf8(), the result is guaranteed to be non-[`None`]
673/// even if the filename actually isn't in the GLib file name encoding.
674///
675/// If GLib cannot make sense of the encoding of @filename, as a last resort it
676/// replaces unknown characters with U+FFFD, the Unicode replacement character.
677/// You can search the result for the UTF-8 encoding of this character (which is
678/// "\357\277\275" in octal notation) to find out if @filename was in an invalid
679/// encoding.
680///
681/// If you know the whole pathname of the file you should use
682/// g_filename_display_basename(), since that allows location-based
683/// translation of filenames.
684/// ## `filename`
685/// a pathname hopefully in the
686///     GLib file name encoding
687///
688/// # Returns
689///
690/// a newly allocated string containing
691///   a rendition of the filename in valid UTF-8
692#[doc(alias = "g_filename_display_name")]
693pub fn filename_display_name(filename: impl AsRef<std::path::Path>) -> crate::GString {
694    unsafe {
695        from_glib_full(ffi::g_filename_display_name(
696            filename.as_ref().to_glib_none().0,
697        ))
698    }
699}
700
701/// Converts an escaped ASCII-encoded URI to a local filename in the
702/// encoding used for filenames.
703///
704/// Since GLib 2.78, the query string and fragment can be present in the URI,
705/// but are not part of the resulting filename.
706/// We take inspiration from https://url.spec.whatwg.org/#file-state,
707/// but we don't support the entire standard.
708/// ## `uri`
709/// a uri describing a filename (escaped, encoded in ASCII).
710///
711/// # Returns
712///
713/// a newly-allocated string holding
714///               the resulting filename, or [`None`] on an error.
715///
716/// ## `hostname`
717/// Location to store hostname for the URI.
718///            If there is no hostname in the URI, [`None`] will be
719///            stored in this location.
720#[doc(alias = "g_filename_from_uri")]
721pub fn filename_from_uri(
722    uri: &str,
723) -> Result<(std::path::PathBuf, Option<crate::GString>), crate::Error> {
724    unsafe {
725        let mut hostname = std::ptr::null_mut();
726        let mut error = std::ptr::null_mut();
727        let ret = ffi::g_filename_from_uri(uri.to_glib_none().0, &mut hostname, &mut error);
728        if error.is_null() {
729            Ok((from_glib_full(ret), from_glib_full(hostname)))
730        } else {
731            Err(from_glib_full(error))
732        }
733    }
734}
735
736/// Converts an absolute filename to an escaped ASCII-encoded URI, with the path
737/// component following Section 3.3. of RFC 2396.
738/// ## `filename`
739/// an absolute filename specified in the GLib file
740///     name encoding, which is the on-disk file name bytes on Unix, and UTF-8
741///     on Windows
742/// ## `hostname`
743/// A UTF-8 encoded hostname, or [`None`] for none.
744///
745/// # Returns
746///
747/// a newly-allocated string holding the resulting
748///               URI, or [`None`] on an error.
749#[doc(alias = "g_filename_to_uri")]
750pub fn filename_to_uri(
751    filename: impl AsRef<std::path::Path>,
752    hostname: Option<&str>,
753) -> Result<crate::GString, crate::Error> {
754    unsafe {
755        let mut error = std::ptr::null_mut();
756        let ret = ffi::g_filename_to_uri(
757            filename.as_ref().to_glib_none().0,
758            hostname.to_glib_none().0,
759            &mut error,
760        );
761        if error.is_null() {
762            Ok(from_glib_full(ret))
763        } else {
764            Err(from_glib_full(error))
765        }
766    }
767}
768
769/// Locates the first executable named @program in the user's path, in the
770/// same way that execvp() would locate it. Returns an allocated string
771/// with the absolute path name, or [`None`] if the program is not found in
772/// the path. If @program is already an absolute path, returns a copy of
773/// @program if @program exists and is executable, and [`None`] otherwise.
774///
775/// On Windows, if @program does not have a file type suffix, tries
776/// with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
777/// the `PATHEXT` environment variable.
778///
779/// On Windows, it looks for the file in the same way as CreateProcess()
780/// would. This means first in the directory where the executing
781/// program was loaded from, then in the current directory, then in the
782/// Windows 32-bit system directory, then in the Windows directory, and
783/// finally in the directories in the `PATH` environment variable. If
784/// the program is found, the return value contains the full name
785/// including the type suffix.
786/// ## `program`
787/// a program name in the GLib file name encoding
788///
789/// # Returns
790///
791/// a newly-allocated
792///   string with the absolute path, or [`None`]
793#[doc(alias = "g_find_program_in_path")]
794pub fn find_program_in_path(program: impl AsRef<std::path::Path>) -> Option<std::path::PathBuf> {
795    unsafe {
796        from_glib_full(ffi::g_find_program_in_path(
797            program.as_ref().to_glib_none().0,
798        ))
799    }
800}
801
802/// Formats a size (for example the size of a file) into a human readable
803/// string.  Sizes are rounded to the nearest size prefix (kB, MB, GB)
804/// and are displayed rounded to the nearest tenth. E.g. the file size
805/// 3292528 bytes will be converted into the string "3.2 MB". The returned string
806/// is UTF-8, and may use a non-breaking space to separate the number and units,
807/// to ensure they aren’t separated when line wrapped.
808///
809/// The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
810///
811/// This string should be freed with g_free() when not needed any longer.
812///
813/// See g_format_size_full() for more options about how the size might be
814/// formatted.
815/// ## `size`
816/// a size in bytes
817///
818/// # Returns
819///
820/// a newly-allocated formatted string containing
821///   a human readable file size
822#[doc(alias = "g_format_size")]
823pub fn format_size(size: u64) -> crate::GString {
824    unsafe { from_glib_full(ffi::g_format_size(size)) }
825}
826
827/// Formats a size.
828///
829/// This function is similar to g_format_size() but allows for flags
830/// that modify the output. See #GFormatSizeFlags.
831/// ## `size`
832/// a size in bytes
833/// ## `flags`
834/// #GFormatSizeFlags to modify the output
835///
836/// # Returns
837///
838/// a newly-allocated formatted string
839///   containing a human readable file size
840#[doc(alias = "g_format_size_full")]
841pub fn format_size_full(size: u64, flags: FormatSizeFlags) -> crate::GString {
842    unsafe { from_glib_full(ffi::g_format_size_full(size, flags.into_glib())) }
843}
844
845/// Gets a human-readable name for the application, as set by
846/// g_set_application_name(). This name should be localized if
847/// possible, and is intended for display to the user.  Contrast with
848/// g_get_prgname(), which gets a non-localized name. If
849/// g_set_application_name() has not been called, returns the result of
850/// g_get_prgname() (which may be [`None`] if g_set_prgname() has also not
851/// been called).
852///
853/// # Returns
854///
855/// human-readable application
856///   name. May return [`None`]
857#[doc(alias = "g_get_application_name")]
858#[doc(alias = "get_application_name")]
859pub fn application_name() -> Option<crate::GString> {
860    unsafe { from_glib_none(ffi::g_get_application_name()) }
861}
862
863/// Gets the character set for the current locale.
864///
865/// # Returns
866///
867/// a newly allocated string containing the name
868///     of the character set. This string must be freed with g_free().
869#[doc(alias = "g_get_codeset")]
870#[doc(alias = "get_codeset")]
871pub fn codeset() -> crate::GString {
872    unsafe { from_glib_full(ffi::g_get_codeset()) }
873}
874
875/// Obtains the character set used by the console attached to the process,
876/// which is suitable for printing output to the terminal.
877///
878/// Usually this matches the result returned by g_get_charset(), but in
879/// environments where the locale's character set does not match the encoding
880/// of the console this function tries to guess a more suitable value instead.
881///
882/// On Windows the character set returned by this function is the
883/// output code page used by the console associated with the calling process.
884/// If the codepage can't be determined (for example because there is no
885/// console attached) UTF-8 is assumed.
886///
887/// The return value is [`true`] if the locale's encoding is UTF-8, in that
888/// case you can perhaps avoid calling g_convert().
889///
890/// The string returned in @charset is not allocated, and should not be
891/// freed.
892///
893/// # Returns
894///
895/// [`true`] if the returned charset is UTF-8
896///
897/// ## `charset`
898/// return location for character set
899///   name, or [`None`].
900#[cfg(feature = "v2_62")]
901#[cfg_attr(docsrs, doc(cfg(feature = "v2_62")))]
902#[doc(alias = "g_get_console_charset")]
903#[doc(alias = "get_console_charset")]
904pub fn console_charset() -> Option<crate::GString> {
905    unsafe {
906        let mut charset = std::ptr::null();
907        let ret = from_glib(ffi::g_get_console_charset(&mut charset));
908        if ret {
909            Some(from_glib_none(charset))
910        } else {
911            None
912        }
913    }
914}
915
916/// Gets the current directory.
917///
918/// The returned string should be freed when no longer needed.
919/// The encoding of the returned string is system defined.
920/// On Windows, it is always UTF-8.
921///
922/// Since GLib 2.40, this function will return the value of the "PWD"
923/// environment variable if it is set and it happens to be the same as
924/// the current directory.  This can make a difference in the case that
925/// the current directory is the target of a symbolic link.
926///
927/// # Returns
928///
929/// the current directory
930#[doc(alias = "g_get_current_dir")]
931#[doc(alias = "get_current_dir")]
932pub fn current_dir() -> std::path::PathBuf {
933    unsafe { from_glib_full(ffi::g_get_current_dir()) }
934}
935
936/// Gets the list of environment variables for the current process.
937///
938/// The list is [`None`] terminated and each item in the list is of the
939/// form 'NAME=VALUE'.
940///
941/// This is equivalent to direct access to the 'environ' global variable,
942/// except portable.
943///
944/// The return value is freshly allocated and it should be freed with
945/// g_strfreev() when it is no longer needed.
946///
947/// # Returns
948///
949///
950///     the list of environment variables
951#[doc(alias = "g_get_environ")]
952#[doc(alias = "get_environ")]
953pub fn environ() -> Vec<std::ffi::OsString> {
954    unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_get_environ()) }
955}
956
957/// Gets the current user's home directory.
958///
959/// As with most UNIX tools, this function will return the value of the
960/// `HOME` environment variable if it is set to an existing absolute path
961/// name, falling back to the `passwd` file in the case that it is unset.
962///
963/// If the path given in `HOME` is non-absolute, does not exist, or is
964/// not a directory, the result is undefined.
965///
966/// Before version 2.36 this function would ignore the `HOME` environment
967/// variable, taking the value from the `passwd` database instead. This was
968/// changed to increase the compatibility of GLib with other programs (and
969/// the XDG basedir specification) and to increase testability of programs
970/// based on GLib (by making it easier to run them from test frameworks).
971///
972/// If your program has a strong requirement for either the new or the
973/// old behaviour (and if you don't wish to increase your GLib
974/// dependency to ensure that the new behaviour is in effect) then you
975/// should either directly check the `HOME` environment variable yourself
976/// or unset it before calling any functions in GLib.
977///
978/// # Returns
979///
980/// the current user's home directory
981#[doc(alias = "g_get_home_dir")]
982#[doc(alias = "get_home_dir")]
983pub fn home_dir() -> std::path::PathBuf {
984    unsafe { from_glib_none(ffi::g_get_home_dir()) }
985}
986
987/// Return a name for the machine.
988///
989/// The returned name is not necessarily a fully-qualified domain name,
990/// or even present in DNS or some other name service at all. It need
991/// not even be unique on your local network or site, but usually it
992/// is. Callers should not rely on the return value having any specific
993/// properties like uniqueness for security purposes. Even if the name
994/// of the machine is changed while an application is running, the
995/// return value from this function does not change. The returned
996/// string is owned by GLib and should not be modified or freed. If no
997/// name can be determined, a default fixed string "localhost" is
998/// returned.
999///
1000/// The encoding of the returned string is UTF-8.
1001///
1002/// # Returns
1003///
1004/// the host name of the machine.
1005#[doc(alias = "g_get_host_name")]
1006#[doc(alias = "get_host_name")]
1007pub fn host_name() -> crate::GString {
1008    unsafe { from_glib_none(ffi::g_get_host_name()) }
1009}
1010
1011/// Computes a list of applicable locale names, which can be used to
1012/// e.g. construct locale-dependent filenames or search paths. The returned
1013/// list is sorted from most desirable to least desirable and always contains
1014/// the default locale "C".
1015///
1016/// For example, if LANGUAGE=de:en_US, then the returned list is
1017/// "de", "en_US", "en", "C".
1018///
1019/// This function consults the environment variables `LANGUAGE`, `LC_ALL`,
1020/// `LC_MESSAGES` and `LANG` to find the list of locales specified by the
1021/// user.
1022///
1023/// # Returns
1024///
1025/// a [`None`]-terminated array of strings owned by GLib
1026///    that must not be modified or freed.
1027#[doc(alias = "g_get_language_names")]
1028#[doc(alias = "get_language_names")]
1029pub fn language_names() -> Vec<crate::GString> {
1030    unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_language_names()) }
1031}
1032
1033/// Computes a list of applicable locale names with a locale category name,
1034/// which can be used to construct the fallback locale-dependent filenames
1035/// or search paths. The returned list is sorted from most desirable to
1036/// least desirable and always contains the default locale "C".
1037///
1038/// This function consults the environment variables `LANGUAGE`, `LC_ALL`,
1039/// @category_name, and `LANG` to find the list of locales specified by the
1040/// user.
1041///
1042/// g_get_language_names() returns g_get_language_names_with_category("LC_MESSAGES").
1043/// ## `category_name`
1044/// a locale category name
1045///
1046/// # Returns
1047///
1048/// a [`None`]-terminated array of strings owned by
1049///    the thread g_get_language_names_with_category was called from.
1050///    It must not be modified or freed. It must be copied if planned to be used in another thread.
1051#[cfg(feature = "v2_58")]
1052#[cfg_attr(docsrs, doc(cfg(feature = "v2_58")))]
1053#[doc(alias = "g_get_language_names_with_category")]
1054#[doc(alias = "get_language_names_with_category")]
1055pub fn language_names_with_category(category_name: &str) -> Vec<crate::GString> {
1056    unsafe {
1057        FromGlibPtrContainer::from_glib_none(ffi::g_get_language_names_with_category(
1058            category_name.to_glib_none().0,
1059        ))
1060    }
1061}
1062
1063/// Returns a list of derived variants of @locale, which can be used to
1064/// e.g. construct locale-dependent filenames or search paths. The returned
1065/// list is sorted from most desirable to least desirable.
1066/// This function handles territory, charset and extra locale modifiers. See
1067/// [`setlocale(3)`](man:setlocale) for information about locales and their format.
1068///
1069/// @locale itself is guaranteed to be returned in the output.
1070///
1071/// For example, if @locale is `fr_BE`, then the returned list
1072/// is `fr_BE`, `fr`. If @locale is `en_GB.UTF-8@euro`, then the returned list
1073/// is `en_GB.UTF-8@euro`, `en_GB.UTF-8`, `en_GB@euro`, `en_GB`, `en.UTF-8@euro`,
1074/// `en.UTF-8`, `en@euro`, `en`.
1075///
1076/// If you need the list of variants for the current locale,
1077/// use g_get_language_names().
1078/// ## `locale`
1079/// a locale identifier
1080///
1081/// # Returns
1082///
1083/// a newly
1084///   allocated array of newly allocated strings with the locale variants. Free with
1085///   g_strfreev().
1086#[doc(alias = "g_get_locale_variants")]
1087#[doc(alias = "get_locale_variants")]
1088pub fn locale_variants(locale: &str) -> Vec<crate::GString> {
1089    unsafe {
1090        FromGlibPtrContainer::from_glib_full(ffi::g_get_locale_variants(locale.to_glib_none().0))
1091    }
1092}
1093
1094/// Queries the system monotonic time in microseconds.
1095///
1096/// The monotonic clock will always increase and doesn’t suffer
1097/// discontinuities when the user (or NTP) changes the system time.  It
1098/// may or may not continue to tick during times where the machine is
1099/// suspended.
1100///
1101/// We try to use the clock that corresponds as closely as possible to
1102/// the passage of time as measured by system calls such as
1103/// [`poll()`](man:poll(2)) but it
1104/// may not always be possible to do this.
1105///
1106/// A more accurate version of this function exists.
1107/// [`monotonic_time_ns()`][crate::monotonic_time_ns()] returns the time in nanoseconds.
1108///
1109/// # Returns
1110///
1111/// the monotonic time, in microseconds
1112#[doc(alias = "g_get_monotonic_time")]
1113#[doc(alias = "get_monotonic_time")]
1114pub fn monotonic_time() -> i64 {
1115    unsafe { ffi::g_get_monotonic_time() }
1116}
1117
1118/// Queries the system monotonic time in nanoseconds.
1119///
1120/// The monotonic clock will always increase and doesn’t suffer
1121/// discontinuities when the user (or NTP) changes the system time.  It
1122/// may or may not continue to tick during times where the machine is
1123/// suspended.
1124///
1125/// We try to use the clock that corresponds as closely as possible to
1126/// the passage of time as measured by system calls such as
1127/// [`poll()`](man:poll(2)) but it
1128/// may not always be possible to do this.
1129///
1130/// Another version of this function exists.
1131/// [`monotonic_time()`][crate::monotonic_time()] returns the time in microseconds.
1132/// If you want to support older GLib versions, it is an alternative.
1133///
1134/// # Returns
1135///
1136/// the monotonic time, in nanoseconds
1137#[cfg(feature = "v2_88")]
1138#[cfg_attr(docsrs, doc(cfg(feature = "v2_88")))]
1139#[doc(alias = "g_get_monotonic_time_ns")]
1140#[doc(alias = "get_monotonic_time_ns")]
1141pub fn monotonic_time_ns() -> u64 {
1142    unsafe { ffi::g_get_monotonic_time_ns() }
1143}
1144
1145/// Determine the approximate number of threads that the system will
1146/// schedule simultaneously for this process.  This is intended to be
1147/// used as a parameter to g_thread_pool_new() for CPU bound tasks and
1148/// similar cases.
1149///
1150/// On platforms where enough information is known, this will be the number of
1151/// high performance cores and will not include low power ‘efficiency’ cores.
1152/// Use platform specific APIs to query for low power cores if needed.
1153///
1154/// # Returns
1155///
1156/// Number of schedulable threads, always greater than 0
1157#[doc(alias = "g_get_num_processors")]
1158#[doc(alias = "get_num_processors")]
1159pub fn num_processors() -> u32 {
1160    unsafe { ffi::g_get_num_processors() }
1161}
1162
1163/// Get information about the operating system.
1164///
1165/// On Linux this comes from the `/etc/os-release` file. On other systems, it may
1166/// come from a variety of sources. You can either use the standard key names
1167/// like `G_OS_INFO_KEY_NAME` or pass any UTF-8 string key name. For example,
1168/// `/etc/os-release` provides a number of other less commonly used values that may
1169/// be useful. No key is guaranteed to be provided, so the caller should always
1170/// check if the result is [`None`].
1171/// ## `key_name`
1172/// a key for the OS info being requested, for example `G_OS_INFO_KEY_NAME`.
1173///
1174/// # Returns
1175///
1176/// The associated value for the requested key or [`None`] if
1177///   this information is not provided.
1178#[cfg(feature = "v2_64")]
1179#[cfg_attr(docsrs, doc(cfg(feature = "v2_64")))]
1180#[doc(alias = "g_get_os_info")]
1181#[doc(alias = "get_os_info")]
1182pub fn os_info(key_name: &str) -> Option<crate::GString> {
1183    unsafe { from_glib_full(ffi::g_get_os_info(key_name.to_glib_none().0)) }
1184}
1185
1186/// Gets the real name of the user. This usually comes from the user's
1187/// entry in the `passwd` file. The encoding of the returned string is
1188/// system-defined. (On Windows, it is, however, always UTF-8.) If the
1189/// real user name cannot be determined, the string "Unknown" is
1190/// returned.
1191///
1192/// # Returns
1193///
1194/// the user's real name.
1195#[doc(alias = "g_get_real_name")]
1196#[doc(alias = "get_real_name")]
1197pub fn real_name() -> std::ffi::OsString {
1198    unsafe { from_glib_none(ffi::g_get_real_name()) }
1199}
1200
1201/// Queries the system wall-clock time.
1202///
1203/// This is equivalent to the UNIX [`gettimeofday()`](man:gettimeofday(2))
1204/// function, but portable.
1205///
1206/// You should only use this call if you are actually interested in the real
1207/// wall-clock time. [`monotonic_time()`][crate::monotonic_time()] is probably more useful for
1208/// measuring intervals.
1209///
1210/// # Returns
1211///
1212/// the number of microseconds since
1213///   [January 1, 1970 UTC](https://en.wikipedia.org/wiki/Unix_time)
1214#[doc(alias = "g_get_real_time")]
1215#[doc(alias = "get_real_time")]
1216pub fn real_time() -> i64 {
1217    unsafe { ffi::g_get_real_time() }
1218}
1219
1220/// Returns an ordered list of base directories in which to access
1221/// system-wide configuration information.
1222///
1223/// On UNIX platforms this is determined using the mechanisms described
1224/// in the
1225/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1226/// In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
1227///
1228/// On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
1229/// If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
1230/// data for all users is used instead. A typical path is
1231/// `C:\Documents and Settings\All Users\Application Data`.
1232/// This folder is used for application data
1233/// that is not user specific. For example, an application can store
1234/// a spell-check dictionary, a database of clip art, or a log file in the
1235/// FOLDERID_ProgramData folder. This information will not roam and is available
1236/// to anyone using the computer.
1237///
1238/// The return value is cached and modifying it at runtime is not supported, as
1239/// it’s not thread-safe to modify environment variables at runtime.
1240///
1241/// # Returns
1242///
1243///
1244///     a [`None`]-terminated array of strings owned by GLib that must not be
1245///     modified or freed.
1246#[doc(alias = "g_get_system_config_dirs")]
1247#[doc(alias = "get_system_config_dirs")]
1248pub fn system_config_dirs() -> Vec<std::path::PathBuf> {
1249    unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_system_config_dirs()) }
1250}
1251
1252/// Returns an ordered list of base directories in which to access
1253/// system-wide application data.
1254///
1255/// On UNIX platforms this is determined using the mechanisms described
1256/// in the
1257/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
1258/// In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
1259///
1260/// On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
1261/// If `XDG_DATA_DIRS` is undefined,
1262/// the first elements in the list are the Application Data
1263/// and Documents folders for All Users. (These can be determined only
1264/// on Windows 2000 or later and are not present in the list on other
1265/// Windows versions.) See documentation for FOLDERID_ProgramData and
1266/// FOLDERID_PublicDocuments.
1267///
1268/// Then follows the "share" subfolder in the installation folder for
1269/// the package containing the DLL that calls this function, if it can
1270/// be determined.
1271///
1272/// Finally the list contains the "share" subfolder in the installation
1273/// folder for GLib, and in the installation folder for the package the
1274/// application's .exe file belongs to.
1275///
1276/// The installation folders above are determined by looking up the
1277/// folder where the module (DLL or EXE) in question is located. If the
1278/// folder's name is "bin", its parent is used, otherwise the folder
1279/// itself.
1280///
1281/// Note that on Windows the returned list can vary depending on where
1282/// this function is called.
1283///
1284/// The return value is cached and modifying it at runtime is not supported, as
1285/// it’s not thread-safe to modify environment variables at runtime.
1286///
1287/// # Returns
1288///
1289///
1290///     a [`None`]-terminated array of strings owned by GLib that must not be
1291///     modified or freed.
1292#[doc(alias = "g_get_system_data_dirs")]
1293#[doc(alias = "get_system_data_dirs")]
1294pub fn system_data_dirs() -> Vec<std::path::PathBuf> {
1295    unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_system_data_dirs()) }
1296}
1297
1298/// Gets the directory to use for temporary files.
1299///
1300/// On UNIX, this is taken from the `TMPDIR` environment variable.
1301/// If the variable is not set, `P_tmpdir` is
1302/// used, as defined by the system C library. Failing that, a
1303/// hard-coded default of "/tmp" is returned.
1304///
1305/// On Windows, the `TEMP` environment variable is used, with the
1306/// root directory of the Windows installation (eg: "C:\") used
1307/// as a default.
1308///
1309/// The encoding of the returned string is system-defined. On Windows,
1310/// it is always UTF-8. The return value is never [`None`] or the empty
1311/// string.
1312///
1313/// # Returns
1314///
1315/// the directory to use for temporary files.
1316#[doc(alias = "g_get_tmp_dir")]
1317#[doc(alias = "get_tmp_dir")]
1318pub fn tmp_dir() -> std::path::PathBuf {
1319    unsafe { from_glib_none(ffi::g_get_tmp_dir()) }
1320}
1321
1322/// Returns a base directory in which to store non-essential, cached
1323/// data specific to particular user.
1324///
1325/// On UNIX platforms this is determined using the mechanisms described
1326/// in the
1327/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1328/// In this case the directory retrieved will be `XDG_CACHE_HOME`.
1329///
1330/// On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
1331/// If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
1332/// repository for temporary Internet files is used instead. A typical path is
1333/// `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
1334/// See the [documentation for `FOLDERID_InternetCache`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
1335///
1336/// The return value is cached and modifying it at runtime is not supported, as
1337/// it’s not thread-safe to modify environment variables at runtime.
1338///
1339/// # Returns
1340///
1341/// a string owned by GLib that
1342///   must not be modified or freed.
1343#[doc(alias = "g_get_user_cache_dir")]
1344#[doc(alias = "get_user_cache_dir")]
1345pub fn user_cache_dir() -> std::path::PathBuf {
1346    unsafe { from_glib_none(ffi::g_get_user_cache_dir()) }
1347}
1348
1349/// Returns a base directory in which to store user-specific application
1350/// configuration information such as user preferences and settings.
1351///
1352/// On UNIX platforms this is determined using the mechanisms described
1353/// in the
1354/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1355/// In this case the directory retrieved will be `XDG_CONFIG_HOME`.
1356///
1357/// On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
1358/// If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
1359/// to roaming) application data is used instead. See the
1360/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
1361/// Note that in this case on Windows it will be  the same
1362/// as what g_get_user_data_dir() returns.
1363///
1364/// The return value is cached and modifying it at runtime is not supported, as
1365/// it’s not thread-safe to modify environment variables at runtime.
1366///
1367/// # Returns
1368///
1369/// a string owned by GLib that
1370///   must not be modified or freed.
1371#[doc(alias = "g_get_user_config_dir")]
1372#[doc(alias = "get_user_config_dir")]
1373pub fn user_config_dir() -> std::path::PathBuf {
1374    unsafe { from_glib_none(ffi::g_get_user_config_dir()) }
1375}
1376
1377/// Returns a base directory in which to access application data such
1378/// as icons that is customized for a particular user.
1379///
1380/// On UNIX platforms this is determined using the mechanisms described
1381/// in the
1382/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1383/// In this case the directory retrieved will be `XDG_DATA_HOME`.
1384///
1385/// On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
1386/// is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
1387/// opposed to roaming) application data is used instead. See the
1388/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
1389/// Note that in this case on Windows it will be the same
1390/// as what g_get_user_config_dir() returns.
1391///
1392/// The return value is cached and modifying it at runtime is not supported, as
1393/// it’s not thread-safe to modify environment variables at runtime.
1394///
1395/// # Returns
1396///
1397/// a string owned by GLib that must
1398///   not be modified or freed.
1399#[doc(alias = "g_get_user_data_dir")]
1400#[doc(alias = "get_user_data_dir")]
1401pub fn user_data_dir() -> std::path::PathBuf {
1402    unsafe { from_glib_none(ffi::g_get_user_data_dir()) }
1403}
1404
1405/// Gets the user name of the current user. The encoding of the returned
1406/// string is system-defined. On UNIX, it might be the preferred file name
1407/// encoding, or something else, and there is no guarantee that it is even
1408/// consistent on a machine. On Windows, it is always UTF-8.
1409///
1410/// # Returns
1411///
1412/// the user name of the current user.
1413#[doc(alias = "g_get_user_name")]
1414#[doc(alias = "get_user_name")]
1415pub fn user_name() -> std::ffi::OsString {
1416    unsafe { from_glib_none(ffi::g_get_user_name()) }
1417}
1418
1419/// Returns a directory that is unique to the current user on the local
1420/// system.
1421///
1422/// This is determined using the mechanisms described
1423/// in the
1424/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1425/// This is the directory
1426/// specified in the `XDG_RUNTIME_DIR` environment variable.
1427/// In the case that this variable is not set, we return the value of
1428/// g_get_user_cache_dir(), after verifying that it exists.
1429///
1430/// The return value is cached and modifying it at runtime is not supported, as
1431/// it’s not thread-safe to modify environment variables at runtime.
1432///
1433/// # Returns
1434///
1435/// a string owned by GLib that must not be
1436///     modified or freed.
1437#[doc(alias = "g_get_user_runtime_dir")]
1438#[doc(alias = "get_user_runtime_dir")]
1439pub fn user_runtime_dir() -> std::path::PathBuf {
1440    unsafe { from_glib_none(ffi::g_get_user_runtime_dir()) }
1441}
1442
1443/// Returns the full path of a special directory using its logical id.
1444///
1445/// On UNIX this is done using the XDG special user directories.
1446/// For compatibility with existing practise, [`UserDirectory::DirectoryDesktop`][crate::UserDirectory::DirectoryDesktop]
1447/// falls back to `$HOME/Desktop` when XDG special user directories have
1448/// not been set up.
1449///
1450/// Depending on the platform, the user might be able to change the path
1451/// of the special directory without requiring the session to restart; GLib
1452/// will not reflect any change once the special directories are loaded.
1453/// ## `directory`
1454/// the logical id of special directory
1455///
1456/// # Returns
1457///
1458/// the path to the specified special
1459///   directory, or [`None`] if the logical id was not found. The returned string is
1460///   owned by GLib and should not be modified or freed.
1461#[doc(alias = "g_get_user_special_dir")]
1462#[doc(alias = "get_user_special_dir")]
1463pub fn user_special_dir(directory: UserDirectory) -> Option<std::path::PathBuf> {
1464    unsafe { from_glib_none(ffi::g_get_user_special_dir(directory.into_glib())) }
1465}
1466
1467/// Returns a base directory in which to store state files specific to
1468/// particular user.
1469///
1470/// On UNIX platforms this is determined using the mechanisms described
1471/// in the
1472/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
1473/// In this case the directory retrieved will be `XDG_STATE_HOME`.
1474///
1475/// On Windows it follows XDG Base Directory Specification if `XDG_STATE_HOME` is defined.
1476/// If `XDG_STATE_HOME` is undefined, the folder to use for local (as opposed
1477/// to roaming) application data is used instead. See the
1478/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
1479/// Note that in this case on Windows it will be the same
1480/// as what g_get_user_data_dir() returns.
1481///
1482/// The return value is cached and modifying it at runtime is not supported, as
1483/// it’s not thread-safe to modify environment variables at runtime.
1484///
1485/// # Returns
1486///
1487/// a string owned by GLib that
1488///   must not be modified or freed.
1489#[cfg(feature = "v2_72")]
1490#[cfg_attr(docsrs, doc(cfg(feature = "v2_72")))]
1491#[doc(alias = "g_get_user_state_dir")]
1492#[doc(alias = "get_user_state_dir")]
1493pub fn user_state_dir() -> std::path::PathBuf {
1494    unsafe { from_glib_none(ffi::g_get_user_state_dir()) }
1495}
1496
1497/// Returns the value of an environment variable.
1498///
1499/// On UNIX, the name and value are byte strings which might or might not
1500/// be in some consistent character set and encoding. On Windows, they are
1501/// in UTF-8.
1502/// On Windows, in case the environment variable's value contains
1503/// references to other environment variables, they are expanded.
1504/// ## `variable`
1505/// the environment variable to get
1506///
1507/// # Returns
1508///
1509/// the value of the environment variable, or [`None`] if
1510///     the environment variable is not found. The returned string
1511///     may be overwritten by the next call to g_getenv(), g_setenv()
1512///     or g_unsetenv().
1513#[doc(alias = "g_getenv")]
1514pub fn getenv(variable: impl AsRef<std::ffi::OsStr>) -> Option<std::ffi::OsString> {
1515    unsafe { from_glib_none(ffi::g_getenv(variable.as_ref().to_glib_none().0)) }
1516}
1517
1518/// Tests if @hostname contains segments with an ASCII-compatible
1519/// encoding of an Internationalized Domain Name. If this returns
1520/// [`true`], you should decode the hostname with g_hostname_to_unicode()
1521/// before displaying it to the user.
1522///
1523/// Note that a hostname might contain a mix of encoded and unencoded
1524/// segments, and so it is possible for g_hostname_is_non_ascii() and
1525/// g_hostname_is_ascii_encoded() to both return [`true`] for a name.
1526/// ## `hostname`
1527/// a hostname
1528///
1529/// # Returns
1530///
1531/// [`true`] if @hostname contains any ASCII-encoded
1532/// segments.
1533#[doc(alias = "g_hostname_is_ascii_encoded")]
1534pub fn hostname_is_ascii_encoded(hostname: &str) -> bool {
1535    unsafe { from_glib(ffi::g_hostname_is_ascii_encoded(hostname.to_glib_none().0)) }
1536}
1537
1538/// Tests if @hostname is the string form of an IPv4 or IPv6 address.
1539/// (Eg, "192.168.0.1".)
1540///
1541/// Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).
1542/// ## `hostname`
1543/// a hostname (or IP address in string form)
1544///
1545/// # Returns
1546///
1547/// [`true`] if @hostname is an IP address
1548#[doc(alias = "g_hostname_is_ip_address")]
1549pub fn hostname_is_ip_address(hostname: &str) -> bool {
1550    unsafe { from_glib(ffi::g_hostname_is_ip_address(hostname.to_glib_none().0)) }
1551}
1552
1553/// Tests if @hostname contains Unicode characters. If this returns
1554/// [`true`], you need to encode the hostname with g_hostname_to_ascii()
1555/// before using it in non-IDN-aware contexts.
1556///
1557/// Note that a hostname might contain a mix of encoded and unencoded
1558/// segments, and so it is possible for g_hostname_is_non_ascii() and
1559/// g_hostname_is_ascii_encoded() to both return [`true`] for a name.
1560/// ## `hostname`
1561/// a hostname
1562///
1563/// # Returns
1564///
1565/// [`true`] if @hostname contains any non-ASCII characters
1566#[doc(alias = "g_hostname_is_non_ascii")]
1567pub fn hostname_is_non_ascii(hostname: &str) -> bool {
1568    unsafe { from_glib(ffi::g_hostname_is_non_ascii(hostname.to_glib_none().0)) }
1569}
1570
1571/// Converts @hostname to its canonical ASCII form; an ASCII-only
1572/// string containing no uppercase letters and not ending with a
1573/// trailing dot.
1574/// ## `hostname`
1575/// a valid UTF-8 or ASCII hostname
1576///
1577/// # Returns
1578///
1579/// an ASCII hostname, which must be freed,
1580///    or [`None`] if @hostname is in some way invalid.
1581#[doc(alias = "g_hostname_to_ascii")]
1582pub fn hostname_to_ascii(hostname: &str) -> Option<crate::GString> {
1583    unsafe { from_glib_full(ffi::g_hostname_to_ascii(hostname.to_glib_none().0)) }
1584}
1585
1586/// Converts @hostname to its canonical presentation form; a UTF-8
1587/// string in Unicode normalization form C, containing no uppercase
1588/// letters, no forbidden characters, and no ASCII-encoded segments,
1589/// and not ending with a trailing dot.
1590///
1591/// Of course if @hostname is not an internationalized hostname, then
1592/// the canonical presentation form will be entirely ASCII.
1593/// ## `hostname`
1594/// a valid UTF-8 or ASCII hostname
1595///
1596/// # Returns
1597///
1598/// a UTF-8 hostname, which must be freed,
1599///    or [`None`] if @hostname is in some way invalid.
1600#[doc(alias = "g_hostname_to_unicode")]
1601pub fn hostname_to_unicode(hostname: &str) -> Option<crate::GString> {
1602    unsafe { from_glib_full(ffi::g_hostname_to_unicode(hostname.to_glib_none().0)) }
1603}
1604
1605/// Gets the names of all variables set in the environment.
1606///
1607/// Programs that want to be portable to Windows should typically use
1608/// this function and g_getenv() instead of using the environ array
1609/// from the C library directly. On Windows, the strings in the environ
1610/// array are in system codepage encoding, while in most of the typical
1611/// use cases for environment variables in GLib-using programs you want
1612/// the UTF-8 encoding that this function and g_getenv() provide.
1613///
1614/// # Returns
1615///
1616///
1617///     a [`None`]-terminated list of strings which must be freed with
1618///     g_strfreev().
1619#[doc(alias = "g_listenv")]
1620pub fn listenv() -> Vec<std::ffi::OsString> {
1621    unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_listenv()) }
1622}
1623
1624/// Returns the currently firing source for this thread.
1625///
1626/// # Returns
1627///
1628/// the currently firing source, or `NULL`
1629///   if none is firing
1630#[doc(alias = "g_main_current_source")]
1631pub fn main_current_source() -> Option<Source> {
1632    unsafe { from_glib_none(ffi::g_main_current_source()) }
1633}
1634
1635/// mem);
1636///           g_free (block);
1637///           free_list = g_list_delete_link (free_list, l);
1638///         }
1639///
1640///       l = next;
1641///     }
1642///   }
1643/// ```text
1644///
1645/// There is a temptation to use [`main_depth()`][crate::main_depth()] to solve
1646/// problems with reentrancy. For instance, while waiting for data
1647/// to be received from the network in response to a menu item,
1648/// the menu item might be selected again. It might seem that
1649/// one could make the menu item’s callback return immediately
1650/// and do nothing if [`main_depth()`][crate::main_depth()] returns a value greater than 1.
1651/// However, this should be avoided since the user then sees selecting
1652/// the menu item do nothing. Furthermore, you’ll find yourself adding
1653/// these checks all over your code, since there are doubtless many,
1654/// many things that the user could do. Instead, you can use the
1655/// following techniques:
1656///
1657/// 1. Use `gtk_widget_set_sensitive()` or modal dialogs to prevent
1658///    the user from interacting with elements while the main
1659///    loop is recursing.
1660///
1661/// 2. Avoid main loop recursion in situations where you can’t handle
1662///    arbitrary  callbacks. Instead, structure your code so that you
1663///    simply return to the main loop and then get called again when
1664///    there is more work to do.
1665///
1666/// # Returns
1667///
1668/// the main loop recursion level in the current thread
1669#[doc(alias = "g_main_depth")]
1670pub fn main_depth() -> i32 {
1671    unsafe { ffi::g_main_depth() }
1672}
1673
1674/// #x1f; for all control sequences
1675/// except for tabstop, newline and carriage return.  The character
1676/// references in this range are not valid XML 1.0, but they are
1677/// valid XML 1.1 and will be accepted by the GMarkup parser.
1678/// ## `text`
1679/// some valid UTF-8 text
1680/// ## `length`
1681/// length of @text in bytes, or -1 if the text is nul-terminated
1682///
1683/// # Returns
1684///
1685/// a newly allocated string with the escaped text
1686#[doc(alias = "g_markup_escape_text")]
1687pub fn markup_escape_text(text: &str) -> crate::GString {
1688    let length = text.len() as _;
1689    unsafe { from_glib_full(ffi::g_markup_escape_text(text.to_glib_none().0, length)) }
1690}
1691
1692/// Create a directory if it doesn't already exist. Create intermediate
1693/// parent directories as needed, too.
1694/// ## `pathname`
1695/// a pathname in the GLib file name encoding
1696/// ## `mode`
1697/// permissions to use for newly created directories
1698///
1699/// # Returns
1700///
1701/// 0 if the directory already exists, or was successfully
1702/// created. Returns -1 if an error occurred, with errno set.
1703#[doc(alias = "g_mkdir_with_parents")]
1704pub fn mkdir_with_parents(pathname: impl AsRef<std::path::Path>, mode: i32) -> i32 {
1705    unsafe { ffi::g_mkdir_with_parents(pathname.as_ref().to_glib_none().0, mode) }
1706}
1707
1708///
1709///
1710/// static void
1711/// log_handler (const gchar   *log_domain,
1712///              GLogLevelFlags log_level,
1713///              const gchar   *message,
1714///              gpointer       user_data)
1715/// {
1716///   g_log_default_handler (log_domain, log_level, message, user_data);
1717///
1718///   g_on_error_query (MY_PROGRAM_NAME);
1719/// }
1720///
1721/// int
1722/// main (int argc, char *argv[])
1723/// {
1724///   g_log_set_handler (MY_LOG_DOMAIN,
1725///                      G_LOG_LEVEL_WARNING |
1726///                      G_LOG_LEVEL_ERROR |
1727///                      G_LOG_LEVEL_CRITICAL,
1728///                      log_handler,
1729///                      NULL);
1730///   ...
1731/// ]|
1732///
1733/// If "[E]xit" is selected, the application terminates with a call
1734/// to _exit(0).
1735///
1736/// If "[S]tack" trace is selected, g_on_error_stack_trace() is called.
1737/// This invokes gdb, which attaches to the current process and shows
1738/// a stack trace. The prompt is then shown again.
1739///
1740/// If "[P]roceed" is selected, the function returns.
1741///
1742/// This function may cause different actions on non-UNIX platforms.
1743///
1744/// On Windows consider using the `G_DEBUGGER` environment
1745/// variable (see [Running GLib Applications](running.html)) and
1746/// calling g_on_error_stack_trace() instead.
1747/// ## `prg_name`
1748/// the program name, needed by gdb for the "[S]tack trace"
1749///     option. If @prg_name is [`None`], g_get_prgname() is called to get
1750///     the program name (which will work correctly if gdk_init() or
1751///     gtk_init() has been called)
1752#[doc(alias = "g_on_error_query")]
1753pub fn on_error_query(prg_name: &str) {
1754    unsafe {
1755        ffi::g_on_error_query(prg_name.to_glib_none().0);
1756    }
1757}
1758
1759/// Invokes gdb, which attaches to the current process and shows a
1760/// stack trace. Called by g_on_error_query() when the "[S]tack trace"
1761/// option is selected. You can get the current process's program name
1762/// with g_get_prgname(), assuming that you have called gtk_init() or
1763/// gdk_init().
1764///
1765/// This function may cause different actions on non-UNIX platforms.
1766///
1767/// When running on Windows, this function is *not* called by
1768/// g_on_error_query(). If called directly, it will raise an
1769/// exception, which will crash the program. If the `G_DEBUGGER` environment
1770/// variable is set, a debugger will be invoked to attach and
1771/// handle that exception (see [Running GLib Applications](running.html)).
1772/// ## `prg_name`
1773/// the program name, needed by gdb for the
1774///   "[S]tack trace" option, or `NULL` to use a default string
1775#[doc(alias = "g_on_error_stack_trace")]
1776pub fn on_error_stack_trace(prg_name: Option<&str>) {
1777    unsafe {
1778        ffi::g_on_error_stack_trace(prg_name.to_glib_none().0);
1779    }
1780}
1781
1782/// Gets the last component of the filename.
1783///
1784/// If @file_name ends with a directory separator it gets the component
1785/// before the last slash. If @file_name consists only of directory
1786/// separators (and on Windows, possibly a drive letter), a single
1787/// separator is returned. If @file_name is empty, it gets ".".
1788/// ## `file_name`
1789/// the name of the file
1790///
1791/// # Returns
1792///
1793/// a newly allocated string
1794///   containing the last component of the filename
1795#[doc(alias = "g_path_get_basename")]
1796#[allow(dead_code)]
1797pub(crate) fn path_get_basename(file_name: impl AsRef<std::path::Path>) -> std::path::PathBuf {
1798    unsafe {
1799        from_glib_full(ffi::g_path_get_basename(
1800            file_name.as_ref().to_glib_none().0,
1801        ))
1802    }
1803}
1804
1805/// Gets the directory components of a file name. For example, the directory
1806/// component of `/usr/bin/test` is `/usr/bin`. The directory component of `/`
1807/// is `/`.
1808///
1809/// If the file name has no directory components "." is returned.
1810/// The returned string should be freed when no longer needed.
1811/// ## `file_name`
1812/// the name of the file
1813///
1814/// # Returns
1815///
1816/// the directory components of the file
1817#[doc(alias = "g_path_get_dirname")]
1818#[allow(dead_code)]
1819pub(crate) fn path_get_dirname(file_name: impl AsRef<std::path::Path>) -> std::path::PathBuf {
1820    unsafe { from_glib_full(ffi::g_path_get_dirname(file_name.as_ref().to_glib_none().0)) }
1821}
1822
1823//#[doc(alias = "g_poll")]
1824//pub fn poll(fds: /*Ignored*/&mut PollFD, nfds: u32, timeout: i32) -> i32 {
1825//    unsafe { TODO: call ffi:g_poll() }
1826//}
1827
1828/// Returns a random #gdouble equally distributed over the range [0..1).
1829///
1830/// # Returns
1831///
1832/// a random number
1833#[doc(alias = "g_random_double")]
1834pub fn random_double() -> f64 {
1835    unsafe { ffi::g_random_double() }
1836}
1837
1838/// Returns a random #gdouble equally distributed over the range
1839/// [@begin..@end).
1840/// ## `begin`
1841/// lower closed bound of the interval
1842/// ## `end`
1843/// upper open bound of the interval
1844///
1845/// # Returns
1846///
1847/// a random number
1848#[doc(alias = "g_random_double_range")]
1849pub fn random_double_range(begin: f64, end: f64) -> f64 {
1850    unsafe { ffi::g_random_double_range(begin, end) }
1851}
1852
1853/// Return a random #guint32 equally distributed over the range
1854/// [0..2^32-1].
1855///
1856/// # Returns
1857///
1858/// a random number
1859#[doc(alias = "g_random_int")]
1860pub fn random_int() -> u32 {
1861    unsafe { ffi::g_random_int() }
1862}
1863
1864/// Returns a random #gint32 equally distributed over the range
1865/// [@begin..@end-1].
1866/// ## `begin`
1867/// lower closed bound of the interval
1868/// ## `end`
1869/// upper open bound of the interval
1870///
1871/// # Returns
1872///
1873/// a random number
1874#[doc(alias = "g_random_int_range")]
1875pub fn random_int_range(begin: i32, end: i32) -> i32 {
1876    unsafe { ffi::g_random_int_range(begin, end) }
1877}
1878
1879/// Sets the seed for the global random number generator, which is used
1880/// by the g_random_* functions, to @seed.
1881/// ## `seed`
1882/// a value to reinitialize the global random number generator
1883#[doc(alias = "g_random_set_seed")]
1884pub fn random_set_seed(seed: u32) {
1885    unsafe {
1886        ffi::g_random_set_seed(seed);
1887    }
1888}
1889
1890/// Resets the cache used for g_get_user_special_dir(), so
1891/// that the latest on-disk version is used. Call this only
1892/// if you just changed the data on disk yourself.
1893///
1894/// Due to thread safety issues this may cause leaking of strings
1895/// that were previously returned from g_get_user_special_dir()
1896/// that can't be freed. We ensure to only leak the data for
1897/// the directories that actually changed value though.
1898#[doc(alias = "g_reload_user_special_dirs_cache")]
1899pub fn reload_user_special_dirs_cache() {
1900    unsafe {
1901        ffi::g_reload_user_special_dirs_cache();
1902    }
1903}
1904
1905/// Sets a human-readable name for the application. This name should be
1906/// localized if possible, and is intended for display to the user.
1907/// Contrast with g_set_prgname(), which sets a non-localized name.
1908/// g_set_prgname() will be called automatically by gtk_init(),
1909/// but g_set_application_name() will not.
1910///
1911/// Note that for thread safety reasons, this function can only
1912/// be called once.
1913///
1914/// The application name will be used in contexts such as error messages,
1915/// or when displaying an application's name in the task list.
1916/// ## `application_name`
1917/// localized name of the application
1918#[doc(alias = "g_set_application_name")]
1919pub fn set_application_name(application_name: &str) {
1920    unsafe {
1921        ffi::g_set_application_name(application_name.to_glib_none().0);
1922    }
1923}
1924
1925/// Sets an environment variable. On UNIX, both the variable's name and
1926/// value can be arbitrary byte strings, except that the variable's name
1927/// cannot contain '='. On Windows, they should be in UTF-8.
1928///
1929/// Note that on some systems, when variables are overwritten, the memory
1930/// used for the previous variables and its value isn't reclaimed.
1931///
1932/// You should be mindful of the fact that environment variable handling
1933/// in UNIX is not thread-safe, and your program may crash if one thread
1934/// calls g_setenv() while another thread is calling getenv(). (And note
1935/// that many functions, such as gettext(), call getenv() internally.)
1936/// This function is only safe to use at the very start of your program,
1937/// before creating any other threads (or creating objects that create
1938/// worker threads of their own).
1939///
1940/// If you need to set up the environment for a child process, you can
1941/// use g_get_environ() to get an environment array, modify that with
1942/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
1943/// array directly to execvpe(), g_spawn_async(), or the like.
1944/// ## `variable`
1945/// the environment variable to set, must not
1946///     contain '='.
1947/// ## `value`
1948/// the value for to set the variable to.
1949/// ## `overwrite`
1950/// whether to change the variable if it already exists.
1951///
1952/// # Returns
1953///
1954/// [`false`] if the environment variable couldn't be set.
1955#[doc(alias = "g_setenv")]
1956pub unsafe fn setenv(
1957    variable: impl AsRef<std::ffi::OsStr>,
1958    value: impl AsRef<std::ffi::OsStr>,
1959    overwrite: bool,
1960) -> Result<(), crate::error::BoolError> {
1961    unsafe {
1962        crate::result_from_gboolean!(
1963            ffi::g_setenv(
1964                variable.as_ref().to_glib_none().0,
1965                value.as_ref().to_glib_none().0,
1966                overwrite.into_glib()
1967            ),
1968            "Failed to set environment variable"
1969        )
1970    }
1971}
1972
1973/// Parses a command line into an argument vector, in much the same way
1974/// the shell would, but without many of the expansions the shell would
1975/// perform (variable expansion, globs, operators, filename expansion,
1976/// etc. are not supported).
1977///
1978/// The results are defined to be the same as those you would get from
1979/// a UNIX98 `/bin/sh`, as long as the input contains none of the
1980/// unsupported shell expansions. If the input does contain such expansions,
1981/// they are passed through literally.
1982///
1983/// Possible errors are those from the `G_SHELL_ERROR` domain.
1984///
1985/// In particular, if @command_line is an empty string (or a string containing
1986/// only whitespace), `G_SHELL_ERROR_EMPTY_STRING` will be returned. It’s
1987/// guaranteed that @argvp will be a non-empty array if this function returns
1988/// successfully.
1989///
1990/// When constructing @command_line, quote any filenames or potentially
1991/// untrusted input using [`shell_quote()`][crate::shell_quote()].
1992///
1993/// Free the returned vector with g_strfreev().
1994/// ## `command_line`
1995/// command line to parse
1996///
1997/// # Returns
1998///
1999/// [`true`] on success, [`false`] if error set
2000///
2001/// ## `argvp`
2002///
2003///   return location for array of args
2004#[doc(alias = "g_shell_parse_argv")]
2005pub fn shell_parse_argv(
2006    command_line: impl AsRef<std::ffi::OsStr>,
2007) -> Result<Vec<std::ffi::OsString>, crate::Error> {
2008    unsafe {
2009        let mut argcp = std::mem::MaybeUninit::uninit();
2010        let mut argvp = std::ptr::null_mut();
2011        let mut error = std::ptr::null_mut();
2012        let is_ok = ffi::g_shell_parse_argv(
2013            command_line.as_ref().to_glib_none().0,
2014            argcp.as_mut_ptr(),
2015            &mut argvp,
2016            &mut error,
2017        );
2018        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
2019        if error.is_null() {
2020            Ok(FromGlibContainer::from_glib_full_num(
2021                argvp,
2022                argcp.assume_init() as _,
2023            ))
2024        } else {
2025            Err(from_glib_full(error))
2026        }
2027    }
2028}
2029
2030/// Quotes a string so that the shell (/bin/sh) will interpret the
2031/// quoted string to mean @unquoted_string.
2032///
2033/// If you pass a filename or other untrusted input to [`shell_parse_argv()`][crate::shell_parse_argv()],
2034/// you should first quote it with this function. This is sufficient to ensure
2035/// untrusted input cannot ‘break out’ of the quotes. Beware: this only works
2036/// because [`shell_parse_argv()`][crate::shell_parse_argv()] is not a real Unix shell. Quoting untrusted
2037/// input is not an adequate security mechanism when using a real shell.
2038///
2039/// The return value must be freed with g_free().
2040///
2041/// The quoting style used is undefined (single or double quotes may be
2042/// used).
2043/// ## `unquoted_string`
2044/// a literal string
2045///
2046/// # Returns
2047///
2048/// quoted string
2049#[doc(alias = "g_shell_quote")]
2050pub fn shell_quote(unquoted_string: impl AsRef<std::ffi::OsStr>) -> std::ffi::OsString {
2051    unsafe {
2052        from_glib_full(ffi::g_shell_quote(
2053            unquoted_string.as_ref().to_glib_none().0,
2054        ))
2055    }
2056}
2057
2058/// Unquotes a string as the shell (/bin/sh) would.
2059///
2060/// This function only handles quotes; if a string contains file globs,
2061/// arithmetic operators, variables, backticks, redirections, or other
2062/// special-to-the-shell features, the result will be different from the
2063/// result a real shell would produce (the variables, backticks, etc.
2064/// will be passed through literally instead of being expanded).
2065///
2066/// This function is guaranteed to succeed if applied to the result of
2067/// g_shell_quote(). If it fails, it returns [`None`] and sets the
2068/// error.
2069///
2070/// The @quoted_string need not actually contain quoted or escaped text;
2071/// g_shell_unquote() simply goes through the string and unquotes/unescapes
2072/// anything that the shell would. Both single and double quotes are
2073/// handled, as are escapes including escaped newlines.
2074///
2075/// The return value must be freed with g_free().
2076///
2077/// Possible errors are in the `G_SHELL_ERROR` domain.
2078///
2079/// Shell quoting rules are a bit strange. Single quotes preserve the
2080/// literal string exactly. escape sequences are not allowed; not even
2081/// `\'` - if you want a `'` in the quoted text, you have to do something
2082/// like `'foo'\''bar'`. Double quotes allow `$`, **⚠️ The following code is in , `"`, `\`, and ⚠️**
2083///
2084/// ```, `"`, `\`, and
2085/// newline to be escaped with backslash. Otherwise double quotes
2086/// preserve things literally.
2087/// ## `quoted_string`
2088/// shell-quoted string
2089///
2090/// # Returns
2091///
2092/// an unquoted string
2093#[doc(alias = "g_shell_unquote")]
2094pub fn shell_unquote(
2095    quoted_string: impl AsRef<std::ffi::OsStr>,
2096) -> Result<std::ffi::OsString, crate::Error> {
2097    unsafe {
2098        let mut error = std::ptr::null_mut();
2099        let ret = ffi::g_shell_unquote(quoted_string.as_ref().to_glib_none().0, &mut error);
2100        if error.is_null() {
2101            Ok(from_glib_full(ret))
2102        } else {
2103            Err(from_glib_full(error))
2104        }
2105    }
2106}
2107
2108//#[cfg(feature = "v2_82")]
2109//#[cfg_attr(docsrs, doc(cfg(feature = "v2_82")))]
2110//#[doc(alias = "g_sort_array")]
2111//pub fn sort_array(array: /*Unimplemented*/&[&Basic: Pointer], element_size: usize, compare_func: /*Unimplemented*/FnMut(/*Unimplemented*/Option<Basic: Pointer>, /*Unimplemented*/Option<Basic: Pointer>) -> i32, user_data: /*Unimplemented*/Option<Basic: Pointer>) {
2112//    unsafe { TODO: call ffi:g_sort_array() }
2113//}
2114
2115/// Gets the smallest prime number from a built-in array of primes which
2116/// is larger than @num. This is used within GLib to calculate the optimum
2117/// size of a #GHashTable.
2118///
2119/// The built-in array of primes ranges from 11 to 13845163 such that
2120/// each prime is approximately 1.5-2 times the previous prime.
2121/// ## `num`
2122/// a #guint
2123///
2124/// # Returns
2125///
2126/// the smallest prime number from a built-in array of primes
2127///     which is larger than @num
2128#[doc(alias = "g_spaced_primes_closest")]
2129pub fn spaced_primes_closest(num: u32) -> u32 {
2130    unsafe { ffi::g_spaced_primes_closest(num) }
2131}
2132
2133/// Executes a child program asynchronously.
2134///
2135/// See g_spawn_async_with_pipes_and_fds() for a full description; this function
2136/// simply calls the g_spawn_async_with_pipes() without any pipes, which in turn
2137/// calls g_spawn_async_with_pipes_and_fds().
2138///
2139/// You should call g_spawn_close_pid() on the returned child process
2140/// reference when you don't need it any more.
2141///
2142/// If you are writing a GTK application, and the program you are spawning is a
2143/// graphical application too, then to ensure that the spawned program opens its
2144/// windows on the right screen, you may want to use #GdkAppLaunchContext,
2145/// #GAppLaunchContext, or set the `DISPLAY` environment variable.
2146///
2147/// Note that the returned @child_pid on Windows is a handle to the child
2148/// process and not its identifier. Process handles and process identifiers
2149/// are different concepts on Windows.
2150/// ## `working_directory`
2151/// child's current working
2152///     directory, or [`None`] to inherit parent's
2153/// ## `argv`
2154///
2155///     child's argument vector
2156/// ## `envp`
2157///
2158///     child's environment, or [`None`] to inherit parent's
2159/// ## `flags`
2160/// flags from #GSpawnFlags
2161/// ## `child_setup`
2162/// function to run
2163///     in the child just before `exec()`
2164///
2165/// # Returns
2166///
2167/// [`true`] on success, [`false`] if error is set
2168///
2169/// ## `child_pid`
2170/// return location for child process reference, or [`None`]
2171#[doc(alias = "g_spawn_async")]
2172pub fn spawn_async(
2173    working_directory: Option<impl AsRef<std::path::Path>>,
2174    argv: &[&std::path::Path],
2175    envp: &[&std::path::Path],
2176    flags: SpawnFlags,
2177    child_setup: Option<Box_<dyn FnOnce() + 'static>>,
2178) -> Result<Pid, crate::Error> {
2179    let child_setup_data: Box_<Option<Box_<dyn FnOnce() + 'static>>> = Box_::new(child_setup);
2180    unsafe extern "C" fn child_setup_func(data: ffi::gpointer) {
2181        unsafe {
2182            let callback = Box_::from_raw(data as *mut Option<Box_<dyn FnOnce() + 'static>>);
2183            let callback = (*callback).expect("cannot get closure...");
2184            callback()
2185        }
2186    }
2187    let child_setup = if child_setup_data.is_some() {
2188        Some(child_setup_func as _)
2189    } else {
2190        None
2191    };
2192    let super_callback0: Box_<Option<Box_<dyn FnOnce() + 'static>>> = child_setup_data;
2193    unsafe {
2194        let mut child_pid = std::mem::MaybeUninit::uninit();
2195        let mut error = std::ptr::null_mut();
2196        let is_ok = ffi::g_spawn_async(
2197            working_directory
2198                .as_ref()
2199                .map(|p| p.as_ref())
2200                .to_glib_none()
2201                .0,
2202            argv.to_glib_none().0,
2203            envp.to_glib_none().0,
2204            flags.into_glib(),
2205            child_setup,
2206            Box_::into_raw(super_callback0) as *mut _,
2207            child_pid.as_mut_ptr(),
2208            &mut error,
2209        );
2210        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
2211        if error.is_null() {
2212            Ok(from_glib(child_pid.assume_init()))
2213        } else {
2214            Err(from_glib_full(error))
2215        }
2216    }
2217}
2218
2219//#[cfg(feature = "v2_68")]
2220//#[cfg_attr(docsrs, doc(cfg(feature = "v2_68")))]
2221//#[doc(alias = "g_spawn_async_with_pipes_and_fds")]
2222//pub fn spawn_async_with_pipes_and_fds(working_directory: Option<impl AsRef<std::path::Path>>, argv: &[&std::path::Path], envp: &[&std::path::Path], flags: SpawnFlags, child_setup: Option<Box_<dyn FnOnce() + 'static>>, stdin_fd: i32, stdout_fd: i32, stderr_fd: i32, source_fds: &[i32], target_fds: &[i32], n_fds: usize) -> Result<(Pid, i32, i32, i32), crate::Error> {
2223//    unsafe { TODO: call ffi:g_spawn_async_with_pipes_and_fds() }
2224//}
2225
2226/// An old name for g_spawn_check_wait_status(), deprecated because its
2227/// name is misleading.
2228///
2229/// Despite the name of the function, @wait_status must be the wait status
2230/// as returned by g_spawn_sync(), g_subprocess_get_status(), `waitpid()`,
2231/// etc. On Unix platforms, it is incorrect for it to be the exit status
2232/// as passed to `exit()` or returned by g_subprocess_get_exit_status() or
2233/// `WEXITSTATUS()`.
2234///
2235/// # Deprecated since 2.70
2236///
2237/// Use g_spawn_check_wait_status() instead, and check whether your code is conflating wait and exit statuses.
2238/// ## `wait_status`
2239/// A status as returned from g_spawn_sync()
2240///
2241/// # Returns
2242///
2243/// [`true`] if child exited successfully, [`false`] otherwise (and
2244///     @error will be set)
2245#[cfg_attr(feature = "v2_70", deprecated = "Since 2.70")]
2246#[allow(deprecated)]
2247#[doc(alias = "g_spawn_check_exit_status")]
2248pub fn spawn_check_exit_status(wait_status: i32) -> Result<(), crate::Error> {
2249    unsafe {
2250        let mut error = std::ptr::null_mut();
2251        let is_ok = ffi::g_spawn_check_exit_status(wait_status, &mut error);
2252        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
2253        if error.is_null() {
2254            Ok(())
2255        } else {
2256            Err(from_glib_full(error))
2257        }
2258    }
2259}
2260
2261/// Set @error if @wait_status indicates the child exited abnormally
2262/// (e.g. with a nonzero exit code, or via a fatal signal).
2263///
2264/// The g_spawn_sync() and g_child_watch_add() family of APIs return the
2265/// status of subprocesses encoded in a platform-specific way.
2266/// On Unix, this is guaranteed to be in the same format waitpid() returns,
2267/// and on Windows it is guaranteed to be the result of GetExitCodeProcess().
2268///
2269/// Prior to the introduction of this function in GLib 2.34, interpreting
2270/// @wait_status required use of platform-specific APIs, which is problematic
2271/// for software using GLib as a cross-platform layer.
2272///
2273/// Additionally, many programs simply want to determine whether or not
2274/// the child exited successfully, and either propagate a #GError or
2275/// print a message to standard error. In that common case, this function
2276/// can be used. Note that the error message in @error will contain
2277/// human-readable information about the wait status.
2278///
2279/// The @domain and @code of @error have special semantics in the case
2280/// where the process has an "exit code", as opposed to being killed by
2281/// a signal. On Unix, this happens if WIFEXITED() would be true of
2282/// @wait_status. On Windows, it is always the case.
2283///
2284/// The special semantics are that the actual exit code will be the
2285/// code set in @error, and the domain will be `G_SPAWN_EXIT_ERROR`.
2286/// This allows you to differentiate between different exit codes.
2287///
2288/// If the process was terminated by some means other than an exit
2289/// status (for example if it was killed by a signal), the domain will be
2290/// `G_SPAWN_ERROR` and the code will be `G_SPAWN_ERROR_FAILED`.
2291///
2292/// This function just offers convenience; you can of course also check
2293/// the available platform via a macro such as `G_OS_UNIX`, and use
2294/// WIFEXITED() and WEXITSTATUS() on @wait_status directly. Do not attempt
2295/// to scan or parse the error message string; it may be translated and/or
2296/// change in future versions of GLib.
2297///
2298/// Prior to version 2.70, g_spawn_check_exit_status() provides the same
2299/// functionality, although under a misleading name.
2300/// ## `wait_status`
2301/// A platform-specific wait status as returned from g_spawn_sync()
2302///
2303/// # Returns
2304///
2305/// [`true`] if child exited successfully, [`false`] otherwise (and
2306///   @error will be set)
2307#[cfg(feature = "v2_70")]
2308#[cfg_attr(docsrs, doc(cfg(feature = "v2_70")))]
2309#[doc(alias = "g_spawn_check_wait_status")]
2310pub fn spawn_check_wait_status(wait_status: i32) -> Result<(), crate::Error> {
2311    unsafe {
2312        let mut error = std::ptr::null_mut();
2313        let is_ok = ffi::g_spawn_check_wait_status(wait_status, &mut error);
2314        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
2315        if error.is_null() {
2316            Ok(())
2317        } else {
2318            Err(from_glib_full(error))
2319        }
2320    }
2321}
2322
2323/// A simple version of g_spawn_async() that parses a command line with
2324/// g_shell_parse_argv() and passes it to g_spawn_async().
2325///
2326/// Filenames and potentially untrusted input in @command_line should be quoted
2327/// using [`shell_quote()`][crate::shell_quote()].
2328///
2329/// Runs a command line in the background. Unlike g_spawn_async(), the
2330/// [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] flag is enabled, other flags are not. Note
2331/// that [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] can have security implications, so
2332/// consider using g_spawn_async() directly if appropriate. Possible
2333/// errors are those from g_shell_parse_argv() and g_spawn_async().
2334///
2335/// The same concerns on Windows apply as for g_spawn_command_line_sync().
2336/// ## `command_line`
2337/// a command line
2338///
2339/// # Returns
2340///
2341/// [`true`] on success, [`false`] if error is set
2342#[cfg(unix)]
2343#[cfg_attr(docsrs, doc(cfg(unix)))]
2344#[doc(alias = "g_spawn_command_line_async")]
2345pub fn spawn_command_line_async(
2346    command_line: impl AsRef<std::ffi::OsStr>,
2347) -> Result<(), crate::Error> {
2348    unsafe {
2349        let mut error = std::ptr::null_mut();
2350        let is_ok =
2351            ffi::g_spawn_command_line_async(command_line.as_ref().to_glib_none().0, &mut error);
2352        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
2353        if error.is_null() {
2354            Ok(())
2355        } else {
2356            Err(from_glib_full(error))
2357        }
2358    }
2359}
2360
2361//#[doc(alias = "g_spawn_command_line_sync")]
2362//pub fn spawn_command_line_sync(command_line: impl AsRef<std::path::Path>, standard_output: Vec<u8>, standard_error: Vec<u8>) -> Result<i32, crate::Error> {
2363//    unsafe { TODO: call ffi:g_spawn_command_line_sync() }
2364//}
2365
2366//#[doc(alias = "g_spawn_sync")]
2367//pub fn spawn_sync(working_directory: Option<impl AsRef<std::path::Path>>, argv: &[&std::path::Path], envp: &[&std::path::Path], flags: SpawnFlags, child_setup: Option<&mut dyn FnMut()>, standard_output: Vec<u8>, standard_error: Vec<u8>) -> Result<i32, crate::Error> {
2368//    unsafe { TODO: call ffi:g_spawn_sync() }
2369//}
2370
2371//#[doc(alias = "g_stat")]
2372//pub fn stat(filename: impl AsRef<std::path::Path>, buf: /*Ignored*/&mut StatBuf) -> i32 {
2373//    unsafe { TODO: call ffi:g_stat() }
2374//}
2375
2376/// A wrapper for the POSIX unlink() function. The unlink() function
2377/// deletes a name from the filesystem. If this was the last link to the
2378/// file and no processes have it opened, the diskspace occupied by the
2379/// file is freed.
2380///
2381/// See your C library manual for more details about unlink(). Note
2382/// that on Windows, it is in general not possible to delete files that
2383/// are open to some process, or mapped into memory.
2384/// ## `filename`
2385/// a pathname in the GLib file name encoding
2386///     (UTF-8 on Windows)
2387///
2388/// # Returns
2389///
2390/// 0 if the name was successfully deleted, -1 if an error
2391///    occurred
2392#[doc(alias = "g_unlink")]
2393pub fn unlink(filename: impl AsRef<std::path::Path>) -> i32 {
2394    unsafe { ffi::g_unlink(filename.as_ref().to_glib_none().0) }
2395}
2396
2397/// Removes an environment variable from the environment.
2398///
2399/// Note that on some systems, when variables are overwritten, the
2400/// memory used for the previous variables and its value isn't reclaimed.
2401///
2402/// You should be mindful of the fact that environment variable handling
2403/// in UNIX is not thread-safe, and your program may crash if one thread
2404/// calls g_unsetenv() while another thread is calling getenv(). (And note
2405/// that many functions, such as gettext(), call getenv() internally.) This
2406/// function is only safe to use at the very start of your program, before
2407/// creating any other threads (or creating objects that create worker
2408/// threads of their own).
2409///
2410/// If you need to set up the environment for a child process, you can
2411/// use g_get_environ() to get an environment array, modify that with
2412/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
2413/// array directly to execvpe(), g_spawn_async(), or the like.
2414/// ## `variable`
2415/// the environment variable to remove, must
2416///     not contain '='
2417#[doc(alias = "g_unsetenv")]
2418pub unsafe fn unsetenv(variable: impl AsRef<std::ffi::OsStr>) {
2419    unsafe {
2420        ffi::g_unsetenv(variable.as_ref().to_glib_none().0);
2421    }
2422}
2423
2424/// Pauses the current thread for the given number of microseconds.
2425///
2426/// There are 1 million microseconds per second (represented by the
2427/// `G_USEC_PER_SEC` macro). g_usleep() may have limited precision,
2428/// depending on hardware and operating system; don't rely on the exact
2429/// length of the sleep.
2430/// ## `microseconds`
2431/// number of microseconds to pause
2432#[doc(alias = "g_usleep")]
2433pub fn usleep(microseconds: libc::c_ulong) {
2434    unsafe {
2435        ffi::g_usleep(microseconds);
2436    }
2437}
2438
2439/// Parses the string @str and verify if it is a UUID.
2440///
2441/// The function accepts the following syntax:
2442///
2443/// - simple forms (e.g. `f81d4fae-7dec-11d0-a765-00a0c91e6bf6`)
2444///
2445/// Note that hyphens are required within the UUID string itself,
2446/// as per the aforementioned RFC.
2447/// ## `str`
2448/// a string representing a UUID
2449///
2450/// # Returns
2451///
2452/// [`true`] if @str is a valid UUID, [`false`] otherwise.
2453#[doc(alias = "g_uuid_string_is_valid")]
2454pub fn uuid_string_is_valid(str: &str) -> bool {
2455    unsafe { from_glib(ffi::g_uuid_string_is_valid(str.to_glib_none().0)) }
2456}
2457
2458/// Generates a random UUID (RFC 4122 version 4) as a string. It has the same
2459/// randomness guarantees as #GRand, so must not be used for cryptographic
2460/// purposes such as key generation, nonces, salts or one-time pads.
2461///
2462/// # Returns
2463///
2464/// A string that should be freed with g_free().
2465#[doc(alias = "g_uuid_string_random")]
2466pub fn uuid_string_random() -> crate::GString {
2467    unsafe { from_glib_full(ffi::g_uuid_string_random()) }
2468}