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 ffi, translate::*, Bytes, ChecksumType, Error, FileTest, FormatSizeFlags, Pid, Source,
10 SpawnFlags, UserDirectory,
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// rustdoc-stripper-ignore-next-stop
38/// A wrapper for the POSIX access() function. This function is used to
39/// test a pathname for one or several of read, write or execute
40/// permissions, or just existence.
41///
42/// On Windows, the file protection mechanism is not at all POSIX-like,
43/// and the underlying function in the C library only checks the
44/// FAT-style READONLY attribute, and does not look at the ACL of a
45/// file at all. This function is this in practise almost useless on
46/// Windows. Software that needs to handle file permissions on Windows
47/// more exactly should use the Win32 API.
48///
49/// See your C library manual for more details about access().
50/// ## `filename`
51/// a pathname in the GLib file name encoding
52/// (UTF-8 on Windows)
53/// ## `mode`
54/// as in access()
55///
56/// # Returns
57///
58/// zero if the pathname refers to an existing file system
59/// object that has all the tested permissions, or -1 otherwise
60/// or on error.
61#[doc(alias = "g_access")]
62pub fn access(filename: impl AsRef<std::path::Path>, mode: i32) -> i32 {
63 unsafe { ffi::g_access(filename.as_ref().to_glib_none().0, mode) }
64}
65
66/// Decode a sequence of Base-64 encoded text into binary data. Note
67/// that the returned binary data is not necessarily zero-terminated,
68/// so it should not be used as a character string.
69/// ## `text`
70/// zero-terminated string with base64 text to decode
71///
72/// # Returns
73///
74///
75/// newly allocated buffer containing the binary data
76/// that @text represents. The returned buffer must
77/// be freed with g_free().
78// rustdoc-stripper-ignore-next-stop
79/// Decode a sequence of Base-64 encoded text into binary data. Note
80/// that the returned binary data is not necessarily zero-terminated,
81/// so it should not be used as a character string.
82/// ## `text`
83/// zero-terminated string with base64 text to decode
84///
85/// # Returns
86///
87///
88/// newly allocated buffer containing the binary data
89/// that @text represents. The returned buffer must
90/// be freed with g_free().
91#[doc(alias = "g_base64_decode")]
92pub fn base64_decode(text: &str) -> Vec<u8> {
93 unsafe {
94 let mut out_len = std::mem::MaybeUninit::uninit();
95 let ret = FromGlibContainer::from_glib_full_num(
96 ffi::g_base64_decode(text.to_glib_none().0, out_len.as_mut_ptr()),
97 out_len.assume_init() as _,
98 );
99 ret
100 }
101}
102
103//#[doc(alias = "g_base64_decode_inplace")]
104//pub fn base64_decode_inplace(text: /*Unimplemented*/Vec<u8>) -> u8 {
105// unsafe { TODO: call ffi:g_base64_decode_inplace() }
106//}
107
108//#[doc(alias = "g_base64_decode_step")]
109//pub fn base64_decode_step(in_: &[u8], out: Vec<u8>, state: &mut i32, save: &mut u32) -> usize {
110// unsafe { TODO: call ffi:g_base64_decode_step() }
111//}
112
113/// Encode a sequence of binary data into its Base-64 stringified
114/// representation.
115/// ## `data`
116/// the binary data to encode
117///
118/// # Returns
119///
120/// a newly allocated, zero-terminated Base-64
121/// encoded string representing @data. The returned string must
122/// be freed with g_free().
123// rustdoc-stripper-ignore-next-stop
124/// Encode a sequence of binary data into its Base-64 stringified
125/// representation.
126/// ## `data`
127/// the binary data to encode
128///
129/// # Returns
130///
131/// a newly allocated, zero-terminated Base-64
132/// encoded string representing @data. The returned string must
133/// be freed with g_free().
134#[doc(alias = "g_base64_encode")]
135pub fn base64_encode(data: &[u8]) -> crate::GString {
136 let len = data.len() as _;
137 unsafe { from_glib_full(ffi::g_base64_encode(data.to_glib_none().0, len)) }
138}
139
140//#[doc(alias = "g_base64_encode_close")]
141//pub fn base64_encode_close(break_lines: bool, out: Vec<u8>, state: &mut i32, save: &mut i32) -> usize {
142// unsafe { TODO: call ffi:g_base64_encode_close() }
143//}
144
145//#[doc(alias = "g_base64_encode_step")]
146//pub fn base64_encode_step(in_: &[u8], break_lines: bool, out: Vec<u8>, state: &mut i32, save: &mut i32) -> usize {
147// unsafe { TODO: call ffi:g_base64_encode_step() }
148//}
149
150/// Checks that the GLib library in use is compatible with the
151/// given version.
152///
153/// Generally you would pass in the constants `GLIB_MAJOR_VERSION`,
154/// `GLIB_MINOR_VERSION`, `GLIB_MICRO_VERSION` as the three arguments
155/// to this function; that produces a check that the library in use
156/// is compatible with the version of GLib the application or module
157/// was compiled against.
158///
159/// Compatibility is defined by two things: first the version
160/// of the running library is newer than the version
161/// `@required_major.required_minor.@required_micro`. Second
162/// the running library must be binary compatible with the
163/// version `@required_major.@required_minor.@required_micro`
164/// (same major version.)
165/// ## `required_major`
166/// the required major version
167/// ## `required_minor`
168/// the required minor version
169/// ## `required_micro`
170/// the required micro version
171///
172/// # Returns
173///
174/// [`None`] if the GLib library is
175/// compatible with the given version, or a string describing the
176/// version mismatch. The returned string is owned by GLib and must
177/// not be modified or freed.
178// rustdoc-stripper-ignore-next-stop
179/// Checks that the GLib library in use is compatible with the
180/// given version.
181///
182/// Generally you would pass in the constants `GLIB_MAJOR_VERSION`,
183/// `GLIB_MINOR_VERSION`, `GLIB_MICRO_VERSION` as the three arguments
184/// to this function; that produces a check that the library in use
185/// is compatible with the version of GLib the application or module
186/// was compiled against.
187///
188/// Compatibility is defined by two things: first the version
189/// of the running library is newer than the version
190/// `@required_major.required_minor.@required_micro`. Second
191/// the running library must be binary compatible with the
192/// version `@required_major.@required_minor.@required_micro`
193/// (same major version.)
194/// ## `required_major`
195/// the required major version
196/// ## `required_minor`
197/// the required minor version
198/// ## `required_micro`
199/// the required micro version
200///
201/// # Returns
202///
203/// [`None`] if the GLib library is
204/// compatible with the given version, or a string describing the
205/// version mismatch. The returned string is owned by GLib and must
206/// not be modified or freed.
207#[doc(alias = "glib_check_version")]
208pub fn check_version(
209 required_major: u32,
210 required_minor: u32,
211 required_micro: u32,
212) -> Option<crate::GString> {
213 unsafe {
214 from_glib_none(ffi::glib_check_version(
215 required_major,
216 required_minor,
217 required_micro,
218 ))
219 }
220}
221
222/// Computes the checksum for a binary @data. This is a
223/// convenience wrapper for g_checksum_new(), g_checksum_get_string()
224/// and g_checksum_free().
225///
226/// The hexadecimal string returned will be in lower case.
227/// ## `checksum_type`
228/// a #GChecksumType
229/// ## `data`
230/// binary blob to compute the digest of
231///
232/// # Returns
233///
234/// the digest of the binary data as a
235/// string in hexadecimal, or [`None`] if g_checksum_new() fails for
236/// @checksum_type. The returned string should be freed with g_free() when
237/// done using it.
238// rustdoc-stripper-ignore-next-stop
239/// Computes the checksum for a binary @data. This is a
240/// convenience wrapper for g_checksum_new(), g_checksum_get_string()
241/// and g_checksum_free().
242///
243/// The hexadecimal string returned will be in lower case.
244/// ## `checksum_type`
245/// a #GChecksumType
246/// ## `data`
247/// binary blob to compute the digest of
248///
249/// # Returns
250///
251/// the digest of the binary data as a
252/// string in hexadecimal, or [`None`] if g_checksum_new() fails for
253/// @checksum_type. The returned string should be freed with g_free() when
254/// done using it.
255#[doc(alias = "g_compute_checksum_for_bytes")]
256pub fn compute_checksum_for_bytes(
257 checksum_type: ChecksumType,
258 data: &Bytes,
259) -> Option<crate::GString> {
260 unsafe {
261 from_glib_full(ffi::g_compute_checksum_for_bytes(
262 checksum_type.into_glib(),
263 data.to_glib_none().0,
264 ))
265 }
266}
267
268/// Computes the checksum for a binary @data of @length. This is a
269/// convenience wrapper for g_checksum_new(), g_checksum_get_string()
270/// and g_checksum_free().
271///
272/// The hexadecimal string returned will be in lower case.
273/// ## `checksum_type`
274/// a #GChecksumType
275/// ## `data`
276/// binary blob to compute the digest of
277///
278/// # Returns
279///
280/// the digest of the binary data as a
281/// string in hexadecimal, or [`None`] if g_checksum_new() fails for
282/// @checksum_type. The returned string should be freed with g_free() when
283/// done using it.
284// rustdoc-stripper-ignore-next-stop
285/// Computes the checksum for a binary @data of @length. This is a
286/// convenience wrapper for g_checksum_new(), g_checksum_get_string()
287/// and g_checksum_free().
288///
289/// The hexadecimal string returned will be in lower case.
290/// ## `checksum_type`
291/// a #GChecksumType
292/// ## `data`
293/// binary blob to compute the digest of
294///
295/// # Returns
296///
297/// the digest of the binary data as a
298/// string in hexadecimal, or [`None`] if g_checksum_new() fails for
299/// @checksum_type. The returned string should be freed with g_free() when
300/// done using it.
301#[doc(alias = "g_compute_checksum_for_data")]
302pub fn compute_checksum_for_data(
303 checksum_type: ChecksumType,
304 data: &[u8],
305) -> Option<crate::GString> {
306 let length = data.len() as _;
307 unsafe {
308 from_glib_full(ffi::g_compute_checksum_for_data(
309 checksum_type.into_glib(),
310 data.to_glib_none().0,
311 length,
312 ))
313 }
314}
315
316/// Computes the HMAC for a binary @data. This is a
317/// convenience wrapper for g_hmac_new(), g_hmac_get_string()
318/// and g_hmac_unref().
319///
320/// The hexadecimal string returned will be in lower case.
321/// ## `digest_type`
322/// a #GChecksumType to use for the HMAC
323/// ## `key`
324/// the key to use in the HMAC
325/// ## `data`
326/// binary blob to compute the HMAC of
327///
328/// # Returns
329///
330/// the HMAC of the binary data as a string in hexadecimal.
331/// The returned string should be freed with g_free() when done using it.
332// rustdoc-stripper-ignore-next-stop
333/// Computes the HMAC for a binary @data. This is a
334/// convenience wrapper for g_hmac_new(), g_hmac_get_string()
335/// and g_hmac_unref().
336///
337/// The hexadecimal string returned will be in lower case.
338/// ## `digest_type`
339/// a #GChecksumType to use for the HMAC
340/// ## `key`
341/// the key to use in the HMAC
342/// ## `data`
343/// binary blob to compute the HMAC of
344///
345/// # Returns
346///
347/// the HMAC of the binary data as a string in hexadecimal.
348/// The returned string should be freed with g_free() when done using it.
349#[doc(alias = "g_compute_hmac_for_bytes")]
350pub fn compute_hmac_for_bytes(
351 digest_type: ChecksumType,
352 key: &Bytes,
353 data: &Bytes,
354) -> crate::GString {
355 unsafe {
356 from_glib_full(ffi::g_compute_hmac_for_bytes(
357 digest_type.into_glib(),
358 key.to_glib_none().0,
359 data.to_glib_none().0,
360 ))
361 }
362}
363
364/// Computes the HMAC for a binary @data of @length. This is a
365/// convenience wrapper for g_hmac_new(), g_hmac_get_string()
366/// and g_hmac_unref().
367///
368/// The hexadecimal string returned will be in lower case.
369/// ## `digest_type`
370/// a #GChecksumType to use for the HMAC
371/// ## `key`
372/// the key to use in the HMAC
373/// ## `data`
374/// binary blob to compute the HMAC of
375///
376/// # Returns
377///
378/// the HMAC of the binary data as a string in hexadecimal.
379/// The returned string should be freed with g_free() when done using it.
380// rustdoc-stripper-ignore-next-stop
381/// Computes the HMAC for a binary @data of @length. This is a
382/// convenience wrapper for g_hmac_new(), g_hmac_get_string()
383/// and g_hmac_unref().
384///
385/// The hexadecimal string returned will be in lower case.
386/// ## `digest_type`
387/// a #GChecksumType to use for the HMAC
388/// ## `key`
389/// the key to use in the HMAC
390/// ## `data`
391/// binary blob to compute the HMAC of
392///
393/// # Returns
394///
395/// the HMAC of the binary data as a string in hexadecimal.
396/// The returned string should be freed with g_free() when done using it.
397#[doc(alias = "g_compute_hmac_for_data")]
398pub fn compute_hmac_for_data(digest_type: ChecksumType, key: &[u8], data: &[u8]) -> crate::GString {
399 let key_len = key.len() as _;
400 let length = data.len() as _;
401 unsafe {
402 from_glib_full(ffi::g_compute_hmac_for_data(
403 digest_type.into_glib(),
404 key.to_glib_none().0,
405 key_len,
406 data.to_glib_none().0,
407 length,
408 ))
409 }
410}
411
412/// This is a variant of g_dgettext() that allows specifying a locale
413/// category instead of always using `LC_MESSAGES`. See g_dgettext() for
414/// more information about how this functions differs from calling
415/// dcgettext() directly.
416/// ## `domain`
417/// the translation domain to use, or [`None`] to use
418/// the domain set with textdomain()
419/// ## `msgid`
420/// message to translate
421/// ## `category`
422/// a locale category
423///
424/// # Returns
425///
426/// the translated string for the given locale category
427// rustdoc-stripper-ignore-next-stop
428/// This is a variant of g_dgettext() that allows specifying a locale
429/// category instead of always using `LC_MESSAGES`. See g_dgettext() for
430/// more information about how this functions differs from calling
431/// dcgettext() directly.
432/// ## `domain`
433/// the translation domain to use, or [`None`] to use
434/// the domain set with textdomain()
435/// ## `msgid`
436/// message to translate
437/// ## `category`
438/// a locale category
439///
440/// # Returns
441///
442/// the translated string for the given locale category
443#[doc(alias = "g_dcgettext")]
444pub fn dcgettext(domain: Option<&str>, msgid: &str, category: i32) -> crate::GString {
445 unsafe {
446 from_glib_none(ffi::g_dcgettext(
447 domain.to_glib_none().0,
448 msgid.to_glib_none().0,
449 category,
450 ))
451 }
452}
453
454/// This function is a wrapper of dgettext() which does not translate
455/// the message if the default domain as set with textdomain() has no
456/// translations for the current locale.
457///
458/// The advantage of using this function over dgettext() proper is that
459/// libraries using this function (like GTK) will not use translations
460/// if the application using the library does not have translations for
461/// the current locale. This results in a consistent English-only
462/// interface instead of one having partial translations. For this
463/// feature to work, the call to textdomain() and setlocale() should
464/// precede any g_dgettext() invocations. For GTK, it means calling
465/// textdomain() before gtk_init or its variants.
466///
467/// This function disables translations if and only if upon its first
468/// call all the following conditions hold:
469///
470/// - @domain is not [`None`]
471///
472/// - textdomain() has been called to set a default text domain
473///
474/// - there is no translations available for the default text domain
475/// and the current locale
476///
477/// - current locale is not "C" or any English locales (those
478/// starting with "en_")
479///
480/// Note that this behavior may not be desired for example if an application
481/// has its untranslated messages in a language other than English. In those
482/// cases the application should call textdomain() after initializing GTK.
483///
484/// Applications should normally not use this function directly,
485/// but use the _() macro for translations.
486/// ## `domain`
487/// the translation domain to use, or [`None`] to use
488/// the domain set with textdomain()
489/// ## `msgid`
490/// message to translate
491///
492/// # Returns
493///
494/// The translated string
495// rustdoc-stripper-ignore-next-stop
496/// This function is a wrapper of dgettext() which does not translate
497/// the message if the default domain as set with textdomain() has no
498/// translations for the current locale.
499///
500/// The advantage of using this function over dgettext() proper is that
501/// libraries using this function (like GTK) will not use translations
502/// if the application using the library does not have translations for
503/// the current locale. This results in a consistent English-only
504/// interface instead of one having partial translations. For this
505/// feature to work, the call to textdomain() and setlocale() should
506/// precede any g_dgettext() invocations. For GTK, it means calling
507/// textdomain() before gtk_init or its variants.
508///
509/// This function disables translations if and only if upon its first
510/// call all the following conditions hold:
511///
512/// - @domain is not [`None`]
513///
514/// - textdomain() has been called to set a default text domain
515///
516/// - there is no translations available for the default text domain
517/// and the current locale
518///
519/// - current locale is not "C" or any English locales (those
520/// starting with "en_")
521///
522/// Note that this behavior may not be desired for example if an application
523/// has its untranslated messages in a language other than English. In those
524/// cases the application should call textdomain() after initializing GTK.
525///
526/// Applications should normally not use this function directly,
527/// but use the _() macro for translations.
528/// ## `domain`
529/// the translation domain to use, or [`None`] to use
530/// the domain set with textdomain()
531/// ## `msgid`
532/// message to translate
533///
534/// # Returns
535///
536/// The translated string
537#[doc(alias = "g_dgettext")]
538pub fn dgettext(domain: Option<&str>, msgid: &str) -> crate::GString {
539 unsafe {
540 from_glib_none(ffi::g_dgettext(
541 domain.to_glib_none().0,
542 msgid.to_glib_none().0,
543 ))
544 }
545}
546
547/// This function is a wrapper of dngettext() which does not translate
548/// the message if the default domain as set with textdomain() has no
549/// translations for the current locale.
550///
551/// See g_dgettext() for details of how this differs from dngettext()
552/// proper.
553/// ## `domain`
554/// the translation domain to use, or [`None`] to use
555/// the domain set with textdomain()
556/// ## `msgid`
557/// message to translate
558/// ## `msgid_plural`
559/// plural form of the message
560/// ## `n`
561/// the quantity for which translation is needed
562///
563/// # Returns
564///
565/// The translated string
566// rustdoc-stripper-ignore-next-stop
567/// This function is a wrapper of dngettext() which does not translate
568/// the message if the default domain as set with textdomain() has no
569/// translations for the current locale.
570///
571/// See g_dgettext() for details of how this differs from dngettext()
572/// proper.
573/// ## `domain`
574/// the translation domain to use, or [`None`] to use
575/// the domain set with textdomain()
576/// ## `msgid`
577/// message to translate
578/// ## `msgid_plural`
579/// plural form of the message
580/// ## `n`
581/// the quantity for which translation is needed
582///
583/// # Returns
584///
585/// The translated string
586#[doc(alias = "g_dngettext")]
587pub fn dngettext(
588 domain: Option<&str>,
589 msgid: &str,
590 msgid_plural: &str,
591 n: libc::c_ulong,
592) -> crate::GString {
593 unsafe {
594 from_glib_none(ffi::g_dngettext(
595 domain.to_glib_none().0,
596 msgid.to_glib_none().0,
597 msgid_plural.to_glib_none().0,
598 n,
599 ))
600 }
601}
602
603/// This function is a variant of g_dgettext() which supports
604/// a disambiguating message context. GNU gettext uses the
605/// '\004' character to separate the message context and
606/// message id in @msgctxtid.
607/// If 0 is passed as @msgidoffset, this function will fall back to
608/// trying to use the deprecated convention of using "|" as a separation
609/// character.
610///
611/// This uses g_dgettext() internally. See that functions for differences
612/// with dgettext() proper.
613///
614/// Applications should normally not use this function directly,
615/// but use the C_() macro for translations with context.
616/// ## `domain`
617/// the translation domain to use, or [`None`] to use
618/// the domain set with textdomain()
619/// ## `msgctxtid`
620/// a combined message context and message id, separated
621/// by a \004 character
622/// ## `msgidoffset`
623/// the offset of the message id in @msgctxid
624///
625/// # Returns
626///
627/// The translated string
628// rustdoc-stripper-ignore-next-stop
629/// This function is a variant of g_dgettext() which supports
630/// a disambiguating message context. GNU gettext uses the
631/// '\004' character to separate the message context and
632/// message id in @msgctxtid.
633/// If 0 is passed as @msgidoffset, this function will fall back to
634/// trying to use the deprecated convention of using "|" as a separation
635/// character.
636///
637/// This uses g_dgettext() internally. See that functions for differences
638/// with dgettext() proper.
639///
640/// Applications should normally not use this function directly,
641/// but use the C_() macro for translations with context.
642/// ## `domain`
643/// the translation domain to use, or [`None`] to use
644/// the domain set with textdomain()
645/// ## `msgctxtid`
646/// a combined message context and message id, separated
647/// by a \004 character
648/// ## `msgidoffset`
649/// the offset of the message id in @msgctxid
650///
651/// # Returns
652///
653/// The translated string
654#[doc(alias = "g_dpgettext")]
655pub fn dpgettext(domain: Option<&str>, msgctxtid: &str, msgidoffset: usize) -> crate::GString {
656 unsafe {
657 from_glib_none(ffi::g_dpgettext(
658 domain.to_glib_none().0,
659 msgctxtid.to_glib_none().0,
660 msgidoffset,
661 ))
662 }
663}
664
665/// This function is a variant of g_dgettext() which supports
666/// a disambiguating message context. GNU gettext uses the
667/// '\004' character to separate the message context and
668/// message id in @msgctxtid.
669///
670/// This uses g_dgettext() internally. See that functions for differences
671/// with dgettext() proper.
672///
673/// This function differs from C_() in that it is not a macro and
674/// thus you may use non-string-literals as context and msgid arguments.
675/// ## `domain`
676/// the translation domain to use, or [`None`] to use
677/// the domain set with textdomain()
678/// ## `context`
679/// the message context
680/// ## `msgid`
681/// the message
682///
683/// # Returns
684///
685/// The translated string
686// rustdoc-stripper-ignore-next-stop
687/// This function is a variant of g_dgettext() which supports
688/// a disambiguating message context. GNU gettext uses the
689/// '\004' character to separate the message context and
690/// message id in @msgctxtid.
691///
692/// This uses g_dgettext() internally. See that functions for differences
693/// with dgettext() proper.
694///
695/// This function differs from C_() in that it is not a macro and
696/// thus you may use non-string-literals as context and msgid arguments.
697/// ## `domain`
698/// the translation domain to use, or [`None`] to use
699/// the domain set with textdomain()
700/// ## `context`
701/// the message context
702/// ## `msgid`
703/// the message
704///
705/// # Returns
706///
707/// The translated string
708#[doc(alias = "g_dpgettext2")]
709pub fn dpgettext2(domain: Option<&str>, context: &str, msgid: &str) -> crate::GString {
710 unsafe {
711 from_glib_none(ffi::g_dpgettext2(
712 domain.to_glib_none().0,
713 context.to_glib_none().0,
714 msgid.to_glib_none().0,
715 ))
716 }
717}
718
719/// Writes all of @contents to a file named @filename. This is a convenience
720/// wrapper around calling g_file_set_contents_full() with `flags` set to
721/// `G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING` and
722/// `mode` set to `0666`.
723/// ## `filename`
724/// name of a file to write @contents to, in the GLib file name
725/// encoding
726/// ## `contents`
727/// string to write to the file
728///
729/// # Returns
730///
731/// [`true`] on success, [`false`] if an error occurred
732// rustdoc-stripper-ignore-next-stop
733/// Writes all of @contents to a file named @filename. This is a convenience
734/// wrapper around calling g_file_set_contents_full() with `flags` set to
735/// `G_FILE_SET_CONTENTS_CONSISTENT | G_FILE_SET_CONTENTS_ONLY_EXISTING` and
736/// `mode` set to `0666`.
737/// ## `filename`
738/// name of a file to write @contents to, in the GLib file name
739/// encoding
740/// ## `contents`
741/// string to write to the file
742///
743/// # Returns
744///
745/// [`true`] on success, [`false`] if an error occurred
746#[doc(alias = "g_file_set_contents")]
747pub fn file_set_contents(
748 filename: impl AsRef<std::path::Path>,
749 contents: &[u8],
750) -> Result<(), crate::Error> {
751 let length = contents.len() as _;
752 unsafe {
753 let mut error = std::ptr::null_mut();
754 let is_ok = ffi::g_file_set_contents(
755 filename.as_ref().to_glib_none().0,
756 contents.to_glib_none().0,
757 length,
758 &mut error,
759 );
760 debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
761 if error.is_null() {
762 Ok(())
763 } else {
764 Err(from_glib_full(error))
765 }
766 }
767}
768
769/// Writes all of @contents to a file named @filename, with good error checking.
770/// If a file called @filename already exists it will be overwritten.
771///
772/// @flags control the properties of the write operation: whether it’s atomic,
773/// and what the tradeoff is between returning quickly or being resilient to
774/// system crashes.
775///
776/// As this function performs file I/O, it is recommended to not call it anywhere
777/// where blocking would cause problems, such as in the main loop of a graphical
778/// application. In particular, if @flags has any value other than
779/// [`FileSetContentsFlags::NONE`][crate::FileSetContentsFlags::NONE] then this function may call `fsync()`.
780///
781/// If [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] is set in @flags, the operation is atomic
782/// in the sense that it is first written to a temporary file which is then
783/// renamed to the final name.
784///
785/// Notes:
786///
787/// - On UNIX, if @filename already exists hard links to @filename will break.
788/// Also since the file is recreated, existing permissions, access control
789/// lists, metadata etc. may be lost. If @filename is a symbolic link,
790/// the link itself will be replaced, not the linked file.
791///
792/// - On UNIX, if @filename already exists and is non-empty, and if the system
793/// supports it (via a journalling filesystem or equivalent), and if
794/// [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] is set in @flags, the `fsync()` call (or
795/// equivalent) will be used to ensure atomic replacement: @filename
796/// will contain either its old contents or @contents, even in the face of
797/// system power loss, the disk being unsafely removed, etc.
798///
799/// - On UNIX, if @filename does not already exist or is empty, there is a
800/// possibility that system power loss etc. after calling this function will
801/// leave @filename empty or full of NUL bytes, depending on the underlying
802/// filesystem, unless [`FileSetContentsFlags::DURABLE`][crate::FileSetContentsFlags::DURABLE] and
803/// [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] are set in @flags.
804///
805/// - On Windows renaming a file will not remove an existing file with the
806/// new name, so on Windows there is a race condition between the existing
807/// file being removed and the temporary file being renamed.
808///
809/// - On Windows there is no way to remove a file that is open to some
810/// process, or mapped into memory. Thus, this function will fail if
811/// @filename already exists and is open.
812///
813/// If the call was successful, it returns [`true`]. If the call was not successful,
814/// it returns [`false`] and sets @error. The error domain is `G_FILE_ERROR`.
815/// Possible error codes are those in the #GFileError enumeration.
816///
817/// Note that the name for the temporary file is constructed by appending up
818/// to 7 characters to @filename.
819///
820/// If the file didn’t exist before and is created, it will be given the
821/// permissions from @mode. Otherwise, the permissions of the existing file will
822/// remain unchanged.
823/// ## `filename`
824/// name of a file to write @contents to, in the GLib file name
825/// encoding
826/// ## `contents`
827/// string to write to the file
828/// ## `flags`
829/// flags controlling the safety vs speed of the operation
830/// ## `mode`
831/// file mode, as passed to `open()`; typically this will be `0666`
832///
833/// # Returns
834///
835/// [`true`] on success, [`false`] if an error occurred
836// rustdoc-stripper-ignore-next-stop
837/// Writes all of @contents to a file named @filename, with good error checking.
838/// If a file called @filename already exists it will be overwritten.
839///
840/// @flags control the properties of the write operation: whether it’s atomic,
841/// and what the tradeoff is between returning quickly or being resilient to
842/// system crashes.
843///
844/// As this function performs file I/O, it is recommended to not call it anywhere
845/// where blocking would cause problems, such as in the main loop of a graphical
846/// application. In particular, if @flags has any value other than
847/// [`FileSetContentsFlags::NONE`][crate::FileSetContentsFlags::NONE] then this function may call `fsync()`.
848///
849/// If [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] is set in @flags, the operation is atomic
850/// in the sense that it is first written to a temporary file which is then
851/// renamed to the final name.
852///
853/// Notes:
854///
855/// - On UNIX, if @filename already exists hard links to @filename will break.
856/// Also since the file is recreated, existing permissions, access control
857/// lists, metadata etc. may be lost. If @filename is a symbolic link,
858/// the link itself will be replaced, not the linked file.
859///
860/// - On UNIX, if @filename already exists and is non-empty, and if the system
861/// supports it (via a journalling filesystem or equivalent), and if
862/// [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] is set in @flags, the `fsync()` call (or
863/// equivalent) will be used to ensure atomic replacement: @filename
864/// will contain either its old contents or @contents, even in the face of
865/// system power loss, the disk being unsafely removed, etc.
866///
867/// - On UNIX, if @filename does not already exist or is empty, there is a
868/// possibility that system power loss etc. after calling this function will
869/// leave @filename empty or full of NUL bytes, depending on the underlying
870/// filesystem, unless [`FileSetContentsFlags::DURABLE`][crate::FileSetContentsFlags::DURABLE] and
871/// [`FileSetContentsFlags::CONSISTENT`][crate::FileSetContentsFlags::CONSISTENT] are set in @flags.
872///
873/// - On Windows renaming a file will not remove an existing file with the
874/// new name, so on Windows there is a race condition between the existing
875/// file being removed and the temporary file being renamed.
876///
877/// - On Windows there is no way to remove a file that is open to some
878/// process, or mapped into memory. Thus, this function will fail if
879/// @filename already exists and is open.
880///
881/// If the call was successful, it returns [`true`]. If the call was not successful,
882/// it returns [`false`] and sets @error. The error domain is `G_FILE_ERROR`.
883/// Possible error codes are those in the #GFileError enumeration.
884///
885/// Note that the name for the temporary file is constructed by appending up
886/// to 7 characters to @filename.
887///
888/// If the file didn’t exist before and is created, it will be given the
889/// permissions from @mode. Otherwise, the permissions of the existing file will
890/// remain unchanged.
891/// ## `filename`
892/// name of a file to write @contents to, in the GLib file name
893/// encoding
894/// ## `contents`
895/// string to write to the file
896/// ## `flags`
897/// flags controlling the safety vs speed of the operation
898/// ## `mode`
899/// file mode, as passed to `open()`; typically this will be `0666`
900///
901/// # Returns
902///
903/// [`true`] on success, [`false`] if an error occurred
904#[cfg(feature = "v2_66")]
905#[cfg_attr(docsrs, doc(cfg(feature = "v2_66")))]
906#[doc(alias = "g_file_set_contents_full")]
907pub fn file_set_contents_full(
908 filename: impl AsRef<std::path::Path>,
909 contents: &[u8],
910 flags: FileSetContentsFlags,
911 mode: i32,
912) -> Result<(), crate::Error> {
913 let length = contents.len() as _;
914 unsafe {
915 let mut error = std::ptr::null_mut();
916 let is_ok = ffi::g_file_set_contents_full(
917 filename.as_ref().to_glib_none().0,
918 contents.to_glib_none().0,
919 length,
920 flags.into_glib(),
921 mode,
922 &mut error,
923 );
924 debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
925 if error.is_null() {
926 Ok(())
927 } else {
928 Err(from_glib_full(error))
929 }
930 }
931}
932
933/// Returns [`true`] if any of the tests in the bitfield @test are
934/// [`true`]. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
935/// will return [`true`] if the file exists; the check whether it's a
936/// directory doesn't matter since the existence test is [`true`]. With
937/// the current set of available tests, there's no point passing in
938/// more than one test at a time.
939///
940/// Apart from [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] all tests follow symbolic links,
941/// so for a symbolic link to a regular file g_file_test() will return
942/// [`true`] for both [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] and [`FileTest::IS_REGULAR`][crate::FileTest::IS_REGULAR].
943///
944/// Note, that for a dangling symbolic link g_file_test() will return
945/// [`true`] for [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] and [`false`] for all other flags.
946///
947/// You should never use g_file_test() to test whether it is safe
948/// to perform an operation, because there is always the possibility
949/// of the condition changing before you actually perform the operation,
950/// see [TOCTOU](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use).
951///
952/// For example, you might think you could use [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK]
953/// to know whether it is safe to write to a file without being
954/// tricked into writing into a different location. It doesn't work!
955///
956///
957///
958/// **⚠️ The following code is in C ⚠️**
959///
960/// ```C
961/// // DON'T DO THIS
962/// if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
963/// {
964/// fd = g_open (filename, O_WRONLY);
965/// // write to fd
966/// }
967///
968/// // DO THIS INSTEAD
969/// fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
970/// if (fd == -1)
971/// {
972/// // check error
973/// if (errno == ELOOP)
974/// // file is a symlink and can be ignored
975/// else
976/// // handle errors as before
977/// }
978/// else
979/// {
980/// // write to fd
981/// }
982/// ```
983///
984/// Another thing to note is that [`FileTest::EXISTS`][crate::FileTest::EXISTS] and
985/// [`FileTest::IS_EXECUTABLE`][crate::FileTest::IS_EXECUTABLE] are implemented using the access()
986/// system call. This usually doesn't matter, but if your program
987/// is setuid or setgid it means that these tests will give you
988/// the answer for the real user ID and group ID, rather than the
989/// effective user ID and group ID.
990///
991/// On Windows, there are no symlinks, so testing for
992/// [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] will always return [`false`]. Testing for
993/// [`FileTest::IS_EXECUTABLE`][crate::FileTest::IS_EXECUTABLE] will just check that the file exists and
994/// its name indicates that it is executable, checking for well-known
995/// extensions and those listed in the `PATHEXT` environment variable.
996/// ## `filename`
997/// a filename to test in the
998/// GLib file name encoding
999/// ## `test`
1000/// bitfield of #GFileTest flags
1001///
1002/// # Returns
1003///
1004/// whether a test was [`true`]
1005// rustdoc-stripper-ignore-next-stop
1006/// Returns [`true`] if any of the tests in the bitfield @test are
1007/// [`true`]. For example, `(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR)`
1008/// will return [`true`] if the file exists; the check whether it's a
1009/// directory doesn't matter since the existence test is [`true`]. With
1010/// the current set of available tests, there's no point passing in
1011/// more than one test at a time.
1012///
1013/// Apart from [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] all tests follow symbolic links,
1014/// so for a symbolic link to a regular file g_file_test() will return
1015/// [`true`] for both [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] and [`FileTest::IS_REGULAR`][crate::FileTest::IS_REGULAR].
1016///
1017/// Note, that for a dangling symbolic link g_file_test() will return
1018/// [`true`] for [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] and [`false`] for all other flags.
1019///
1020/// You should never use g_file_test() to test whether it is safe
1021/// to perform an operation, because there is always the possibility
1022/// of the condition changing before you actually perform the operation,
1023/// see [TOCTOU](https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use).
1024///
1025/// For example, you might think you could use [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK]
1026/// to know whether it is safe to write to a file without being
1027/// tricked into writing into a different location. It doesn't work!
1028///
1029///
1030///
1031/// **⚠️ The following code is in C ⚠️**
1032///
1033/// ```C
1034/// // DON'T DO THIS
1035/// if (!g_file_test (filename, G_FILE_TEST_IS_SYMLINK))
1036/// {
1037/// fd = g_open (filename, O_WRONLY);
1038/// // write to fd
1039/// }
1040///
1041/// // DO THIS INSTEAD
1042/// fd = g_open (filename, O_WRONLY | O_NOFOLLOW | O_CLOEXEC);
1043/// if (fd == -1)
1044/// {
1045/// // check error
1046/// if (errno == ELOOP)
1047/// // file is a symlink and can be ignored
1048/// else
1049/// // handle errors as before
1050/// }
1051/// else
1052/// {
1053/// // write to fd
1054/// }
1055/// ```
1056///
1057/// Another thing to note is that [`FileTest::EXISTS`][crate::FileTest::EXISTS] and
1058/// [`FileTest::IS_EXECUTABLE`][crate::FileTest::IS_EXECUTABLE] are implemented using the access()
1059/// system call. This usually doesn't matter, but if your program
1060/// is setuid or setgid it means that these tests will give you
1061/// the answer for the real user ID and group ID, rather than the
1062/// effective user ID and group ID.
1063///
1064/// On Windows, there are no symlinks, so testing for
1065/// [`FileTest::IS_SYMLINK`][crate::FileTest::IS_SYMLINK] will always return [`false`]. Testing for
1066/// [`FileTest::IS_EXECUTABLE`][crate::FileTest::IS_EXECUTABLE] will just check that the file exists and
1067/// its name indicates that it is executable, checking for well-known
1068/// extensions and those listed in the `PATHEXT` environment variable.
1069/// ## `filename`
1070/// a filename to test in the
1071/// GLib file name encoding
1072/// ## `test`
1073/// bitfield of #GFileTest flags
1074///
1075/// # Returns
1076///
1077/// whether a test was [`true`]
1078#[doc(alias = "g_file_test")]
1079#[allow(dead_code)]
1080pub(crate) fn file_test(filename: impl AsRef<std::path::Path>, test: FileTest) -> bool {
1081 unsafe {
1082 from_glib(ffi::g_file_test(
1083 filename.as_ref().to_glib_none().0,
1084 test.into_glib(),
1085 ))
1086 }
1087}
1088
1089/// Returns the display basename for the particular filename, guaranteed
1090/// to be valid UTF-8. The display name might not be identical to the filename,
1091/// for instance there might be problems converting it to UTF-8, and some files
1092/// can be translated in the display.
1093///
1094/// If GLib cannot make sense of the encoding of @filename, as a last resort it
1095/// replaces unknown characters with U+FFFD, the Unicode replacement character.
1096/// You can search the result for the UTF-8 encoding of this character (which is
1097/// "\357\277\275" in octal notation) to find out if @filename was in an invalid
1098/// encoding.
1099///
1100/// You must pass the whole absolute pathname to this functions so that
1101/// translation of well known locations can be done.
1102///
1103/// This function is preferred over g_filename_display_name() if you know the
1104/// whole path, as it allows translation.
1105/// ## `filename`
1106/// an absolute pathname in the
1107/// GLib file name encoding
1108///
1109/// # Returns
1110///
1111/// a newly allocated string containing
1112/// a rendition of the basename of the filename in valid UTF-8
1113// rustdoc-stripper-ignore-next-stop
1114/// Returns the display basename for the particular filename, guaranteed
1115/// to be valid UTF-8. The display name might not be identical to the filename,
1116/// for instance there might be problems converting it to UTF-8, and some files
1117/// can be translated in the display.
1118///
1119/// If GLib cannot make sense of the encoding of @filename, as a last resort it
1120/// replaces unknown characters with U+FFFD, the Unicode replacement character.
1121/// You can search the result for the UTF-8 encoding of this character (which is
1122/// "\357\277\275" in octal notation) to find out if @filename was in an invalid
1123/// encoding.
1124///
1125/// You must pass the whole absolute pathname to this functions so that
1126/// translation of well known locations can be done.
1127///
1128/// This function is preferred over g_filename_display_name() if you know the
1129/// whole path, as it allows translation.
1130/// ## `filename`
1131/// an absolute pathname in the
1132/// GLib file name encoding
1133///
1134/// # Returns
1135///
1136/// a newly allocated string containing
1137/// a rendition of the basename of the filename in valid UTF-8
1138#[doc(alias = "g_filename_display_basename")]
1139pub fn filename_display_basename(filename: impl AsRef<std::path::Path>) -> crate::GString {
1140 unsafe {
1141 from_glib_full(ffi::g_filename_display_basename(
1142 filename.as_ref().to_glib_none().0,
1143 ))
1144 }
1145}
1146
1147/// Converts a filename into a valid UTF-8 string. The conversion is
1148/// not necessarily reversible, so you should keep the original around
1149/// and use the return value of this function only for display purposes.
1150/// Unlike g_filename_to_utf8(), the result is guaranteed to be non-[`None`]
1151/// even if the filename actually isn't in the GLib file name encoding.
1152///
1153/// If GLib cannot make sense of the encoding of @filename, as a last resort it
1154/// replaces unknown characters with U+FFFD, the Unicode replacement character.
1155/// You can search the result for the UTF-8 encoding of this character (which is
1156/// "\357\277\275" in octal notation) to find out if @filename was in an invalid
1157/// encoding.
1158///
1159/// If you know the whole pathname of the file you should use
1160/// g_filename_display_basename(), since that allows location-based
1161/// translation of filenames.
1162/// ## `filename`
1163/// a pathname hopefully in the
1164/// GLib file name encoding
1165///
1166/// # Returns
1167///
1168/// a newly allocated string containing
1169/// a rendition of the filename in valid UTF-8
1170// rustdoc-stripper-ignore-next-stop
1171/// Converts a filename into a valid UTF-8 string. The conversion is
1172/// not necessarily reversible, so you should keep the original around
1173/// and use the return value of this function only for display purposes.
1174/// Unlike g_filename_to_utf8(), the result is guaranteed to be non-[`None`]
1175/// even if the filename actually isn't in the GLib file name encoding.
1176///
1177/// If GLib cannot make sense of the encoding of @filename, as a last resort it
1178/// replaces unknown characters with U+FFFD, the Unicode replacement character.
1179/// You can search the result for the UTF-8 encoding of this character (which is
1180/// "\357\277\275" in octal notation) to find out if @filename was in an invalid
1181/// encoding.
1182///
1183/// If you know the whole pathname of the file you should use
1184/// g_filename_display_basename(), since that allows location-based
1185/// translation of filenames.
1186/// ## `filename`
1187/// a pathname hopefully in the
1188/// GLib file name encoding
1189///
1190/// # Returns
1191///
1192/// a newly allocated string containing
1193/// a rendition of the filename in valid UTF-8
1194#[doc(alias = "g_filename_display_name")]
1195pub fn filename_display_name(filename: impl AsRef<std::path::Path>) -> crate::GString {
1196 unsafe {
1197 from_glib_full(ffi::g_filename_display_name(
1198 filename.as_ref().to_glib_none().0,
1199 ))
1200 }
1201}
1202
1203/// Converts an escaped ASCII-encoded URI to a local filename in the
1204/// encoding used for filenames.
1205///
1206/// Since GLib 2.78, the query string and fragment can be present in the URI,
1207/// but are not part of the resulting filename.
1208/// We take inspiration from https://url.spec.whatwg.org/#file-state,
1209/// but we don't support the entire standard.
1210/// ## `uri`
1211/// a uri describing a filename (escaped, encoded in ASCII).
1212///
1213/// # Returns
1214///
1215/// a newly-allocated string holding
1216/// the resulting filename, or [`None`] on an error.
1217///
1218/// ## `hostname`
1219/// Location to store hostname for the URI.
1220/// If there is no hostname in the URI, [`None`] will be
1221/// stored in this location.
1222// rustdoc-stripper-ignore-next-stop
1223/// Converts an escaped ASCII-encoded URI to a local filename in the
1224/// encoding used for filenames.
1225///
1226/// Since GLib 2.78, the query string and fragment can be present in the URI,
1227/// but are not part of the resulting filename.
1228/// We take inspiration from https://url.spec.whatwg.org/#file-state,
1229/// but we don't support the entire standard.
1230/// ## `uri`
1231/// a uri describing a filename (escaped, encoded in ASCII).
1232///
1233/// # Returns
1234///
1235/// a newly-allocated string holding
1236/// the resulting filename, or [`None`] on an error.
1237///
1238/// ## `hostname`
1239/// Location to store hostname for the URI.
1240/// If there is no hostname in the URI, [`None`] will be
1241/// stored in this location.
1242#[doc(alias = "g_filename_from_uri")]
1243pub fn filename_from_uri(
1244 uri: &str,
1245) -> Result<(std::path::PathBuf, Option<crate::GString>), crate::Error> {
1246 unsafe {
1247 let mut hostname = std::ptr::null_mut();
1248 let mut error = std::ptr::null_mut();
1249 let ret = ffi::g_filename_from_uri(uri.to_glib_none().0, &mut hostname, &mut error);
1250 if error.is_null() {
1251 Ok((from_glib_full(ret), from_glib_full(hostname)))
1252 } else {
1253 Err(from_glib_full(error))
1254 }
1255 }
1256}
1257
1258/// Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1259/// component following Section 3.3. of RFC 2396.
1260/// ## `filename`
1261/// an absolute filename specified in the GLib file
1262/// name encoding, which is the on-disk file name bytes on Unix, and UTF-8
1263/// on Windows
1264/// ## `hostname`
1265/// A UTF-8 encoded hostname, or [`None`] for none.
1266///
1267/// # Returns
1268///
1269/// a newly-allocated string holding the resulting
1270/// URI, or [`None`] on an error.
1271// rustdoc-stripper-ignore-next-stop
1272/// Converts an absolute filename to an escaped ASCII-encoded URI, with the path
1273/// component following Section 3.3. of RFC 2396.
1274/// ## `filename`
1275/// an absolute filename specified in the GLib file
1276/// name encoding, which is the on-disk file name bytes on Unix, and UTF-8
1277/// on Windows
1278/// ## `hostname`
1279/// A UTF-8 encoded hostname, or [`None`] for none.
1280///
1281/// # Returns
1282///
1283/// a newly-allocated string holding the resulting
1284/// URI, or [`None`] on an error.
1285#[doc(alias = "g_filename_to_uri")]
1286pub fn filename_to_uri(
1287 filename: impl AsRef<std::path::Path>,
1288 hostname: Option<&str>,
1289) -> Result<crate::GString, crate::Error> {
1290 unsafe {
1291 let mut error = std::ptr::null_mut();
1292 let ret = ffi::g_filename_to_uri(
1293 filename.as_ref().to_glib_none().0,
1294 hostname.to_glib_none().0,
1295 &mut error,
1296 );
1297 if error.is_null() {
1298 Ok(from_glib_full(ret))
1299 } else {
1300 Err(from_glib_full(error))
1301 }
1302 }
1303}
1304
1305/// Locates the first executable named @program in the user's path, in the
1306/// same way that execvp() would locate it. Returns an allocated string
1307/// with the absolute path name, or [`None`] if the program is not found in
1308/// the path. If @program is already an absolute path, returns a copy of
1309/// @program if @program exists and is executable, and [`None`] otherwise.
1310///
1311/// On Windows, if @program does not have a file type suffix, tries
1312/// with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
1313/// the `PATHEXT` environment variable.
1314///
1315/// On Windows, it looks for the file in the same way as CreateProcess()
1316/// would. This means first in the directory where the executing
1317/// program was loaded from, then in the current directory, then in the
1318/// Windows 32-bit system directory, then in the Windows directory, and
1319/// finally in the directories in the `PATH` environment variable. If
1320/// the program is found, the return value contains the full name
1321/// including the type suffix.
1322/// ## `program`
1323/// a program name in the GLib file name encoding
1324///
1325/// # Returns
1326///
1327/// a newly-allocated
1328/// string with the absolute path, or [`None`]
1329// rustdoc-stripper-ignore-next-stop
1330/// Locates the first executable named @program in the user's path, in the
1331/// same way that execvp() would locate it. Returns an allocated string
1332/// with the absolute path name, or [`None`] if the program is not found in
1333/// the path. If @program is already an absolute path, returns a copy of
1334/// @program if @program exists and is executable, and [`None`] otherwise.
1335///
1336/// On Windows, if @program does not have a file type suffix, tries
1337/// with the suffixes .exe, .cmd, .bat and .com, and the suffixes in
1338/// the `PATHEXT` environment variable.
1339///
1340/// On Windows, it looks for the file in the same way as CreateProcess()
1341/// would. This means first in the directory where the executing
1342/// program was loaded from, then in the current directory, then in the
1343/// Windows 32-bit system directory, then in the Windows directory, and
1344/// finally in the directories in the `PATH` environment variable. If
1345/// the program is found, the return value contains the full name
1346/// including the type suffix.
1347/// ## `program`
1348/// a program name in the GLib file name encoding
1349///
1350/// # Returns
1351///
1352/// a newly-allocated
1353/// string with the absolute path, or [`None`]
1354#[doc(alias = "g_find_program_in_path")]
1355pub fn find_program_in_path(program: impl AsRef<std::path::Path>) -> Option<std::path::PathBuf> {
1356 unsafe {
1357 from_glib_full(ffi::g_find_program_in_path(
1358 program.as_ref().to_glib_none().0,
1359 ))
1360 }
1361}
1362
1363/// Formats a size (for example the size of a file) into a human readable
1364/// string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
1365/// and are displayed rounded to the nearest tenth. E.g. the file size
1366/// 3292528 bytes will be converted into the string "3.2 MB". The returned string
1367/// is UTF-8, and may use a non-breaking space to separate the number and units,
1368/// to ensure they aren’t separated when line wrapped.
1369///
1370/// The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
1371///
1372/// This string should be freed with g_free() when not needed any longer.
1373///
1374/// See g_format_size_full() for more options about how the size might be
1375/// formatted.
1376/// ## `size`
1377/// a size in bytes
1378///
1379/// # Returns
1380///
1381/// a newly-allocated formatted string containing
1382/// a human readable file size
1383// rustdoc-stripper-ignore-next-stop
1384/// Formats a size (for example the size of a file) into a human readable
1385/// string. Sizes are rounded to the nearest size prefix (kB, MB, GB)
1386/// and are displayed rounded to the nearest tenth. E.g. the file size
1387/// 3292528 bytes will be converted into the string "3.2 MB". The returned string
1388/// is UTF-8, and may use a non-breaking space to separate the number and units,
1389/// to ensure they aren’t separated when line wrapped.
1390///
1391/// The prefix units base is 1000 (i.e. 1 kB is 1000 bytes).
1392///
1393/// This string should be freed with g_free() when not needed any longer.
1394///
1395/// See g_format_size_full() for more options about how the size might be
1396/// formatted.
1397/// ## `size`
1398/// a size in bytes
1399///
1400/// # Returns
1401///
1402/// a newly-allocated formatted string containing
1403/// a human readable file size
1404#[doc(alias = "g_format_size")]
1405pub fn format_size(size: u64) -> crate::GString {
1406 unsafe { from_glib_full(ffi::g_format_size(size)) }
1407}
1408
1409/// Formats a size.
1410///
1411/// This function is similar to g_format_size() but allows for flags
1412/// that modify the output. See #GFormatSizeFlags.
1413/// ## `size`
1414/// a size in bytes
1415/// ## `flags`
1416/// #GFormatSizeFlags to modify the output
1417///
1418/// # Returns
1419///
1420/// a newly-allocated formatted string
1421/// containing a human readable file size
1422// rustdoc-stripper-ignore-next-stop
1423/// Formats a size.
1424///
1425/// This function is similar to g_format_size() but allows for flags
1426/// that modify the output. See #GFormatSizeFlags.
1427/// ## `size`
1428/// a size in bytes
1429/// ## `flags`
1430/// #GFormatSizeFlags to modify the output
1431///
1432/// # Returns
1433///
1434/// a newly-allocated formatted string
1435/// containing a human readable file size
1436#[doc(alias = "g_format_size_full")]
1437pub fn format_size_full(size: u64, flags: FormatSizeFlags) -> crate::GString {
1438 unsafe { from_glib_full(ffi::g_format_size_full(size, flags.into_glib())) }
1439}
1440
1441/// Gets a human-readable name for the application, as set by
1442/// g_set_application_name(). This name should be localized if
1443/// possible, and is intended for display to the user. Contrast with
1444/// g_get_prgname(), which gets a non-localized name. If
1445/// g_set_application_name() has not been called, returns the result of
1446/// g_get_prgname() (which may be [`None`] if g_set_prgname() has also not
1447/// been called).
1448///
1449/// # Returns
1450///
1451/// human-readable application
1452/// name. May return [`None`]
1453// rustdoc-stripper-ignore-next-stop
1454/// Gets a human-readable name for the application, as set by
1455/// g_set_application_name(). This name should be localized if
1456/// possible, and is intended for display to the user. Contrast with
1457/// g_get_prgname(), which gets a non-localized name. If
1458/// g_set_application_name() has not been called, returns the result of
1459/// g_get_prgname() (which may be [`None`] if g_set_prgname() has also not
1460/// been called).
1461///
1462/// # Returns
1463///
1464/// human-readable application
1465/// name. May return [`None`]
1466#[doc(alias = "g_get_application_name")]
1467#[doc(alias = "get_application_name")]
1468pub fn application_name() -> Option<crate::GString> {
1469 unsafe { from_glib_none(ffi::g_get_application_name()) }
1470}
1471
1472/// Gets the character set for the current locale.
1473///
1474/// # Returns
1475///
1476/// a newly allocated string containing the name
1477/// of the character set. This string must be freed with g_free().
1478// rustdoc-stripper-ignore-next-stop
1479/// Gets the character set for the current locale.
1480///
1481/// # Returns
1482///
1483/// a newly allocated string containing the name
1484/// of the character set. This string must be freed with g_free().
1485#[doc(alias = "g_get_codeset")]
1486#[doc(alias = "get_codeset")]
1487pub fn codeset() -> crate::GString {
1488 unsafe { from_glib_full(ffi::g_get_codeset()) }
1489}
1490
1491/// Obtains the character set used by the console attached to the process,
1492/// which is suitable for printing output to the terminal.
1493///
1494/// Usually this matches the result returned by g_get_charset(), but in
1495/// environments where the locale's character set does not match the encoding
1496/// of the console this function tries to guess a more suitable value instead.
1497///
1498/// On Windows the character set returned by this function is the
1499/// output code page used by the console associated with the calling process.
1500/// If the codepage can't be determined (for example because there is no
1501/// console attached) UTF-8 is assumed.
1502///
1503/// The return value is [`true`] if the locale's encoding is UTF-8, in that
1504/// case you can perhaps avoid calling g_convert().
1505///
1506/// The string returned in @charset is not allocated, and should not be
1507/// freed.
1508///
1509/// # Returns
1510///
1511/// [`true`] if the returned charset is UTF-8
1512///
1513/// ## `charset`
1514/// return location for character set
1515/// name, or [`None`].
1516// rustdoc-stripper-ignore-next-stop
1517/// Obtains the character set used by the console attached to the process,
1518/// which is suitable for printing output to the terminal.
1519///
1520/// Usually this matches the result returned by g_get_charset(), but in
1521/// environments where the locale's character set does not match the encoding
1522/// of the console this function tries to guess a more suitable value instead.
1523///
1524/// On Windows the character set returned by this function is the
1525/// output code page used by the console associated with the calling process.
1526/// If the codepage can't be determined (for example because there is no
1527/// console attached) UTF-8 is assumed.
1528///
1529/// The return value is [`true`] if the locale's encoding is UTF-8, in that
1530/// case you can perhaps avoid calling g_convert().
1531///
1532/// The string returned in @charset is not allocated, and should not be
1533/// freed.
1534///
1535/// # Returns
1536///
1537/// [`true`] if the returned charset is UTF-8
1538///
1539/// ## `charset`
1540/// return location for character set
1541/// name, or [`None`].
1542#[cfg(feature = "v2_62")]
1543#[cfg_attr(docsrs, doc(cfg(feature = "v2_62")))]
1544#[doc(alias = "g_get_console_charset")]
1545#[doc(alias = "get_console_charset")]
1546pub fn console_charset() -> Option<crate::GString> {
1547 unsafe {
1548 let mut charset = std::ptr::null();
1549 let ret = from_glib(ffi::g_get_console_charset(&mut charset));
1550 if ret {
1551 Some(from_glib_none(charset))
1552 } else {
1553 None
1554 }
1555 }
1556}
1557
1558/// Gets the current directory.
1559///
1560/// The returned string should be freed when no longer needed.
1561/// The encoding of the returned string is system defined.
1562/// On Windows, it is always UTF-8.
1563///
1564/// Since GLib 2.40, this function will return the value of the "PWD"
1565/// environment variable if it is set and it happens to be the same as
1566/// the current directory. This can make a difference in the case that
1567/// the current directory is the target of a symbolic link.
1568///
1569/// # Returns
1570///
1571/// the current directory
1572// rustdoc-stripper-ignore-next-stop
1573/// Gets the current directory.
1574///
1575/// The returned string should be freed when no longer needed.
1576/// The encoding of the returned string is system defined.
1577/// On Windows, it is always UTF-8.
1578///
1579/// Since GLib 2.40, this function will return the value of the "PWD"
1580/// environment variable if it is set and it happens to be the same as
1581/// the current directory. This can make a difference in the case that
1582/// the current directory is the target of a symbolic link.
1583///
1584/// # Returns
1585///
1586/// the current directory
1587#[doc(alias = "g_get_current_dir")]
1588#[doc(alias = "get_current_dir")]
1589pub fn current_dir() -> std::path::PathBuf {
1590 unsafe { from_glib_full(ffi::g_get_current_dir()) }
1591}
1592
1593/// Gets the list of environment variables for the current process.
1594///
1595/// The list is [`None`] terminated and each item in the list is of the
1596/// form 'NAME=VALUE'.
1597///
1598/// This is equivalent to direct access to the 'environ' global variable,
1599/// except portable.
1600///
1601/// The return value is freshly allocated and it should be freed with
1602/// g_strfreev() when it is no longer needed.
1603///
1604/// # Returns
1605///
1606///
1607/// the list of environment variables
1608// rustdoc-stripper-ignore-next-stop
1609/// Gets the list of environment variables for the current process.
1610///
1611/// The list is [`None`] terminated and each item in the list is of the
1612/// form 'NAME=VALUE'.
1613///
1614/// This is equivalent to direct access to the 'environ' global variable,
1615/// except portable.
1616///
1617/// The return value is freshly allocated and it should be freed with
1618/// g_strfreev() when it is no longer needed.
1619///
1620/// # Returns
1621///
1622///
1623/// the list of environment variables
1624#[doc(alias = "g_get_environ")]
1625#[doc(alias = "get_environ")]
1626pub fn environ() -> Vec<std::ffi::OsString> {
1627 unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_get_environ()) }
1628}
1629
1630/// Gets the current user's home directory.
1631///
1632/// As with most UNIX tools, this function will return the value of the
1633/// `HOME` environment variable if it is set to an existing absolute path
1634/// name, falling back to the `passwd` file in the case that it is unset.
1635///
1636/// If the path given in `HOME` is non-absolute, does not exist, or is
1637/// not a directory, the result is undefined.
1638///
1639/// Before version 2.36 this function would ignore the `HOME` environment
1640/// variable, taking the value from the `passwd` database instead. This was
1641/// changed to increase the compatibility of GLib with other programs (and
1642/// the XDG basedir specification) and to increase testability of programs
1643/// based on GLib (by making it easier to run them from test frameworks).
1644///
1645/// If your program has a strong requirement for either the new or the
1646/// old behaviour (and if you don't wish to increase your GLib
1647/// dependency to ensure that the new behaviour is in effect) then you
1648/// should either directly check the `HOME` environment variable yourself
1649/// or unset it before calling any functions in GLib.
1650///
1651/// # Returns
1652///
1653/// the current user's home directory
1654// rustdoc-stripper-ignore-next-stop
1655/// Gets the current user's home directory.
1656///
1657/// As with most UNIX tools, this function will return the value of the
1658/// `HOME` environment variable if it is set to an existing absolute path
1659/// name, falling back to the `passwd` file in the case that it is unset.
1660///
1661/// If the path given in `HOME` is non-absolute, does not exist, or is
1662/// not a directory, the result is undefined.
1663///
1664/// Before version 2.36 this function would ignore the `HOME` environment
1665/// variable, taking the value from the `passwd` database instead. This was
1666/// changed to increase the compatibility of GLib with other programs (and
1667/// the XDG basedir specification) and to increase testability of programs
1668/// based on GLib (by making it easier to run them from test frameworks).
1669///
1670/// If your program has a strong requirement for either the new or the
1671/// old behaviour (and if you don't wish to increase your GLib
1672/// dependency to ensure that the new behaviour is in effect) then you
1673/// should either directly check the `HOME` environment variable yourself
1674/// or unset it before calling any functions in GLib.
1675///
1676/// # Returns
1677///
1678/// the current user's home directory
1679#[doc(alias = "g_get_home_dir")]
1680#[doc(alias = "get_home_dir")]
1681pub fn home_dir() -> std::path::PathBuf {
1682 unsafe { from_glib_none(ffi::g_get_home_dir()) }
1683}
1684
1685/// Return a name for the machine.
1686///
1687/// The returned name is not necessarily a fully-qualified domain name,
1688/// or even present in DNS or some other name service at all. It need
1689/// not even be unique on your local network or site, but usually it
1690/// is. Callers should not rely on the return value having any specific
1691/// properties like uniqueness for security purposes. Even if the name
1692/// of the machine is changed while an application is running, the
1693/// return value from this function does not change. The returned
1694/// string is owned by GLib and should not be modified or freed. If no
1695/// name can be determined, a default fixed string "localhost" is
1696/// returned.
1697///
1698/// The encoding of the returned string is UTF-8.
1699///
1700/// # Returns
1701///
1702/// the host name of the machine.
1703// rustdoc-stripper-ignore-next-stop
1704/// Return a name for the machine.
1705///
1706/// The returned name is not necessarily a fully-qualified domain name,
1707/// or even present in DNS or some other name service at all. It need
1708/// not even be unique on your local network or site, but usually it
1709/// is. Callers should not rely on the return value having any specific
1710/// properties like uniqueness for security purposes. Even if the name
1711/// of the machine is changed while an application is running, the
1712/// return value from this function does not change. The returned
1713/// string is owned by GLib and should not be modified or freed. If no
1714/// name can be determined, a default fixed string "localhost" is
1715/// returned.
1716///
1717/// The encoding of the returned string is UTF-8.
1718///
1719/// # Returns
1720///
1721/// the host name of the machine.
1722#[doc(alias = "g_get_host_name")]
1723#[doc(alias = "get_host_name")]
1724pub fn host_name() -> crate::GString {
1725 unsafe { from_glib_none(ffi::g_get_host_name()) }
1726}
1727
1728/// Computes a list of applicable locale names, which can be used to
1729/// e.g. construct locale-dependent filenames or search paths. The returned
1730/// list is sorted from most desirable to least desirable and always contains
1731/// the default locale "C".
1732///
1733/// For example, if LANGUAGE=de:en_US, then the returned list is
1734/// "de", "en_US", "en", "C".
1735///
1736/// This function consults the environment variables `LANGUAGE`, `LC_ALL`,
1737/// `LC_MESSAGES` and `LANG` to find the list of locales specified by the
1738/// user.
1739///
1740/// # Returns
1741///
1742/// a [`None`]-terminated array of strings owned by GLib
1743/// that must not be modified or freed.
1744// rustdoc-stripper-ignore-next-stop
1745/// Computes a list of applicable locale names, which can be used to
1746/// e.g. construct locale-dependent filenames or search paths. The returned
1747/// list is sorted from most desirable to least desirable and always contains
1748/// the default locale "C".
1749///
1750/// For example, if LANGUAGE=de:en_US, then the returned list is
1751/// "de", "en_US", "en", "C".
1752///
1753/// This function consults the environment variables `LANGUAGE`, `LC_ALL`,
1754/// `LC_MESSAGES` and `LANG` to find the list of locales specified by the
1755/// user.
1756///
1757/// # Returns
1758///
1759/// a [`None`]-terminated array of strings owned by GLib
1760/// that must not be modified or freed.
1761#[doc(alias = "g_get_language_names")]
1762#[doc(alias = "get_language_names")]
1763pub fn language_names() -> Vec<crate::GString> {
1764 unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_language_names()) }
1765}
1766
1767/// Computes a list of applicable locale names with a locale category name,
1768/// which can be used to construct the fallback locale-dependent filenames
1769/// or search paths. The returned list is sorted from most desirable to
1770/// least desirable and always contains the default locale "C".
1771///
1772/// This function consults the environment variables `LANGUAGE`, `LC_ALL`,
1773/// @category_name, and `LANG` to find the list of locales specified by the
1774/// user.
1775///
1776/// g_get_language_names() returns g_get_language_names_with_category("LC_MESSAGES").
1777/// ## `category_name`
1778/// a locale category name
1779///
1780/// # Returns
1781///
1782/// a [`None`]-terminated array of strings owned by
1783/// the thread g_get_language_names_with_category was called from.
1784/// It must not be modified or freed. It must be copied if planned to be used in another thread.
1785// rustdoc-stripper-ignore-next-stop
1786/// Computes a list of applicable locale names with a locale category name,
1787/// which can be used to construct the fallback locale-dependent filenames
1788/// or search paths. The returned list is sorted from most desirable to
1789/// least desirable and always contains the default locale "C".
1790///
1791/// This function consults the environment variables `LANGUAGE`, `LC_ALL`,
1792/// @category_name, and `LANG` to find the list of locales specified by the
1793/// user.
1794///
1795/// g_get_language_names() returns g_get_language_names_with_category("LC_MESSAGES").
1796/// ## `category_name`
1797/// a locale category name
1798///
1799/// # Returns
1800///
1801/// a [`None`]-terminated array of strings owned by
1802/// the thread g_get_language_names_with_category was called from.
1803/// It must not be modified or freed. It must be copied if planned to be used in another thread.
1804#[cfg(feature = "v2_58")]
1805#[cfg_attr(docsrs, doc(cfg(feature = "v2_58")))]
1806#[doc(alias = "g_get_language_names_with_category")]
1807#[doc(alias = "get_language_names_with_category")]
1808pub fn language_names_with_category(category_name: &str) -> Vec<crate::GString> {
1809 unsafe {
1810 FromGlibPtrContainer::from_glib_none(ffi::g_get_language_names_with_category(
1811 category_name.to_glib_none().0,
1812 ))
1813 }
1814}
1815
1816/// Returns a list of derived variants of @locale, which can be used to
1817/// e.g. construct locale-dependent filenames or search paths. The returned
1818/// list is sorted from most desirable to least desirable.
1819/// This function handles territory, charset and extra locale modifiers. See
1820/// [`setlocale(3)`](man:setlocale) for information about locales and their format.
1821///
1822/// @locale itself is guaranteed to be returned in the output.
1823///
1824/// For example, if @locale is `fr_BE`, then the returned list
1825/// is `fr_BE`, `fr`. If @locale is `en_GB.UTF-8@euro`, then the returned list
1826/// is `en_GB.UTF-8@euro`, `en_GB.UTF-8`, `en_GB@euro`, `en_GB`, `en.UTF-8@euro`,
1827/// `en.UTF-8`, `en@euro`, `en`.
1828///
1829/// If you need the list of variants for the current locale,
1830/// use g_get_language_names().
1831/// ## `locale`
1832/// a locale identifier
1833///
1834/// # Returns
1835///
1836/// a newly
1837/// allocated array of newly allocated strings with the locale variants. Free with
1838/// g_strfreev().
1839// rustdoc-stripper-ignore-next-stop
1840/// Returns a list of derived variants of @locale, which can be used to
1841/// e.g. construct locale-dependent filenames or search paths. The returned
1842/// list is sorted from most desirable to least desirable.
1843/// This function handles territory, charset and extra locale modifiers. See
1844/// [`setlocale(3)`](man:setlocale) for information about locales and their format.
1845///
1846/// @locale itself is guaranteed to be returned in the output.
1847///
1848/// For example, if @locale is `fr_BE`, then the returned list
1849/// is `fr_BE`, `fr`. If @locale is `en_GB.UTF-8@euro`, then the returned list
1850/// is `en_GB.UTF-8@euro`, `en_GB.UTF-8`, `en_GB@euro`, `en_GB`, `en.UTF-8@euro`,
1851/// `en.UTF-8`, `en@euro`, `en`.
1852///
1853/// If you need the list of variants for the current locale,
1854/// use g_get_language_names().
1855/// ## `locale`
1856/// a locale identifier
1857///
1858/// # Returns
1859///
1860/// a newly
1861/// allocated array of newly allocated strings with the locale variants. Free with
1862/// g_strfreev().
1863#[doc(alias = "g_get_locale_variants")]
1864#[doc(alias = "get_locale_variants")]
1865pub fn locale_variants(locale: &str) -> Vec<crate::GString> {
1866 unsafe {
1867 FromGlibPtrContainer::from_glib_full(ffi::g_get_locale_variants(locale.to_glib_none().0))
1868 }
1869}
1870
1871/// Queries the system monotonic time.
1872///
1873/// The monotonic clock will always increase and doesn’t suffer
1874/// discontinuities when the user (or NTP) changes the system time. It
1875/// may or may not continue to tick during times where the machine is
1876/// suspended.
1877///
1878/// We try to use the clock that corresponds as closely as possible to
1879/// the passage of time as measured by system calls such as
1880/// [`poll()`](man:poll(2)) but it
1881/// may not always be possible to do this.
1882///
1883/// # Returns
1884///
1885/// the monotonic time, in microseconds
1886// rustdoc-stripper-ignore-next-stop
1887/// Queries the system monotonic time.
1888///
1889/// The monotonic clock will always increase and doesn’t suffer
1890/// discontinuities when the user (or NTP) changes the system time. It
1891/// may or may not continue to tick during times where the machine is
1892/// suspended.
1893///
1894/// We try to use the clock that corresponds as closely as possible to
1895/// the passage of time as measured by system calls such as
1896/// [`poll()`](man:poll(2)) but it
1897/// may not always be possible to do this.
1898///
1899/// # Returns
1900///
1901/// the monotonic time, in microseconds
1902#[doc(alias = "g_get_monotonic_time")]
1903#[doc(alias = "get_monotonic_time")]
1904pub fn monotonic_time() -> i64 {
1905 unsafe { ffi::g_get_monotonic_time() }
1906}
1907
1908/// Determine the approximate number of threads that the system will
1909/// schedule simultaneously for this process. This is intended to be
1910/// used as a parameter to g_thread_pool_new() for CPU bound tasks and
1911/// similar cases.
1912///
1913/// # Returns
1914///
1915/// Number of schedulable threads, always greater than 0
1916// rustdoc-stripper-ignore-next-stop
1917/// Determine the approximate number of threads that the system will
1918/// schedule simultaneously for this process. This is intended to be
1919/// used as a parameter to g_thread_pool_new() for CPU bound tasks and
1920/// similar cases.
1921///
1922/// # Returns
1923///
1924/// Number of schedulable threads, always greater than 0
1925#[doc(alias = "g_get_num_processors")]
1926#[doc(alias = "get_num_processors")]
1927pub fn num_processors() -> u32 {
1928 unsafe { ffi::g_get_num_processors() }
1929}
1930
1931/// Get information about the operating system.
1932///
1933/// On Linux this comes from the `/etc/os-release` file. On other systems, it may
1934/// come from a variety of sources. You can either use the standard key names
1935/// like `G_OS_INFO_KEY_NAME` or pass any UTF-8 string key name. For example,
1936/// `/etc/os-release` provides a number of other less commonly used values that may
1937/// be useful. No key is guaranteed to be provided, so the caller should always
1938/// check if the result is [`None`].
1939/// ## `key_name`
1940/// a key for the OS info being requested, for example `G_OS_INFO_KEY_NAME`.
1941///
1942/// # Returns
1943///
1944/// The associated value for the requested key or [`None`] if
1945/// this information is not provided.
1946// rustdoc-stripper-ignore-next-stop
1947/// Get information about the operating system.
1948///
1949/// On Linux this comes from the `/etc/os-release` file. On other systems, it may
1950/// come from a variety of sources. You can either use the standard key names
1951/// like `G_OS_INFO_KEY_NAME` or pass any UTF-8 string key name. For example,
1952/// `/etc/os-release` provides a number of other less commonly used values that may
1953/// be useful. No key is guaranteed to be provided, so the caller should always
1954/// check if the result is [`None`].
1955/// ## `key_name`
1956/// a key for the OS info being requested, for example `G_OS_INFO_KEY_NAME`.
1957///
1958/// # Returns
1959///
1960/// The associated value for the requested key or [`None`] if
1961/// this information is not provided.
1962#[cfg(feature = "v2_64")]
1963#[cfg_attr(docsrs, doc(cfg(feature = "v2_64")))]
1964#[doc(alias = "g_get_os_info")]
1965#[doc(alias = "get_os_info")]
1966pub fn os_info(key_name: &str) -> Option<crate::GString> {
1967 unsafe { from_glib_full(ffi::g_get_os_info(key_name.to_glib_none().0)) }
1968}
1969
1970/// Gets the real name of the user. This usually comes from the user's
1971/// entry in the `passwd` file. The encoding of the returned string is
1972/// system-defined. (On Windows, it is, however, always UTF-8.) If the
1973/// real user name cannot be determined, the string "Unknown" is
1974/// returned.
1975///
1976/// # Returns
1977///
1978/// the user's real name.
1979// rustdoc-stripper-ignore-next-stop
1980/// Gets the real name of the user. This usually comes from the user's
1981/// entry in the `passwd` file. The encoding of the returned string is
1982/// system-defined. (On Windows, it is, however, always UTF-8.) If the
1983/// real user name cannot be determined, the string "Unknown" is
1984/// returned.
1985///
1986/// # Returns
1987///
1988/// the user's real name.
1989#[doc(alias = "g_get_real_name")]
1990#[doc(alias = "get_real_name")]
1991pub fn real_name() -> std::ffi::OsString {
1992 unsafe { from_glib_none(ffi::g_get_real_name()) }
1993}
1994
1995/// Queries the system wall-clock time.
1996///
1997/// This is equivalent to the UNIX [`gettimeofday()`](man:gettimeofday(2))
1998/// function, but portable.
1999///
2000/// You should only use this call if you are actually interested in the real
2001/// wall-clock time. [`monotonic_time()`][crate::monotonic_time()] is probably more useful for
2002/// measuring intervals.
2003///
2004/// # Returns
2005///
2006/// the number of microseconds since
2007/// [January 1, 1970 UTC](https://en.wikipedia.org/wiki/Unix_time)
2008// rustdoc-stripper-ignore-next-stop
2009/// Queries the system wall-clock time.
2010///
2011/// This is equivalent to the UNIX [`gettimeofday()`](man:gettimeofday(2))
2012/// function, but portable.
2013///
2014/// You should only use this call if you are actually interested in the real
2015/// wall-clock time. [`monotonic_time()`][crate::monotonic_time()] is probably more useful for
2016/// measuring intervals.
2017///
2018/// # Returns
2019///
2020/// the number of microseconds since
2021/// [January 1, 1970 UTC](https://en.wikipedia.org/wiki/Unix_time)
2022#[doc(alias = "g_get_real_time")]
2023#[doc(alias = "get_real_time")]
2024pub fn real_time() -> i64 {
2025 unsafe { ffi::g_get_real_time() }
2026}
2027
2028/// Returns an ordered list of base directories in which to access
2029/// system-wide configuration information.
2030///
2031/// On UNIX platforms this is determined using the mechanisms described
2032/// in the
2033/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2034/// In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2035///
2036/// On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2037/// If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2038/// data for all users is used instead. A typical path is
2039/// `C:\Documents and Settings\All Users\Application Data`.
2040/// This folder is used for application data
2041/// that is not user specific. For example, an application can store
2042/// a spell-check dictionary, a database of clip art, or a log file in the
2043/// FOLDERID_ProgramData folder. This information will not roam and is available
2044/// to anyone using the computer.
2045///
2046/// The return value is cached and modifying it at runtime is not supported, as
2047/// it’s not thread-safe to modify environment variables at runtime.
2048///
2049/// # Returns
2050///
2051///
2052/// a [`None`]-terminated array of strings owned by GLib that must not be
2053/// modified or freed.
2054// rustdoc-stripper-ignore-next-stop
2055/// Returns an ordered list of base directories in which to access
2056/// system-wide configuration information.
2057///
2058/// On UNIX platforms this is determined using the mechanisms described
2059/// in the
2060/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2061/// In this case the list of directories retrieved will be `XDG_CONFIG_DIRS`.
2062///
2063/// On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_DIRS` is defined.
2064/// If `XDG_CONFIG_DIRS` is undefined, the directory that contains application
2065/// data for all users is used instead. A typical path is
2066/// `C:\Documents and Settings\All Users\Application Data`.
2067/// This folder is used for application data
2068/// that is not user specific. For example, an application can store
2069/// a spell-check dictionary, a database of clip art, or a log file in the
2070/// FOLDERID_ProgramData folder. This information will not roam and is available
2071/// to anyone using the computer.
2072///
2073/// The return value is cached and modifying it at runtime is not supported, as
2074/// it’s not thread-safe to modify environment variables at runtime.
2075///
2076/// # Returns
2077///
2078///
2079/// a [`None`]-terminated array of strings owned by GLib that must not be
2080/// modified or freed.
2081#[doc(alias = "g_get_system_config_dirs")]
2082#[doc(alias = "get_system_config_dirs")]
2083pub fn system_config_dirs() -> Vec<std::path::PathBuf> {
2084 unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_system_config_dirs()) }
2085}
2086
2087/// Returns an ordered list of base directories in which to access
2088/// system-wide application data.
2089///
2090/// On UNIX platforms this is determined using the mechanisms described
2091/// in the
2092/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
2093/// In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
2094///
2095/// On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
2096/// If `XDG_DATA_DIRS` is undefined,
2097/// the first elements in the list are the Application Data
2098/// and Documents folders for All Users. (These can be determined only
2099/// on Windows 2000 or later and are not present in the list on other
2100/// Windows versions.) See documentation for FOLDERID_ProgramData and
2101/// FOLDERID_PublicDocuments.
2102///
2103/// Then follows the "share" subfolder in the installation folder for
2104/// the package containing the DLL that calls this function, if it can
2105/// be determined.
2106///
2107/// Finally the list contains the "share" subfolder in the installation
2108/// folder for GLib, and in the installation folder for the package the
2109/// application's .exe file belongs to.
2110///
2111/// The installation folders above are determined by looking up the
2112/// folder where the module (DLL or EXE) in question is located. If the
2113/// folder's name is "bin", its parent is used, otherwise the folder
2114/// itself.
2115///
2116/// Note that on Windows the returned list can vary depending on where
2117/// this function is called.
2118///
2119/// The return value is cached and modifying it at runtime is not supported, as
2120/// it’s not thread-safe to modify environment variables at runtime.
2121///
2122/// # Returns
2123///
2124///
2125/// a [`None`]-terminated array of strings owned by GLib that must not be
2126/// modified or freed.
2127// rustdoc-stripper-ignore-next-stop
2128/// Returns an ordered list of base directories in which to access
2129/// system-wide application data.
2130///
2131/// On UNIX platforms this is determined using the mechanisms described
2132/// in the
2133/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec)
2134/// In this case the list of directories retrieved will be `XDG_DATA_DIRS`.
2135///
2136/// On Windows it follows XDG Base Directory Specification if `XDG_DATA_DIRS` is defined.
2137/// If `XDG_DATA_DIRS` is undefined,
2138/// the first elements in the list are the Application Data
2139/// and Documents folders for All Users. (These can be determined only
2140/// on Windows 2000 or later and are not present in the list on other
2141/// Windows versions.) See documentation for FOLDERID_ProgramData and
2142/// FOLDERID_PublicDocuments.
2143///
2144/// Then follows the "share" subfolder in the installation folder for
2145/// the package containing the DLL that calls this function, if it can
2146/// be determined.
2147///
2148/// Finally the list contains the "share" subfolder in the installation
2149/// folder for GLib, and in the installation folder for the package the
2150/// application's .exe file belongs to.
2151///
2152/// The installation folders above are determined by looking up the
2153/// folder where the module (DLL or EXE) in question is located. If the
2154/// folder's name is "bin", its parent is used, otherwise the folder
2155/// itself.
2156///
2157/// Note that on Windows the returned list can vary depending on where
2158/// this function is called.
2159///
2160/// The return value is cached and modifying it at runtime is not supported, as
2161/// it’s not thread-safe to modify environment variables at runtime.
2162///
2163/// # Returns
2164///
2165///
2166/// a [`None`]-terminated array of strings owned by GLib that must not be
2167/// modified or freed.
2168#[doc(alias = "g_get_system_data_dirs")]
2169#[doc(alias = "get_system_data_dirs")]
2170pub fn system_data_dirs() -> Vec<std::path::PathBuf> {
2171 unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_system_data_dirs()) }
2172}
2173
2174/// Gets the directory to use for temporary files.
2175///
2176/// On UNIX, this is taken from the `TMPDIR` environment variable.
2177/// If the variable is not set, `P_tmpdir` is
2178/// used, as defined by the system C library. Failing that, a
2179/// hard-coded default of "/tmp" is returned.
2180///
2181/// On Windows, the `TEMP` environment variable is used, with the
2182/// root directory of the Windows installation (eg: "C:\") used
2183/// as a default.
2184///
2185/// The encoding of the returned string is system-defined. On Windows,
2186/// it is always UTF-8. The return value is never [`None`] or the empty
2187/// string.
2188///
2189/// # Returns
2190///
2191/// the directory to use for temporary files.
2192// rustdoc-stripper-ignore-next-stop
2193/// Gets the directory to use for temporary files.
2194///
2195/// On UNIX, this is taken from the `TMPDIR` environment variable.
2196/// If the variable is not set, `P_tmpdir` is
2197/// used, as defined by the system C library. Failing that, a
2198/// hard-coded default of "/tmp" is returned.
2199///
2200/// On Windows, the `TEMP` environment variable is used, with the
2201/// root directory of the Windows installation (eg: "C:\") used
2202/// as a default.
2203///
2204/// The encoding of the returned string is system-defined. On Windows,
2205/// it is always UTF-8. The return value is never [`None`] or the empty
2206/// string.
2207///
2208/// # Returns
2209///
2210/// the directory to use for temporary files.
2211#[doc(alias = "g_get_tmp_dir")]
2212#[doc(alias = "get_tmp_dir")]
2213pub fn tmp_dir() -> std::path::PathBuf {
2214 unsafe { from_glib_none(ffi::g_get_tmp_dir()) }
2215}
2216
2217/// Returns a base directory in which to store non-essential, cached
2218/// data specific to particular user.
2219///
2220/// On UNIX platforms this is determined using the mechanisms described
2221/// in the
2222/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2223/// In this case the directory retrieved will be `XDG_CACHE_HOME`.
2224///
2225/// On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
2226/// If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
2227/// repository for temporary Internet files is used instead. A typical path is
2228/// `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
2229/// See the [documentation for `FOLDERID_InternetCache`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2230///
2231/// The return value is cached and modifying it at runtime is not supported, as
2232/// it’s not thread-safe to modify environment variables at runtime.
2233///
2234/// # Returns
2235///
2236/// a string owned by GLib that
2237/// must not be modified or freed.
2238// rustdoc-stripper-ignore-next-stop
2239/// Returns a base directory in which to store non-essential, cached
2240/// data specific to particular user.
2241///
2242/// On UNIX platforms this is determined using the mechanisms described
2243/// in the
2244/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2245/// In this case the directory retrieved will be `XDG_CACHE_HOME`.
2246///
2247/// On Windows it follows XDG Base Directory Specification if `XDG_CACHE_HOME` is defined.
2248/// If `XDG_CACHE_HOME` is undefined, the directory that serves as a common
2249/// repository for temporary Internet files is used instead. A typical path is
2250/// `C:\Documents and Settings\username\Local Settings\Temporary Internet Files`.
2251/// See the [documentation for `FOLDERID_InternetCache`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2252///
2253/// The return value is cached and modifying it at runtime is not supported, as
2254/// it’s not thread-safe to modify environment variables at runtime.
2255///
2256/// # Returns
2257///
2258/// a string owned by GLib that
2259/// must not be modified or freed.
2260#[doc(alias = "g_get_user_cache_dir")]
2261#[doc(alias = "get_user_cache_dir")]
2262pub fn user_cache_dir() -> std::path::PathBuf {
2263 unsafe { from_glib_none(ffi::g_get_user_cache_dir()) }
2264}
2265
2266/// Returns a base directory in which to store user-specific application
2267/// configuration information such as user preferences and settings.
2268///
2269/// On UNIX platforms this is determined using the mechanisms described
2270/// in the
2271/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2272/// In this case the directory retrieved will be `XDG_CONFIG_HOME`.
2273///
2274/// On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
2275/// If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
2276/// to roaming) application data is used instead. See the
2277/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2278/// Note that in this case on Windows it will be the same
2279/// as what g_get_user_data_dir() returns.
2280///
2281/// The return value is cached and modifying it at runtime is not supported, as
2282/// it’s not thread-safe to modify environment variables at runtime.
2283///
2284/// # Returns
2285///
2286/// a string owned by GLib that
2287/// must not be modified or freed.
2288// rustdoc-stripper-ignore-next-stop
2289/// Returns a base directory in which to store user-specific application
2290/// configuration information such as user preferences and settings.
2291///
2292/// On UNIX platforms this is determined using the mechanisms described
2293/// in the
2294/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2295/// In this case the directory retrieved will be `XDG_CONFIG_HOME`.
2296///
2297/// On Windows it follows XDG Base Directory Specification if `XDG_CONFIG_HOME` is defined.
2298/// If `XDG_CONFIG_HOME` is undefined, the folder to use for local (as opposed
2299/// to roaming) application data is used instead. See the
2300/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2301/// Note that in this case on Windows it will be the same
2302/// as what g_get_user_data_dir() returns.
2303///
2304/// The return value is cached and modifying it at runtime is not supported, as
2305/// it’s not thread-safe to modify environment variables at runtime.
2306///
2307/// # Returns
2308///
2309/// a string owned by GLib that
2310/// must not be modified or freed.
2311#[doc(alias = "g_get_user_config_dir")]
2312#[doc(alias = "get_user_config_dir")]
2313pub fn user_config_dir() -> std::path::PathBuf {
2314 unsafe { from_glib_none(ffi::g_get_user_config_dir()) }
2315}
2316
2317/// Returns a base directory in which to access application data such
2318/// as icons that is customized for a particular user.
2319///
2320/// On UNIX platforms this is determined using the mechanisms described
2321/// in the
2322/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2323/// In this case the directory retrieved will be `XDG_DATA_HOME`.
2324///
2325/// On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
2326/// is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
2327/// opposed to roaming) application data is used instead. See the
2328/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2329/// Note that in this case on Windows it will be the same
2330/// as what g_get_user_config_dir() returns.
2331///
2332/// The return value is cached and modifying it at runtime is not supported, as
2333/// it’s not thread-safe to modify environment variables at runtime.
2334///
2335/// # Returns
2336///
2337/// a string owned by GLib that must
2338/// not be modified or freed.
2339// rustdoc-stripper-ignore-next-stop
2340/// Returns a base directory in which to access application data such
2341/// as icons that is customized for a particular user.
2342///
2343/// On UNIX platforms this is determined using the mechanisms described
2344/// in the
2345/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2346/// In this case the directory retrieved will be `XDG_DATA_HOME`.
2347///
2348/// On Windows it follows XDG Base Directory Specification if `XDG_DATA_HOME`
2349/// is defined. If `XDG_DATA_HOME` is undefined, the folder to use for local (as
2350/// opposed to roaming) application data is used instead. See the
2351/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2352/// Note that in this case on Windows it will be the same
2353/// as what g_get_user_config_dir() returns.
2354///
2355/// The return value is cached and modifying it at runtime is not supported, as
2356/// it’s not thread-safe to modify environment variables at runtime.
2357///
2358/// # Returns
2359///
2360/// a string owned by GLib that must
2361/// not be modified or freed.
2362#[doc(alias = "g_get_user_data_dir")]
2363#[doc(alias = "get_user_data_dir")]
2364pub fn user_data_dir() -> std::path::PathBuf {
2365 unsafe { from_glib_none(ffi::g_get_user_data_dir()) }
2366}
2367
2368/// Gets the user name of the current user. The encoding of the returned
2369/// string is system-defined. On UNIX, it might be the preferred file name
2370/// encoding, or something else, and there is no guarantee that it is even
2371/// consistent on a machine. On Windows, it is always UTF-8.
2372///
2373/// # Returns
2374///
2375/// the user name of the current user.
2376// rustdoc-stripper-ignore-next-stop
2377/// Gets the user name of the current user. The encoding of the returned
2378/// string is system-defined. On UNIX, it might be the preferred file name
2379/// encoding, or something else, and there is no guarantee that it is even
2380/// consistent on a machine. On Windows, it is always UTF-8.
2381///
2382/// # Returns
2383///
2384/// the user name of the current user.
2385#[doc(alias = "g_get_user_name")]
2386#[doc(alias = "get_user_name")]
2387pub fn user_name() -> std::ffi::OsString {
2388 unsafe { from_glib_none(ffi::g_get_user_name()) }
2389}
2390
2391/// Returns a directory that is unique to the current user on the local
2392/// system.
2393///
2394/// This is determined using the mechanisms described
2395/// in the
2396/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2397/// This is the directory
2398/// specified in the `XDG_RUNTIME_DIR` environment variable.
2399/// In the case that this variable is not set, we return the value of
2400/// g_get_user_cache_dir(), after verifying that it exists.
2401///
2402/// The return value is cached and modifying it at runtime is not supported, as
2403/// it’s not thread-safe to modify environment variables at runtime.
2404///
2405/// # Returns
2406///
2407/// a string owned by GLib that must not be
2408/// modified or freed.
2409// rustdoc-stripper-ignore-next-stop
2410/// Returns a directory that is unique to the current user on the local
2411/// system.
2412///
2413/// This is determined using the mechanisms described
2414/// in the
2415/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2416/// This is the directory
2417/// specified in the `XDG_RUNTIME_DIR` environment variable.
2418/// In the case that this variable is not set, we return the value of
2419/// g_get_user_cache_dir(), after verifying that it exists.
2420///
2421/// The return value is cached and modifying it at runtime is not supported, as
2422/// it’s not thread-safe to modify environment variables at runtime.
2423///
2424/// # Returns
2425///
2426/// a string owned by GLib that must not be
2427/// modified or freed.
2428#[doc(alias = "g_get_user_runtime_dir")]
2429#[doc(alias = "get_user_runtime_dir")]
2430pub fn user_runtime_dir() -> std::path::PathBuf {
2431 unsafe { from_glib_none(ffi::g_get_user_runtime_dir()) }
2432}
2433
2434/// Returns the full path of a special directory using its logical id.
2435///
2436/// On UNIX this is done using the XDG special user directories.
2437/// For compatibility with existing practise, [`UserDirectory::DirectoryDesktop`][crate::UserDirectory::DirectoryDesktop]
2438/// falls back to `$HOME/Desktop` when XDG special user directories have
2439/// not been set up.
2440///
2441/// Depending on the platform, the user might be able to change the path
2442/// of the special directory without requiring the session to restart; GLib
2443/// will not reflect any change once the special directories are loaded.
2444/// ## `directory`
2445/// the logical id of special directory
2446///
2447/// # Returns
2448///
2449/// the path to the specified special
2450/// directory, or [`None`] if the logical id was not found. The returned string is
2451/// owned by GLib and should not be modified or freed.
2452// rustdoc-stripper-ignore-next-stop
2453/// Returns the full path of a special directory using its logical id.
2454///
2455/// On UNIX this is done using the XDG special user directories.
2456/// For compatibility with existing practise, [`UserDirectory::DirectoryDesktop`][crate::UserDirectory::DirectoryDesktop]
2457/// falls back to `$HOME/Desktop` when XDG special user directories have
2458/// not been set up.
2459///
2460/// Depending on the platform, the user might be able to change the path
2461/// of the special directory without requiring the session to restart; GLib
2462/// will not reflect any change once the special directories are loaded.
2463/// ## `directory`
2464/// the logical id of special directory
2465///
2466/// # Returns
2467///
2468/// the path to the specified special
2469/// directory, or [`None`] if the logical id was not found. The returned string is
2470/// owned by GLib and should not be modified or freed.
2471#[doc(alias = "g_get_user_special_dir")]
2472#[doc(alias = "get_user_special_dir")]
2473pub fn user_special_dir(directory: UserDirectory) -> Option<std::path::PathBuf> {
2474 unsafe { from_glib_none(ffi::g_get_user_special_dir(directory.into_glib())) }
2475}
2476
2477/// Returns a base directory in which to store state files specific to
2478/// particular user.
2479///
2480/// On UNIX platforms this is determined using the mechanisms described
2481/// in the
2482/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2483/// In this case the directory retrieved will be `XDG_STATE_HOME`.
2484///
2485/// On Windows it follows XDG Base Directory Specification if `XDG_STATE_HOME` is defined.
2486/// If `XDG_STATE_HOME` is undefined, the folder to use for local (as opposed
2487/// to roaming) application data is used instead. See the
2488/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2489/// Note that in this case on Windows it will be the same
2490/// as what g_get_user_data_dir() returns.
2491///
2492/// The return value is cached and modifying it at runtime is not supported, as
2493/// it’s not thread-safe to modify environment variables at runtime.
2494///
2495/// # Returns
2496///
2497/// a string owned by GLib that
2498/// must not be modified or freed.
2499// rustdoc-stripper-ignore-next-stop
2500/// Returns a base directory in which to store state files specific to
2501/// particular user.
2502///
2503/// On UNIX platforms this is determined using the mechanisms described
2504/// in the
2505/// [XDG Base Directory Specification](http://www.freedesktop.org/Standards/basedir-spec).
2506/// In this case the directory retrieved will be `XDG_STATE_HOME`.
2507///
2508/// On Windows it follows XDG Base Directory Specification if `XDG_STATE_HOME` is defined.
2509/// If `XDG_STATE_HOME` is undefined, the folder to use for local (as opposed
2510/// to roaming) application data is used instead. See the
2511/// [documentation for `FOLDERID_LocalAppData`](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid).
2512/// Note that in this case on Windows it will be the same
2513/// as what g_get_user_data_dir() returns.
2514///
2515/// The return value is cached and modifying it at runtime is not supported, as
2516/// it’s not thread-safe to modify environment variables at runtime.
2517///
2518/// # Returns
2519///
2520/// a string owned by GLib that
2521/// must not be modified or freed.
2522#[cfg(feature = "v2_72")]
2523#[cfg_attr(docsrs, doc(cfg(feature = "v2_72")))]
2524#[doc(alias = "g_get_user_state_dir")]
2525#[doc(alias = "get_user_state_dir")]
2526pub fn user_state_dir() -> std::path::PathBuf {
2527 unsafe { from_glib_none(ffi::g_get_user_state_dir()) }
2528}
2529
2530/// Returns the value of an environment variable.
2531///
2532/// On UNIX, the name and value are byte strings which might or might not
2533/// be in some consistent character set and encoding. On Windows, they are
2534/// in UTF-8.
2535/// On Windows, in case the environment variable's value contains
2536/// references to other environment variables, they are expanded.
2537/// ## `variable`
2538/// the environment variable to get
2539///
2540/// # Returns
2541///
2542/// the value of the environment variable, or [`None`] if
2543/// the environment variable is not found. The returned string
2544/// may be overwritten by the next call to g_getenv(), g_setenv()
2545/// or g_unsetenv().
2546// rustdoc-stripper-ignore-next-stop
2547/// Returns the value of an environment variable.
2548///
2549/// On UNIX, the name and value are byte strings which might or might not
2550/// be in some consistent character set and encoding. On Windows, they are
2551/// in UTF-8.
2552/// On Windows, in case the environment variable's value contains
2553/// references to other environment variables, they are expanded.
2554/// ## `variable`
2555/// the environment variable to get
2556///
2557/// # Returns
2558///
2559/// the value of the environment variable, or [`None`] if
2560/// the environment variable is not found. The returned string
2561/// may be overwritten by the next call to g_getenv(), g_setenv()
2562/// or g_unsetenv().
2563#[doc(alias = "g_getenv")]
2564pub fn getenv(variable: impl AsRef<std::ffi::OsStr>) -> Option<std::ffi::OsString> {
2565 unsafe { from_glib_none(ffi::g_getenv(variable.as_ref().to_glib_none().0)) }
2566}
2567
2568/// Tests if @hostname contains segments with an ASCII-compatible
2569/// encoding of an Internationalized Domain Name. If this returns
2570/// [`true`], you should decode the hostname with g_hostname_to_unicode()
2571/// before displaying it to the user.
2572///
2573/// Note that a hostname might contain a mix of encoded and unencoded
2574/// segments, and so it is possible for g_hostname_is_non_ascii() and
2575/// g_hostname_is_ascii_encoded() to both return [`true`] for a name.
2576/// ## `hostname`
2577/// a hostname
2578///
2579/// # Returns
2580///
2581/// [`true`] if @hostname contains any ASCII-encoded
2582/// segments.
2583// rustdoc-stripper-ignore-next-stop
2584/// Tests if @hostname contains segments with an ASCII-compatible
2585/// encoding of an Internationalized Domain Name. If this returns
2586/// [`true`], you should decode the hostname with g_hostname_to_unicode()
2587/// before displaying it to the user.
2588///
2589/// Note that a hostname might contain a mix of encoded and unencoded
2590/// segments, and so it is possible for g_hostname_is_non_ascii() and
2591/// g_hostname_is_ascii_encoded() to both return [`true`] for a name.
2592/// ## `hostname`
2593/// a hostname
2594///
2595/// # Returns
2596///
2597/// [`true`] if @hostname contains any ASCII-encoded
2598/// segments.
2599#[doc(alias = "g_hostname_is_ascii_encoded")]
2600pub fn hostname_is_ascii_encoded(hostname: &str) -> bool {
2601 unsafe { from_glib(ffi::g_hostname_is_ascii_encoded(hostname.to_glib_none().0)) }
2602}
2603
2604/// Tests if @hostname is the string form of an IPv4 or IPv6 address.
2605/// (Eg, "192.168.0.1".)
2606///
2607/// Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).
2608/// ## `hostname`
2609/// a hostname (or IP address in string form)
2610///
2611/// # Returns
2612///
2613/// [`true`] if @hostname is an IP address
2614// rustdoc-stripper-ignore-next-stop
2615/// Tests if @hostname is the string form of an IPv4 or IPv6 address.
2616/// (Eg, "192.168.0.1".)
2617///
2618/// Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).
2619/// ## `hostname`
2620/// a hostname (or IP address in string form)
2621///
2622/// # Returns
2623///
2624/// [`true`] if @hostname is an IP address
2625#[doc(alias = "g_hostname_is_ip_address")]
2626pub fn hostname_is_ip_address(hostname: &str) -> bool {
2627 unsafe { from_glib(ffi::g_hostname_is_ip_address(hostname.to_glib_none().0)) }
2628}
2629
2630/// Tests if @hostname contains Unicode characters. If this returns
2631/// [`true`], you need to encode the hostname with g_hostname_to_ascii()
2632/// before using it in non-IDN-aware contexts.
2633///
2634/// Note that a hostname might contain a mix of encoded and unencoded
2635/// segments, and so it is possible for g_hostname_is_non_ascii() and
2636/// g_hostname_is_ascii_encoded() to both return [`true`] for a name.
2637/// ## `hostname`
2638/// a hostname
2639///
2640/// # Returns
2641///
2642/// [`true`] if @hostname contains any non-ASCII characters
2643// rustdoc-stripper-ignore-next-stop
2644/// Tests if @hostname contains Unicode characters. If this returns
2645/// [`true`], you need to encode the hostname with g_hostname_to_ascii()
2646/// before using it in non-IDN-aware contexts.
2647///
2648/// Note that a hostname might contain a mix of encoded and unencoded
2649/// segments, and so it is possible for g_hostname_is_non_ascii() and
2650/// g_hostname_is_ascii_encoded() to both return [`true`] for a name.
2651/// ## `hostname`
2652/// a hostname
2653///
2654/// # Returns
2655///
2656/// [`true`] if @hostname contains any non-ASCII characters
2657#[doc(alias = "g_hostname_is_non_ascii")]
2658pub fn hostname_is_non_ascii(hostname: &str) -> bool {
2659 unsafe { from_glib(ffi::g_hostname_is_non_ascii(hostname.to_glib_none().0)) }
2660}
2661
2662/// Converts @hostname to its canonical ASCII form; an ASCII-only
2663/// string containing no uppercase letters and not ending with a
2664/// trailing dot.
2665/// ## `hostname`
2666/// a valid UTF-8 or ASCII hostname
2667///
2668/// # Returns
2669///
2670/// an ASCII hostname, which must be freed,
2671/// or [`None`] if @hostname is in some way invalid.
2672// rustdoc-stripper-ignore-next-stop
2673/// Converts @hostname to its canonical ASCII form; an ASCII-only
2674/// string containing no uppercase letters and not ending with a
2675/// trailing dot.
2676/// ## `hostname`
2677/// a valid UTF-8 or ASCII hostname
2678///
2679/// # Returns
2680///
2681/// an ASCII hostname, which must be freed,
2682/// or [`None`] if @hostname is in some way invalid.
2683#[doc(alias = "g_hostname_to_ascii")]
2684pub fn hostname_to_ascii(hostname: &str) -> Option<crate::GString> {
2685 unsafe { from_glib_full(ffi::g_hostname_to_ascii(hostname.to_glib_none().0)) }
2686}
2687
2688/// Converts @hostname to its canonical presentation form; a UTF-8
2689/// string in Unicode normalization form C, containing no uppercase
2690/// letters, no forbidden characters, and no ASCII-encoded segments,
2691/// and not ending with a trailing dot.
2692///
2693/// Of course if @hostname is not an internationalized hostname, then
2694/// the canonical presentation form will be entirely ASCII.
2695/// ## `hostname`
2696/// a valid UTF-8 or ASCII hostname
2697///
2698/// # Returns
2699///
2700/// a UTF-8 hostname, which must be freed,
2701/// or [`None`] if @hostname is in some way invalid.
2702// rustdoc-stripper-ignore-next-stop
2703/// Converts @hostname to its canonical presentation form; a UTF-8
2704/// string in Unicode normalization form C, containing no uppercase
2705/// letters, no forbidden characters, and no ASCII-encoded segments,
2706/// and not ending with a trailing dot.
2707///
2708/// Of course if @hostname is not an internationalized hostname, then
2709/// the canonical presentation form will be entirely ASCII.
2710/// ## `hostname`
2711/// a valid UTF-8 or ASCII hostname
2712///
2713/// # Returns
2714///
2715/// a UTF-8 hostname, which must be freed,
2716/// or [`None`] if @hostname is in some way invalid.
2717#[doc(alias = "g_hostname_to_unicode")]
2718pub fn hostname_to_unicode(hostname: &str) -> Option<crate::GString> {
2719 unsafe { from_glib_full(ffi::g_hostname_to_unicode(hostname.to_glib_none().0)) }
2720}
2721
2722/// Gets the names of all variables set in the environment.
2723///
2724/// Programs that want to be portable to Windows should typically use
2725/// this function and g_getenv() instead of using the environ array
2726/// from the C library directly. On Windows, the strings in the environ
2727/// array are in system codepage encoding, while in most of the typical
2728/// use cases for environment variables in GLib-using programs you want
2729/// the UTF-8 encoding that this function and g_getenv() provide.
2730///
2731/// # Returns
2732///
2733///
2734/// a [`None`]-terminated list of strings which must be freed with
2735/// g_strfreev().
2736// rustdoc-stripper-ignore-next-stop
2737/// Gets the names of all variables set in the environment.
2738///
2739/// Programs that want to be portable to Windows should typically use
2740/// this function and g_getenv() instead of using the environ array
2741/// from the C library directly. On Windows, the strings in the environ
2742/// array are in system codepage encoding, while in most of the typical
2743/// use cases for environment variables in GLib-using programs you want
2744/// the UTF-8 encoding that this function and g_getenv() provide.
2745///
2746/// # Returns
2747///
2748///
2749/// a [`None`]-terminated list of strings which must be freed with
2750/// g_strfreev().
2751#[doc(alias = "g_listenv")]
2752pub fn listenv() -> Vec<std::ffi::OsString> {
2753 unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_listenv()) }
2754}
2755
2756/// Returns the currently firing source for this thread.
2757///
2758/// # Returns
2759///
2760/// the currently firing source, or `NULL`
2761/// if none is firing
2762// rustdoc-stripper-ignore-next-stop
2763/// Returns the currently firing source for this thread.
2764///
2765/// # Returns
2766///
2767/// the currently firing source, or `NULL`
2768/// if none is firing
2769#[doc(alias = "g_main_current_source")]
2770pub fn main_current_source() -> Option<Source> {
2771 unsafe { from_glib_none(ffi::g_main_current_source()) }
2772}
2773
2774/// Returns the depth of the stack of calls to
2775/// [`MainContext::dispatch()`][crate::MainContext::dispatch()] on any #GMainContext in the current thread.
2776///
2777/// That is, when called from the top level, it gives `0`. When
2778/// called from within a callback from [`MainContext::iteration()`][crate::MainContext::iteration()]
2779/// (or [`MainLoop::run()`][crate::MainLoop::run()], etc.) it returns `1`. When called from within
2780/// a callback to a recursive call to [`MainContext::iteration()`][crate::MainContext::iteration()],
2781/// it returns `2`. And so forth.
2782///
2783/// This function is useful in a situation like the following:
2784/// Imagine an extremely simple ‘garbage collected’ system.
2785///
2786/// **⚠️ The following code is in c ⚠️**
2787///
2788/// ```c
2789/// static GList *free_list;
2790///
2791/// gpointer
2792/// allocate_memory (gsize size)
2793/// {
2794/// gpointer result = g_malloc (size);
2795/// free_list = g_list_prepend (free_list, result);
2796/// return result;
2797/// }
2798///
2799/// void
2800/// free_allocated_memory (void)
2801/// {
2802/// GList *l;
2803/// for (l = free_list; l; l = l->next);
2804/// g_free (l->data);
2805/// g_list_free (free_list);
2806/// free_list = NULL;
2807/// }
2808///
2809/// [...]
2810///
2811/// while (TRUE);
2812/// {
2813/// g_main_context_iteration (NULL, TRUE);
2814/// free_allocated_memory();
2815/// }
2816/// ```
2817///
2818/// This works from an application, however, if you want to do the same
2819/// thing from a library, it gets more difficult, since you no longer
2820/// control the main loop. You might think you can simply use an idle
2821/// function to make the call to `free_allocated_memory()`, but that
2822/// doesn’t work, since the idle function could be called from a
2823/// recursive callback. This can be fixed by using [`main_depth()`][crate::main_depth()]
2824///
2825/// **⚠️ The following code is in c ⚠️**
2826///
2827/// ```c
2828/// gpointer
2829/// allocate_memory (gsize size)
2830/// {
2831/// FreeListBlock *block = g_new (FreeListBlock, 1);
2832/// block->mem = g_malloc (size);
2833/// block->depth = g_main_depth ();
2834/// free_list = g_list_prepend (free_list, block);
2835/// return block->mem;
2836/// }
2837///
2838/// void
2839/// free_allocated_memory (void)
2840/// {
2841/// GList *l;
2842///
2843/// int depth = g_main_depth ();
2844/// for (l = free_list; l; );
2845/// {
2846/// GList *next = l->next;
2847/// FreeListBlock *block = l->data;
2848/// if (block->depth > depth)
2849/// {
2850/// g_free (block->mem);
2851/// g_free (block);
2852/// free_list = g_list_delete_link (free_list, l);
2853/// }
2854///
2855/// l = next;
2856/// }
2857/// }
2858/// ```
2859///
2860/// There is a temptation to use [`main_depth()`][crate::main_depth()] to solve
2861/// problems with reentrancy. For instance, while waiting for data
2862/// to be received from the network in response to a menu item,
2863/// the menu item might be selected again. It might seem that
2864/// one could make the menu item’s callback return immediately
2865/// and do nothing if [`main_depth()`][crate::main_depth()] returns a value greater than 1.
2866/// However, this should be avoided since the user then sees selecting
2867/// the menu item do nothing. Furthermore, you’ll find yourself adding
2868/// these checks all over your code, since there are doubtless many,
2869/// many things that the user could do. Instead, you can use the
2870/// following techniques:
2871///
2872/// 1. Use `gtk_widget_set_sensitive()` or modal dialogs to prevent
2873/// the user from interacting with elements while the main
2874/// loop is recursing.
2875///
2876/// 2. Avoid main loop recursion in situations where you can’t handle
2877/// arbitrary callbacks. Instead, structure your code so that you
2878/// simply return to the main loop and then get called again when
2879/// there is more work to do.
2880///
2881/// # Returns
2882///
2883/// the main loop recursion level in the current thread
2884// rustdoc-stripper-ignore-next-stop
2885/// Returns the depth of the stack of calls to
2886/// [`MainContext::dispatch()`][crate::MainContext::dispatch()] on any #GMainContext in the current thread.
2887///
2888/// That is, when called from the top level, it gives `0`. When
2889/// called from within a callback from [`MainContext::iteration()`][crate::MainContext::iteration()]
2890/// (or [`MainLoop::run()`][crate::MainLoop::run()], etc.) it returns `1`. When called from within
2891/// a callback to a recursive call to [`MainContext::iteration()`][crate::MainContext::iteration()],
2892/// it returns `2`. And so forth.
2893///
2894/// This function is useful in a situation like the following:
2895/// Imagine an extremely simple ‘garbage collected’ system.
2896///
2897/// **⚠️ The following code is in c ⚠️**
2898///
2899/// ```c
2900/// static GList *free_list;
2901///
2902/// gpointer
2903/// allocate_memory (gsize size)
2904/// {
2905/// gpointer result = g_malloc (size);
2906/// free_list = g_list_prepend (free_list, result);
2907/// return result;
2908/// }
2909///
2910/// void
2911/// free_allocated_memory (void)
2912/// {
2913/// GList *l;
2914/// for (l = free_list; l; l = l->next);
2915/// g_free (l->data);
2916/// g_list_free (free_list);
2917/// free_list = NULL;
2918/// }
2919///
2920/// [...]
2921///
2922/// while (TRUE);
2923/// {
2924/// g_main_context_iteration (NULL, TRUE);
2925/// free_allocated_memory();
2926/// }
2927/// ```
2928///
2929/// This works from an application, however, if you want to do the same
2930/// thing from a library, it gets more difficult, since you no longer
2931/// control the main loop. You might think you can simply use an idle
2932/// function to make the call to `free_allocated_memory()`, but that
2933/// doesn’t work, since the idle function could be called from a
2934/// recursive callback. This can be fixed by using [`main_depth()`][crate::main_depth()]
2935///
2936/// **⚠️ The following code is in c ⚠️**
2937///
2938/// ```c
2939/// gpointer
2940/// allocate_memory (gsize size)
2941/// {
2942/// FreeListBlock *block = g_new (FreeListBlock, 1);
2943/// block->mem = g_malloc (size);
2944/// block->depth = g_main_depth ();
2945/// free_list = g_list_prepend (free_list, block);
2946/// return block->mem;
2947/// }
2948///
2949/// void
2950/// free_allocated_memory (void)
2951/// {
2952/// GList *l;
2953///
2954/// int depth = g_main_depth ();
2955/// for (l = free_list; l; );
2956/// {
2957/// GList *next = l->next;
2958/// FreeListBlock *block = l->data;
2959/// if (block->depth > depth)
2960/// {
2961/// g_free (block->mem);
2962/// g_free (block);
2963/// free_list = g_list_delete_link (free_list, l);
2964/// }
2965///
2966/// l = next;
2967/// }
2968/// }
2969/// ```
2970///
2971/// There is a temptation to use [`main_depth()`][crate::main_depth()] to solve
2972/// problems with reentrancy. For instance, while waiting for data
2973/// to be received from the network in response to a menu item,
2974/// the menu item might be selected again. It might seem that
2975/// one could make the menu item’s callback return immediately
2976/// and do nothing if [`main_depth()`][crate::main_depth()] returns a value greater than 1.
2977/// However, this should be avoided since the user then sees selecting
2978/// the menu item do nothing. Furthermore, you’ll find yourself adding
2979/// these checks all over your code, since there are doubtless many,
2980/// many things that the user could do. Instead, you can use the
2981/// following techniques:
2982///
2983/// 1. Use `gtk_widget_set_sensitive()` or modal dialogs to prevent
2984/// the user from interacting with elements while the main
2985/// loop is recursing.
2986///
2987/// 2. Avoid main loop recursion in situations where you can’t handle
2988/// arbitrary callbacks. Instead, structure your code so that you
2989/// simply return to the main loop and then get called again when
2990/// there is more work to do.
2991///
2992/// # Returns
2993///
2994/// the main loop recursion level in the current thread
2995#[doc(alias = "g_main_depth")]
2996pub fn main_depth() -> i32 {
2997 unsafe { ffi::g_main_depth() }
2998}
2999
3000/// Escapes text so that the markup parser will parse it verbatim.
3001/// Less than, greater than, ampersand, etc. are replaced with the
3002/// corresponding entities. This function would typically be used
3003/// when writing out a file to be parsed with the markup parser.
3004///
3005/// Note that this function doesn't protect whitespace and line endings
3006/// from being processed according to the XML rules for normalization
3007/// of line endings and attribute values.
3008///
3009/// Note also that this function will produce character references in
3010/// the range of  ...  for all control sequences
3011/// except for tabstop, newline and carriage return. The character
3012/// references in this range are not valid XML 1.0, but they are
3013/// valid XML 1.1 and will be accepted by the GMarkup parser.
3014/// ## `text`
3015/// some valid UTF-8 text
3016/// ## `length`
3017/// length of @text in bytes, or -1 if the text is nul-terminated
3018///
3019/// # Returns
3020///
3021/// a newly allocated string with the escaped text
3022// rustdoc-stripper-ignore-next-stop
3023/// Escapes text so that the markup parser will parse it verbatim.
3024/// Less than, greater than, ampersand, etc. are replaced with the
3025/// corresponding entities. This function would typically be used
3026/// when writing out a file to be parsed with the markup parser.
3027///
3028/// Note that this function doesn't protect whitespace and line endings
3029/// from being processed according to the XML rules for normalization
3030/// of line endings and attribute values.
3031///
3032/// Note also that this function will produce character references in
3033/// the range of  ...  for all control sequences
3034/// except for tabstop, newline and carriage return. The character
3035/// references in this range are not valid XML 1.0, but they are
3036/// valid XML 1.1 and will be accepted by the GMarkup parser.
3037/// ## `text`
3038/// some valid UTF-8 text
3039/// ## `length`
3040/// length of @text in bytes, or -1 if the text is nul-terminated
3041///
3042/// # Returns
3043///
3044/// a newly allocated string with the escaped text
3045#[doc(alias = "g_markup_escape_text")]
3046pub fn markup_escape_text(text: &str) -> crate::GString {
3047 let length = text.len() as _;
3048 unsafe { from_glib_full(ffi::g_markup_escape_text(text.to_glib_none().0, length)) }
3049}
3050
3051/// Create a directory if it doesn't already exist. Create intermediate
3052/// parent directories as needed, too.
3053/// ## `pathname`
3054/// a pathname in the GLib file name encoding
3055/// ## `mode`
3056/// permissions to use for newly created directories
3057///
3058/// # Returns
3059///
3060/// 0 if the directory already exists, or was successfully
3061/// created. Returns -1 if an error occurred, with errno set.
3062// rustdoc-stripper-ignore-next-stop
3063/// Create a directory if it doesn't already exist. Create intermediate
3064/// parent directories as needed, too.
3065/// ## `pathname`
3066/// a pathname in the GLib file name encoding
3067/// ## `mode`
3068/// permissions to use for newly created directories
3069///
3070/// # Returns
3071///
3072/// 0 if the directory already exists, or was successfully
3073/// created. Returns -1 if an error occurred, with errno set.
3074#[doc(alias = "g_mkdir_with_parents")]
3075pub fn mkdir_with_parents(pathname: impl AsRef<std::path::Path>, mode: i32) -> i32 {
3076 unsafe { ffi::g_mkdir_with_parents(pathname.as_ref().to_glib_none().0, mode) }
3077}
3078
3079/// Prompts the user with
3080/// `[E]xit, [H]alt, show [S]tack trace or [P]roceed`.
3081/// This function is intended to be used for debugging use only.
3082/// The following example shows how it can be used together with
3083/// the g_log() functions.
3084///
3085///
3086///
3087/// **⚠️ The following code is in C ⚠️**
3088///
3089/// ```C
3090/// #include <glib.h>
3091///
3092/// static void
3093/// log_handler (const gchar *log_domain,
3094/// GLogLevelFlags log_level,
3095/// const gchar *message,
3096/// gpointer user_data)
3097/// {
3098/// g_log_default_handler (log_domain, log_level, message, user_data);
3099///
3100/// g_on_error_query (MY_PROGRAM_NAME);
3101/// }
3102///
3103/// int
3104/// main (int argc, char *argv[])
3105/// {
3106/// g_log_set_handler (MY_LOG_DOMAIN,
3107/// G_LOG_LEVEL_WARNING |
3108/// G_LOG_LEVEL_ERROR |
3109/// G_LOG_LEVEL_CRITICAL,
3110/// log_handler,
3111/// NULL);
3112/// ...
3113/// ```
3114///
3115/// If "[E]xit" is selected, the application terminates with a call
3116/// to _exit(0).
3117///
3118/// If "[S]tack" trace is selected, g_on_error_stack_trace() is called.
3119/// This invokes gdb, which attaches to the current process and shows
3120/// a stack trace. The prompt is then shown again.
3121///
3122/// If "[P]roceed" is selected, the function returns.
3123///
3124/// This function may cause different actions on non-UNIX platforms.
3125///
3126/// On Windows consider using the `G_DEBUGGER` environment
3127/// variable (see [Running GLib Applications](running.html)) and
3128/// calling g_on_error_stack_trace() instead.
3129/// ## `prg_name`
3130/// the program name, needed by gdb for the "[S]tack trace"
3131/// option. If @prg_name is [`None`], g_get_prgname() is called to get
3132/// the program name (which will work correctly if gdk_init() or
3133/// gtk_init() has been called)
3134// rustdoc-stripper-ignore-next-stop
3135/// Prompts the user with
3136/// `[E]xit, [H]alt, show [S]tack trace or [P]roceed`.
3137/// This function is intended to be used for debugging use only.
3138/// The following example shows how it can be used together with
3139/// the g_log() functions.
3140///
3141///
3142///
3143/// **⚠️ The following code is in C ⚠️**
3144///
3145/// ```C
3146/// #include <glib.h>
3147///
3148/// static void
3149/// log_handler (const gchar *log_domain,
3150/// GLogLevelFlags log_level,
3151/// const gchar *message,
3152/// gpointer user_data)
3153/// {
3154/// g_log_default_handler (log_domain, log_level, message, user_data);
3155///
3156/// g_on_error_query (MY_PROGRAM_NAME);
3157/// }
3158///
3159/// int
3160/// main (int argc, char *argv[])
3161/// {
3162/// g_log_set_handler (MY_LOG_DOMAIN,
3163/// G_LOG_LEVEL_WARNING |
3164/// G_LOG_LEVEL_ERROR |
3165/// G_LOG_LEVEL_CRITICAL,
3166/// log_handler,
3167/// NULL);
3168/// ...
3169/// ```
3170///
3171/// If "[E]xit" is selected, the application terminates with a call
3172/// to _exit(0).
3173///
3174/// If "[S]tack" trace is selected, g_on_error_stack_trace() is called.
3175/// This invokes gdb, which attaches to the current process and shows
3176/// a stack trace. The prompt is then shown again.
3177///
3178/// If "[P]roceed" is selected, the function returns.
3179///
3180/// This function may cause different actions on non-UNIX platforms.
3181///
3182/// On Windows consider using the `G_DEBUGGER` environment
3183/// variable (see [Running GLib Applications](running.html)) and
3184/// calling g_on_error_stack_trace() instead.
3185/// ## `prg_name`
3186/// the program name, needed by gdb for the "[S]tack trace"
3187/// option. If @prg_name is [`None`], g_get_prgname() is called to get
3188/// the program name (which will work correctly if gdk_init() or
3189/// gtk_init() has been called)
3190#[doc(alias = "g_on_error_query")]
3191pub fn on_error_query(prg_name: &str) {
3192 unsafe {
3193 ffi::g_on_error_query(prg_name.to_glib_none().0);
3194 }
3195}
3196
3197/// Invokes gdb, which attaches to the current process and shows a
3198/// stack trace. Called by g_on_error_query() when the "[S]tack trace"
3199/// option is selected. You can get the current process's program name
3200/// with g_get_prgname(), assuming that you have called gtk_init() or
3201/// gdk_init().
3202///
3203/// This function may cause different actions on non-UNIX platforms.
3204///
3205/// When running on Windows, this function is *not* called by
3206/// g_on_error_query(). If called directly, it will raise an
3207/// exception, which will crash the program. If the `G_DEBUGGER` environment
3208/// variable is set, a debugger will be invoked to attach and
3209/// handle that exception (see [Running GLib Applications](running.html)).
3210/// ## `prg_name`
3211/// the program name, needed by gdb for the
3212/// "[S]tack trace" option, or `NULL` to use a default string
3213// rustdoc-stripper-ignore-next-stop
3214/// Invokes gdb, which attaches to the current process and shows a
3215/// stack trace. Called by g_on_error_query() when the "[S]tack trace"
3216/// option is selected. You can get the current process's program name
3217/// with g_get_prgname(), assuming that you have called gtk_init() or
3218/// gdk_init().
3219///
3220/// This function may cause different actions on non-UNIX platforms.
3221///
3222/// When running on Windows, this function is *not* called by
3223/// g_on_error_query(). If called directly, it will raise an
3224/// exception, which will crash the program. If the `G_DEBUGGER` environment
3225/// variable is set, a debugger will be invoked to attach and
3226/// handle that exception (see [Running GLib Applications](running.html)).
3227/// ## `prg_name`
3228/// the program name, needed by gdb for the
3229/// "[S]tack trace" option, or `NULL` to use a default string
3230#[doc(alias = "g_on_error_stack_trace")]
3231pub fn on_error_stack_trace(prg_name: Option<&str>) {
3232 unsafe {
3233 ffi::g_on_error_stack_trace(prg_name.to_glib_none().0);
3234 }
3235}
3236
3237/// Gets the last component of the filename.
3238///
3239/// If @file_name ends with a directory separator it gets the component
3240/// before the last slash. If @file_name consists only of directory
3241/// separators (and on Windows, possibly a drive letter), a single
3242/// separator is returned. If @file_name is empty, it gets ".".
3243/// ## `file_name`
3244/// the name of the file
3245///
3246/// # Returns
3247///
3248/// a newly allocated string
3249/// containing the last component of the filename
3250// rustdoc-stripper-ignore-next-stop
3251/// Gets the last component of the filename.
3252///
3253/// If @file_name ends with a directory separator it gets the component
3254/// before the last slash. If @file_name consists only of directory
3255/// separators (and on Windows, possibly a drive letter), a single
3256/// separator is returned. If @file_name is empty, it gets ".".
3257/// ## `file_name`
3258/// the name of the file
3259///
3260/// # Returns
3261///
3262/// a newly allocated string
3263/// containing the last component of the filename
3264#[doc(alias = "g_path_get_basename")]
3265#[allow(dead_code)]
3266pub(crate) fn path_get_basename(file_name: impl AsRef<std::path::Path>) -> std::path::PathBuf {
3267 unsafe {
3268 from_glib_full(ffi::g_path_get_basename(
3269 file_name.as_ref().to_glib_none().0,
3270 ))
3271 }
3272}
3273
3274/// Gets the directory components of a file name. For example, the directory
3275/// component of `/usr/bin/test` is `/usr/bin`. The directory component of `/`
3276/// is `/`.
3277///
3278/// If the file name has no directory components "." is returned.
3279/// The returned string should be freed when no longer needed.
3280/// ## `file_name`
3281/// the name of the file
3282///
3283/// # Returns
3284///
3285/// the directory components of the file
3286// rustdoc-stripper-ignore-next-stop
3287/// Gets the directory components of a file name. For example, the directory
3288/// component of `/usr/bin/test` is `/usr/bin`. The directory component of `/`
3289/// is `/`.
3290///
3291/// If the file name has no directory components "." is returned.
3292/// The returned string should be freed when no longer needed.
3293/// ## `file_name`
3294/// the name of the file
3295///
3296/// # Returns
3297///
3298/// the directory components of the file
3299#[doc(alias = "g_path_get_dirname")]
3300#[allow(dead_code)]
3301pub(crate) fn path_get_dirname(file_name: impl AsRef<std::path::Path>) -> std::path::PathBuf {
3302 unsafe { from_glib_full(ffi::g_path_get_dirname(file_name.as_ref().to_glib_none().0)) }
3303}
3304
3305//#[doc(alias = "g_poll")]
3306//pub fn poll(fds: /*Ignored*/&mut PollFD, nfds: u32, timeout: i32) -> i32 {
3307// unsafe { TODO: call ffi:g_poll() }
3308//}
3309
3310/// Returns a random #gdouble equally distributed over the range [0..1).
3311///
3312/// # Returns
3313///
3314/// a random number
3315// rustdoc-stripper-ignore-next-stop
3316/// Returns a random #gdouble equally distributed over the range [0..1).
3317///
3318/// # Returns
3319///
3320/// a random number
3321#[doc(alias = "g_random_double")]
3322pub fn random_double() -> f64 {
3323 unsafe { ffi::g_random_double() }
3324}
3325
3326/// Returns a random #gdouble equally distributed over the range
3327/// [@begin..@end).
3328/// ## `begin`
3329/// lower closed bound of the interval
3330/// ## `end`
3331/// upper open bound of the interval
3332///
3333/// # Returns
3334///
3335/// a random number
3336// rustdoc-stripper-ignore-next-stop
3337/// Returns a random #gdouble equally distributed over the range
3338/// [@begin..@end).
3339/// ## `begin`
3340/// lower closed bound of the interval
3341/// ## `end`
3342/// upper open bound of the interval
3343///
3344/// # Returns
3345///
3346/// a random number
3347#[doc(alias = "g_random_double_range")]
3348pub fn random_double_range(begin: f64, end: f64) -> f64 {
3349 unsafe { ffi::g_random_double_range(begin, end) }
3350}
3351
3352/// Return a random #guint32 equally distributed over the range
3353/// [0..2^32-1].
3354///
3355/// # Returns
3356///
3357/// a random number
3358// rustdoc-stripper-ignore-next-stop
3359/// Return a random #guint32 equally distributed over the range
3360/// [0..2^32-1].
3361///
3362/// # Returns
3363///
3364/// a random number
3365#[doc(alias = "g_random_int")]
3366pub fn random_int() -> u32 {
3367 unsafe { ffi::g_random_int() }
3368}
3369
3370/// Returns a random #gint32 equally distributed over the range
3371/// [@begin..@end-1].
3372/// ## `begin`
3373/// lower closed bound of the interval
3374/// ## `end`
3375/// upper open bound of the interval
3376///
3377/// # Returns
3378///
3379/// a random number
3380// rustdoc-stripper-ignore-next-stop
3381/// Returns a random #gint32 equally distributed over the range
3382/// [@begin..@end-1].
3383/// ## `begin`
3384/// lower closed bound of the interval
3385/// ## `end`
3386/// upper open bound of the interval
3387///
3388/// # Returns
3389///
3390/// a random number
3391#[doc(alias = "g_random_int_range")]
3392pub fn random_int_range(begin: i32, end: i32) -> i32 {
3393 unsafe { ffi::g_random_int_range(begin, end) }
3394}
3395
3396/// Sets the seed for the global random number generator, which is used
3397/// by the g_random_* functions, to @seed.
3398/// ## `seed`
3399/// a value to reinitialize the global random number generator
3400// rustdoc-stripper-ignore-next-stop
3401/// Sets the seed for the global random number generator, which is used
3402/// by the g_random_* functions, to @seed.
3403/// ## `seed`
3404/// a value to reinitialize the global random number generator
3405#[doc(alias = "g_random_set_seed")]
3406pub fn random_set_seed(seed: u32) {
3407 unsafe {
3408 ffi::g_random_set_seed(seed);
3409 }
3410}
3411
3412/// Resets the cache used for g_get_user_special_dir(), so
3413/// that the latest on-disk version is used. Call this only
3414/// if you just changed the data on disk yourself.
3415///
3416/// Due to thread safety issues this may cause leaking of strings
3417/// that were previously returned from g_get_user_special_dir()
3418/// that can't be freed. We ensure to only leak the data for
3419/// the directories that actually changed value though.
3420// rustdoc-stripper-ignore-next-stop
3421/// Resets the cache used for g_get_user_special_dir(), so
3422/// that the latest on-disk version is used. Call this only
3423/// if you just changed the data on disk yourself.
3424///
3425/// Due to thread safety issues this may cause leaking of strings
3426/// that were previously returned from g_get_user_special_dir()
3427/// that can't be freed. We ensure to only leak the data for
3428/// the directories that actually changed value though.
3429#[doc(alias = "g_reload_user_special_dirs_cache")]
3430pub fn reload_user_special_dirs_cache() {
3431 unsafe {
3432 ffi::g_reload_user_special_dirs_cache();
3433 }
3434}
3435
3436/// Sets a human-readable name for the application. This name should be
3437/// localized if possible, and is intended for display to the user.
3438/// Contrast with g_set_prgname(), which sets a non-localized name.
3439/// g_set_prgname() will be called automatically by gtk_init(),
3440/// but g_set_application_name() will not.
3441///
3442/// Note that for thread safety reasons, this function can only
3443/// be called once.
3444///
3445/// The application name will be used in contexts such as error messages,
3446/// or when displaying an application's name in the task list.
3447/// ## `application_name`
3448/// localized name of the application
3449// rustdoc-stripper-ignore-next-stop
3450/// Sets a human-readable name for the application. This name should be
3451/// localized if possible, and is intended for display to the user.
3452/// Contrast with g_set_prgname(), which sets a non-localized name.
3453/// g_set_prgname() will be called automatically by gtk_init(),
3454/// but g_set_application_name() will not.
3455///
3456/// Note that for thread safety reasons, this function can only
3457/// be called once.
3458///
3459/// The application name will be used in contexts such as error messages,
3460/// or when displaying an application's name in the task list.
3461/// ## `application_name`
3462/// localized name of the application
3463#[doc(alias = "g_set_application_name")]
3464pub fn set_application_name(application_name: &str) {
3465 unsafe {
3466 ffi::g_set_application_name(application_name.to_glib_none().0);
3467 }
3468}
3469
3470/// Sets an environment variable. On UNIX, both the variable's name and
3471/// value can be arbitrary byte strings, except that the variable's name
3472/// cannot contain '='. On Windows, they should be in UTF-8.
3473///
3474/// Note that on some systems, when variables are overwritten, the memory
3475/// used for the previous variables and its value isn't reclaimed.
3476///
3477/// You should be mindful of the fact that environment variable handling
3478/// in UNIX is not thread-safe, and your program may crash if one thread
3479/// calls g_setenv() while another thread is calling getenv(). (And note
3480/// that many functions, such as gettext(), call getenv() internally.)
3481/// This function is only safe to use at the very start of your program,
3482/// before creating any other threads (or creating objects that create
3483/// worker threads of their own).
3484///
3485/// If you need to set up the environment for a child process, you can
3486/// use g_get_environ() to get an environment array, modify that with
3487/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
3488/// array directly to execvpe(), g_spawn_async(), or the like.
3489/// ## `variable`
3490/// the environment variable to set, must not
3491/// contain '='.
3492/// ## `value`
3493/// the value for to set the variable to.
3494/// ## `overwrite`
3495/// whether to change the variable if it already exists.
3496///
3497/// # Returns
3498///
3499/// [`false`] if the environment variable couldn't be set.
3500// rustdoc-stripper-ignore-next-stop
3501/// Sets an environment variable. On UNIX, both the variable's name and
3502/// value can be arbitrary byte strings, except that the variable's name
3503/// cannot contain '='. On Windows, they should be in UTF-8.
3504///
3505/// Note that on some systems, when variables are overwritten, the memory
3506/// used for the previous variables and its value isn't reclaimed.
3507///
3508/// You should be mindful of the fact that environment variable handling
3509/// in UNIX is not thread-safe, and your program may crash if one thread
3510/// calls g_setenv() while another thread is calling getenv(). (And note
3511/// that many functions, such as gettext(), call getenv() internally.)
3512/// This function is only safe to use at the very start of your program,
3513/// before creating any other threads (or creating objects that create
3514/// worker threads of their own).
3515///
3516/// If you need to set up the environment for a child process, you can
3517/// use g_get_environ() to get an environment array, modify that with
3518/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
3519/// array directly to execvpe(), g_spawn_async(), or the like.
3520/// ## `variable`
3521/// the environment variable to set, must not
3522/// contain '='.
3523/// ## `value`
3524/// the value for to set the variable to.
3525/// ## `overwrite`
3526/// whether to change the variable if it already exists.
3527///
3528/// # Returns
3529///
3530/// [`false`] if the environment variable couldn't be set.
3531#[doc(alias = "g_setenv")]
3532pub fn setenv(
3533 variable: impl AsRef<std::ffi::OsStr>,
3534 value: impl AsRef<std::ffi::OsStr>,
3535 overwrite: bool,
3536) -> Result<(), crate::error::BoolError> {
3537 unsafe {
3538 crate::result_from_gboolean!(
3539 ffi::g_setenv(
3540 variable.as_ref().to_glib_none().0,
3541 value.as_ref().to_glib_none().0,
3542 overwrite.into_glib()
3543 ),
3544 "Failed to set environment variable"
3545 )
3546 }
3547}
3548
3549/// Parses a command line into an argument vector, in much the same way
3550/// the shell would, but without many of the expansions the shell would
3551/// perform (variable expansion, globs, operators, filename expansion,
3552/// etc. are not supported).
3553///
3554/// The results are defined to be the same as those you would get from
3555/// a UNIX98 `/bin/sh`, as long as the input contains none of the
3556/// unsupported shell expansions. If the input does contain such expansions,
3557/// they are passed through literally.
3558///
3559/// Possible errors are those from the `G_SHELL_ERROR` domain.
3560///
3561/// In particular, if @command_line is an empty string (or a string containing
3562/// only whitespace), `G_SHELL_ERROR_EMPTY_STRING` will be returned. It’s
3563/// guaranteed that @argvp will be a non-empty array if this function returns
3564/// successfully.
3565///
3566/// Free the returned vector with g_strfreev().
3567/// ## `command_line`
3568/// command line to parse
3569///
3570/// # Returns
3571///
3572/// [`true`] on success, [`false`] if error set
3573///
3574/// ## `argvp`
3575///
3576/// return location for array of args
3577// rustdoc-stripper-ignore-next-stop
3578/// Parses a command line into an argument vector, in much the same way
3579/// the shell would, but without many of the expansions the shell would
3580/// perform (variable expansion, globs, operators, filename expansion,
3581/// etc. are not supported).
3582///
3583/// The results are defined to be the same as those you would get from
3584/// a UNIX98 `/bin/sh`, as long as the input contains none of the
3585/// unsupported shell expansions. If the input does contain such expansions,
3586/// they are passed through literally.
3587///
3588/// Possible errors are those from the `G_SHELL_ERROR` domain.
3589///
3590/// In particular, if @command_line is an empty string (or a string containing
3591/// only whitespace), `G_SHELL_ERROR_EMPTY_STRING` will be returned. It’s
3592/// guaranteed that @argvp will be a non-empty array if this function returns
3593/// successfully.
3594///
3595/// Free the returned vector with g_strfreev().
3596/// ## `command_line`
3597/// command line to parse
3598///
3599/// # Returns
3600///
3601/// [`true`] on success, [`false`] if error set
3602///
3603/// ## `argvp`
3604///
3605/// return location for array of args
3606#[doc(alias = "g_shell_parse_argv")]
3607pub fn shell_parse_argv(
3608 command_line: impl AsRef<std::ffi::OsStr>,
3609) -> Result<Vec<std::ffi::OsString>, crate::Error> {
3610 unsafe {
3611 let mut argcp = std::mem::MaybeUninit::uninit();
3612 let mut argvp = std::ptr::null_mut();
3613 let mut error = std::ptr::null_mut();
3614 let is_ok = ffi::g_shell_parse_argv(
3615 command_line.as_ref().to_glib_none().0,
3616 argcp.as_mut_ptr(),
3617 &mut argvp,
3618 &mut error,
3619 );
3620 debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
3621 if error.is_null() {
3622 Ok(FromGlibContainer::from_glib_full_num(
3623 argvp,
3624 argcp.assume_init() as _,
3625 ))
3626 } else {
3627 Err(from_glib_full(error))
3628 }
3629 }
3630}
3631
3632/// Quotes a string so that the shell (/bin/sh) will interpret the
3633/// quoted string to mean @unquoted_string.
3634///
3635/// If you pass a filename to the shell, for example, you should first
3636/// quote it with this function.
3637///
3638/// The return value must be freed with g_free().
3639///
3640/// The quoting style used is undefined (single or double quotes may be
3641/// used).
3642/// ## `unquoted_string`
3643/// a literal string
3644///
3645/// # Returns
3646///
3647/// quoted string
3648// rustdoc-stripper-ignore-next-stop
3649/// Quotes a string so that the shell (/bin/sh) will interpret the
3650/// quoted string to mean @unquoted_string.
3651///
3652/// If you pass a filename to the shell, for example, you should first
3653/// quote it with this function.
3654///
3655/// The return value must be freed with g_free().
3656///
3657/// The quoting style used is undefined (single or double quotes may be
3658/// used).
3659/// ## `unquoted_string`
3660/// a literal string
3661///
3662/// # Returns
3663///
3664/// quoted string
3665#[doc(alias = "g_shell_quote")]
3666pub fn shell_quote(unquoted_string: impl AsRef<std::ffi::OsStr>) -> std::ffi::OsString {
3667 unsafe {
3668 from_glib_full(ffi::g_shell_quote(
3669 unquoted_string.as_ref().to_glib_none().0,
3670 ))
3671 }
3672}
3673
3674/// Unquotes a string as the shell (/bin/sh) would.
3675///
3676/// This function only handles quotes; if a string contains file globs,
3677/// arithmetic operators, variables, backticks, redirections, or other
3678/// special-to-the-shell features, the result will be different from the
3679/// result a real shell would produce (the variables, backticks, etc.
3680/// will be passed through literally instead of being expanded).
3681///
3682/// This function is guaranteed to succeed if applied to the result of
3683/// g_shell_quote(). If it fails, it returns [`None`] and sets the
3684/// error.
3685///
3686/// The @quoted_string need not actually contain quoted or escaped text;
3687/// g_shell_unquote() simply goes through the string and unquotes/unescapes
3688/// anything that the shell would. Both single and double quotes are
3689/// handled, as are escapes including escaped newlines.
3690///
3691/// The return value must be freed with g_free().
3692///
3693/// Possible errors are in the `G_SHELL_ERROR` domain.
3694///
3695/// Shell quoting rules are a bit strange. Single quotes preserve the
3696/// literal string exactly. escape sequences are not allowed; not even
3697/// `\'` - if you want a `'` in the quoted text, you have to do something
3698/// like `'foo'\''bar'`. Double quotes allow `$`, **⚠️ The following code is in , `"`, `\`, and ⚠️**
3699///
3700/// ```, `"`, `\`, and
3701/// newline to be escaped with backslash. Otherwise double quotes
3702/// preserve things literally.
3703/// ## `quoted_string`
3704/// shell-quoted string
3705///
3706/// # Returns
3707///
3708/// an unquoted string
3709// rustdoc-stripper-ignore-next-stop
3710/// Unquotes a string as the shell (/bin/sh) would.
3711///
3712/// This function only handles quotes; if a string contains file globs,
3713/// arithmetic operators, variables, backticks, redirections, or other
3714/// special-to-the-shell features, the result will be different from the
3715/// result a real shell would produce (the variables, backticks, etc.
3716/// will be passed through literally instead of being expanded).
3717///
3718/// This function is guaranteed to succeed if applied to the result of
3719/// g_shell_quote(). If it fails, it returns [`None`] and sets the
3720/// error.
3721///
3722/// The @quoted_string need not actually contain quoted or escaped text;
3723/// g_shell_unquote() simply goes through the string and unquotes/unescapes
3724/// anything that the shell would. Both single and double quotes are
3725/// handled, as are escapes including escaped newlines.
3726///
3727/// The return value must be freed with g_free().
3728///
3729/// Possible errors are in the `G_SHELL_ERROR` domain.
3730///
3731/// Shell quoting rules are a bit strange. Single quotes preserve the
3732/// literal string exactly. escape sequences are not allowed; not even
3733/// `\'` - if you want a `'` in the quoted text, you have to do something
3734/// like `'foo'\''bar'`. Double quotes allow `$`, **⚠️ The following code is in , `"`, `\`, and ⚠️**
3735///
3736/// ```, `"`, `\`, and
3737/// newline to be escaped with backslash. Otherwise double quotes
3738/// preserve things literally.
3739/// ## `quoted_string`
3740/// shell-quoted string
3741///
3742/// # Returns
3743///
3744/// an unquoted string
3745#[doc(alias = "g_shell_unquote")]
3746pub fn shell_unquote(
3747 quoted_string: impl AsRef<std::ffi::OsStr>,
3748) -> Result<std::ffi::OsString, crate::Error> {
3749 unsafe {
3750 let mut error = std::ptr::null_mut();
3751 let ret = ffi::g_shell_unquote(quoted_string.as_ref().to_glib_none().0, &mut error);
3752 if error.is_null() {
3753 Ok(from_glib_full(ret))
3754 } else {
3755 Err(from_glib_full(error))
3756 }
3757 }
3758}
3759
3760//#[cfg(feature = "v2_82")]
3761//#[cfg_attr(docsrs, doc(cfg(feature = "v2_82")))]
3762//#[doc(alias = "g_sort_array")]
3763//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>) {
3764// unsafe { TODO: call ffi:g_sort_array() }
3765//}
3766
3767/// Gets the smallest prime number from a built-in array of primes which
3768/// is larger than @num. This is used within GLib to calculate the optimum
3769/// size of a #GHashTable.
3770///
3771/// The built-in array of primes ranges from 11 to 13845163 such that
3772/// each prime is approximately 1.5-2 times the previous prime.
3773/// ## `num`
3774/// a #guint
3775///
3776/// # Returns
3777///
3778/// the smallest prime number from a built-in array of primes
3779/// which is larger than @num
3780// rustdoc-stripper-ignore-next-stop
3781/// Gets the smallest prime number from a built-in array of primes which
3782/// is larger than @num. This is used within GLib to calculate the optimum
3783/// size of a #GHashTable.
3784///
3785/// The built-in array of primes ranges from 11 to 13845163 such that
3786/// each prime is approximately 1.5-2 times the previous prime.
3787/// ## `num`
3788/// a #guint
3789///
3790/// # Returns
3791///
3792/// the smallest prime number from a built-in array of primes
3793/// which is larger than @num
3794#[doc(alias = "g_spaced_primes_closest")]
3795pub fn spaced_primes_closest(num: u32) -> u32 {
3796 unsafe { ffi::g_spaced_primes_closest(num) }
3797}
3798
3799/// Executes a child program asynchronously.
3800///
3801/// See g_spawn_async_with_pipes_and_fds() for a full description; this function
3802/// simply calls the g_spawn_async_with_pipes() without any pipes, which in turn
3803/// calls g_spawn_async_with_pipes_and_fds().
3804///
3805/// You should call g_spawn_close_pid() on the returned child process
3806/// reference when you don't need it any more.
3807///
3808/// If you are writing a GTK application, and the program you are spawning is a
3809/// graphical application too, then to ensure that the spawned program opens its
3810/// windows on the right screen, you may want to use #GdkAppLaunchContext,
3811/// #GAppLaunchContext, or set the `DISPLAY` environment variable.
3812///
3813/// Note that the returned @child_pid on Windows is a handle to the child
3814/// process and not its identifier. Process handles and process identifiers
3815/// are different concepts on Windows.
3816/// ## `working_directory`
3817/// child's current working
3818/// directory, or [`None`] to inherit parent's
3819/// ## `argv`
3820///
3821/// child's argument vector
3822/// ## `envp`
3823///
3824/// child's environment, or [`None`] to inherit parent's
3825/// ## `flags`
3826/// flags from #GSpawnFlags
3827/// ## `child_setup`
3828/// function to run
3829/// in the child just before `exec()`
3830///
3831/// # Returns
3832///
3833/// [`true`] on success, [`false`] if error is set
3834///
3835/// ## `child_pid`
3836/// return location for child process reference, or [`None`]
3837// rustdoc-stripper-ignore-next-stop
3838/// Executes a child program asynchronously.
3839///
3840/// See g_spawn_async_with_pipes_and_fds() for a full description; this function
3841/// simply calls the g_spawn_async_with_pipes() without any pipes, which in turn
3842/// calls g_spawn_async_with_pipes_and_fds().
3843///
3844/// You should call g_spawn_close_pid() on the returned child process
3845/// reference when you don't need it any more.
3846///
3847/// If you are writing a GTK application, and the program you are spawning is a
3848/// graphical application too, then to ensure that the spawned program opens its
3849/// windows on the right screen, you may want to use #GdkAppLaunchContext,
3850/// #GAppLaunchContext, or set the `DISPLAY` environment variable.
3851///
3852/// Note that the returned @child_pid on Windows is a handle to the child
3853/// process and not its identifier. Process handles and process identifiers
3854/// are different concepts on Windows.
3855/// ## `working_directory`
3856/// child's current working
3857/// directory, or [`None`] to inherit parent's
3858/// ## `argv`
3859///
3860/// child's argument vector
3861/// ## `envp`
3862///
3863/// child's environment, or [`None`] to inherit parent's
3864/// ## `flags`
3865/// flags from #GSpawnFlags
3866/// ## `child_setup`
3867/// function to run
3868/// in the child just before `exec()`
3869///
3870/// # Returns
3871///
3872/// [`true`] on success, [`false`] if error is set
3873///
3874/// ## `child_pid`
3875/// return location for child process reference, or [`None`]
3876#[doc(alias = "g_spawn_async")]
3877pub fn spawn_async(
3878 working_directory: Option<impl AsRef<std::path::Path>>,
3879 argv: &[&std::path::Path],
3880 envp: &[&std::path::Path],
3881 flags: SpawnFlags,
3882 child_setup: Option<Box_<dyn FnOnce() + 'static>>,
3883) -> Result<Pid, crate::Error> {
3884 let child_setup_data: Box_<Option<Box_<dyn FnOnce() + 'static>>> = Box_::new(child_setup);
3885 unsafe extern "C" fn child_setup_func(data: ffi::gpointer) {
3886 let callback = Box_::from_raw(data as *mut Option<Box_<dyn FnOnce() + 'static>>);
3887 let callback = (*callback).expect("cannot get closure...");
3888 callback()
3889 }
3890 let child_setup = if child_setup_data.is_some() {
3891 Some(child_setup_func as _)
3892 } else {
3893 None
3894 };
3895 let super_callback0: Box_<Option<Box_<dyn FnOnce() + 'static>>> = child_setup_data;
3896 unsafe {
3897 let mut child_pid = std::mem::MaybeUninit::uninit();
3898 let mut error = std::ptr::null_mut();
3899 let is_ok = ffi::g_spawn_async(
3900 working_directory
3901 .as_ref()
3902 .map(|p| p.as_ref())
3903 .to_glib_none()
3904 .0,
3905 argv.to_glib_none().0,
3906 envp.to_glib_none().0,
3907 flags.into_glib(),
3908 child_setup,
3909 Box_::into_raw(super_callback0) as *mut _,
3910 child_pid.as_mut_ptr(),
3911 &mut error,
3912 );
3913 debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
3914 if error.is_null() {
3915 Ok(from_glib(child_pid.assume_init()))
3916 } else {
3917 Err(from_glib_full(error))
3918 }
3919 }
3920}
3921
3922//#[cfg(feature = "v2_68")]
3923//#[cfg_attr(docsrs, doc(cfg(feature = "v2_68")))]
3924//#[doc(alias = "g_spawn_async_with_pipes_and_fds")]
3925//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> {
3926// unsafe { TODO: call ffi:g_spawn_async_with_pipes_and_fds() }
3927//}
3928
3929#[cfg_attr(feature = "v2_70", deprecated = "Since 2.70")]
3930#[allow(deprecated)]
3931#[doc(alias = "g_spawn_check_exit_status")]
3932pub fn spawn_check_exit_status(wait_status: i32) -> Result<(), crate::Error> {
3933 unsafe {
3934 let mut error = std::ptr::null_mut();
3935 let is_ok = ffi::g_spawn_check_exit_status(wait_status, &mut error);
3936 debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
3937 if error.is_null() {
3938 Ok(())
3939 } else {
3940 Err(from_glib_full(error))
3941 }
3942 }
3943}
3944
3945#[cfg(feature = "v2_70")]
3946#[cfg_attr(docsrs, doc(cfg(feature = "v2_70")))]
3947#[doc(alias = "g_spawn_check_wait_status")]
3948pub fn spawn_check_wait_status(wait_status: i32) -> Result<(), crate::Error> {
3949 unsafe {
3950 let mut error = std::ptr::null_mut();
3951 let is_ok = ffi::g_spawn_check_wait_status(wait_status, &mut error);
3952 debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
3953 if error.is_null() {
3954 Ok(())
3955 } else {
3956 Err(from_glib_full(error))
3957 }
3958 }
3959}
3960
3961/// A simple version of g_spawn_async() that parses a command line with
3962/// g_shell_parse_argv() and passes it to g_spawn_async().
3963///
3964/// Runs a command line in the background. Unlike g_spawn_async(), the
3965/// [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] flag is enabled, other flags are not. Note
3966/// that [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] can have security implications, so
3967/// consider using g_spawn_async() directly if appropriate. Possible
3968/// errors are those from g_shell_parse_argv() and g_spawn_async().
3969///
3970/// The same concerns on Windows apply as for g_spawn_command_line_sync().
3971/// ## `command_line`
3972/// a command line
3973///
3974/// # Returns
3975///
3976/// [`true`] on success, [`false`] if error is set
3977// rustdoc-stripper-ignore-next-stop
3978/// A simple version of g_spawn_async() that parses a command line with
3979/// g_shell_parse_argv() and passes it to g_spawn_async().
3980///
3981/// Runs a command line in the background. Unlike g_spawn_async(), the
3982/// [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] flag is enabled, other flags are not. Note
3983/// that [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] can have security implications, so
3984/// consider using g_spawn_async() directly if appropriate. Possible
3985/// errors are those from g_shell_parse_argv() and g_spawn_async().
3986///
3987/// The same concerns on Windows apply as for g_spawn_command_line_sync().
3988/// ## `command_line`
3989/// a command line
3990///
3991/// # Returns
3992///
3993/// [`true`] on success, [`false`] if error is set
3994#[cfg(unix)]
3995#[cfg_attr(docsrs, doc(cfg(unix)))]
3996#[doc(alias = "g_spawn_command_line_async")]
3997pub fn spawn_command_line_async(
3998 command_line: impl AsRef<std::ffi::OsStr>,
3999) -> Result<(), crate::Error> {
4000 unsafe {
4001 let mut error = std::ptr::null_mut();
4002 let is_ok =
4003 ffi::g_spawn_command_line_async(command_line.as_ref().to_glib_none().0, &mut error);
4004 debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
4005 if error.is_null() {
4006 Ok(())
4007 } else {
4008 Err(from_glib_full(error))
4009 }
4010 }
4011}
4012
4013//#[doc(alias = "g_spawn_command_line_sync")]
4014//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> {
4015// unsafe { TODO: call ffi:g_spawn_command_line_sync() }
4016//}
4017
4018//#[doc(alias = "g_spawn_sync")]
4019//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> {
4020// unsafe { TODO: call ffi:g_spawn_sync() }
4021//}
4022
4023//#[doc(alias = "g_stat")]
4024//pub fn stat(filename: impl AsRef<std::path::Path>, buf: /*Ignored*/&mut StatBuf) -> i32 {
4025// unsafe { TODO: call ffi:g_stat() }
4026//}
4027
4028//#[cfg(unix)]
4029//#[cfg_attr(docsrs, doc(cfg(unix)))]
4030//#[cfg(feature = "v2_64")]
4031//#[cfg_attr(docsrs, doc(cfg(feature = "v2_64")))]
4032//#[doc(alias = "g_unix_get_passwd_entry")]
4033//pub fn unix_get_passwd_entry(user_name: &str) -> Result</*Unimplemented*/Option<Basic: Pointer>, crate::Error> {
4034// unsafe { TODO: call ffi:g_unix_get_passwd_entry() }
4035//}
4036
4037/// A wrapper for the POSIX unlink() function. The unlink() function
4038/// deletes a name from the filesystem. If this was the last link to the
4039/// file and no processes have it opened, the diskspace occupied by the
4040/// file is freed.
4041///
4042/// See your C library manual for more details about unlink(). Note
4043/// that on Windows, it is in general not possible to delete files that
4044/// are open to some process, or mapped into memory.
4045/// ## `filename`
4046/// a pathname in the GLib file name encoding
4047/// (UTF-8 on Windows)
4048///
4049/// # Returns
4050///
4051/// 0 if the name was successfully deleted, -1 if an error
4052/// occurred
4053// rustdoc-stripper-ignore-next-stop
4054/// A wrapper for the POSIX unlink() function. The unlink() function
4055/// deletes a name from the filesystem. If this was the last link to the
4056/// file and no processes have it opened, the diskspace occupied by the
4057/// file is freed.
4058///
4059/// See your C library manual for more details about unlink(). Note
4060/// that on Windows, it is in general not possible to delete files that
4061/// are open to some process, or mapped into memory.
4062/// ## `filename`
4063/// a pathname in the GLib file name encoding
4064/// (UTF-8 on Windows)
4065///
4066/// # Returns
4067///
4068/// 0 if the name was successfully deleted, -1 if an error
4069/// occurred
4070#[doc(alias = "g_unlink")]
4071pub fn unlink(filename: impl AsRef<std::path::Path>) -> i32 {
4072 unsafe { ffi::g_unlink(filename.as_ref().to_glib_none().0) }
4073}
4074
4075/// Removes an environment variable from the environment.
4076///
4077/// Note that on some systems, when variables are overwritten, the
4078/// memory used for the previous variables and its value isn't reclaimed.
4079///
4080/// You should be mindful of the fact that environment variable handling
4081/// in UNIX is not thread-safe, and your program may crash if one thread
4082/// calls g_unsetenv() while another thread is calling getenv(). (And note
4083/// that many functions, such as gettext(), call getenv() internally.) This
4084/// function is only safe to use at the very start of your program, before
4085/// creating any other threads (or creating objects that create worker
4086/// threads of their own).
4087///
4088/// If you need to set up the environment for a child process, you can
4089/// use g_get_environ() to get an environment array, modify that with
4090/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
4091/// array directly to execvpe(), g_spawn_async(), or the like.
4092/// ## `variable`
4093/// the environment variable to remove, must
4094/// not contain '='
4095// rustdoc-stripper-ignore-next-stop
4096/// Removes an environment variable from the environment.
4097///
4098/// Note that on some systems, when variables are overwritten, the
4099/// memory used for the previous variables and its value isn't reclaimed.
4100///
4101/// You should be mindful of the fact that environment variable handling
4102/// in UNIX is not thread-safe, and your program may crash if one thread
4103/// calls g_unsetenv() while another thread is calling getenv(). (And note
4104/// that many functions, such as gettext(), call getenv() internally.) This
4105/// function is only safe to use at the very start of your program, before
4106/// creating any other threads (or creating objects that create worker
4107/// threads of their own).
4108///
4109/// If you need to set up the environment for a child process, you can
4110/// use g_get_environ() to get an environment array, modify that with
4111/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
4112/// array directly to execvpe(), g_spawn_async(), or the like.
4113/// ## `variable`
4114/// the environment variable to remove, must
4115/// not contain '='
4116#[doc(alias = "g_unsetenv")]
4117pub fn unsetenv(variable: impl AsRef<std::ffi::OsStr>) {
4118 unsafe {
4119 ffi::g_unsetenv(variable.as_ref().to_glib_none().0);
4120 }
4121}
4122
4123/// Pauses the current thread for the given number of microseconds.
4124///
4125/// There are 1 million microseconds per second (represented by the
4126/// `G_USEC_PER_SEC` macro). g_usleep() may have limited precision,
4127/// depending on hardware and operating system; don't rely on the exact
4128/// length of the sleep.
4129/// ## `microseconds`
4130/// number of microseconds to pause
4131// rustdoc-stripper-ignore-next-stop
4132/// Pauses the current thread for the given number of microseconds.
4133///
4134/// There are 1 million microseconds per second (represented by the
4135/// `G_USEC_PER_SEC` macro). g_usleep() may have limited precision,
4136/// depending on hardware and operating system; don't rely on the exact
4137/// length of the sleep.
4138/// ## `microseconds`
4139/// number of microseconds to pause
4140#[doc(alias = "g_usleep")]
4141pub fn usleep(microseconds: libc::c_ulong) {
4142 unsafe {
4143 ffi::g_usleep(microseconds);
4144 }
4145}
4146
4147/// Parses the string @str and verify if it is a UUID.
4148///
4149/// The function accepts the following syntax:
4150///
4151/// - simple forms (e.g. `f81d4fae-7dec-11d0-a765-00a0c91e6bf6`)
4152///
4153/// Note that hyphens are required within the UUID string itself,
4154/// as per the aforementioned RFC.
4155/// ## `str`
4156/// a string representing a UUID
4157///
4158/// # Returns
4159///
4160/// [`true`] if @str is a valid UUID, [`false`] otherwise.
4161// rustdoc-stripper-ignore-next-stop
4162/// Parses the string @str and verify if it is a UUID.
4163///
4164/// The function accepts the following syntax:
4165///
4166/// - simple forms (e.g. `f81d4fae-7dec-11d0-a765-00a0c91e6bf6`)
4167///
4168/// Note that hyphens are required within the UUID string itself,
4169/// as per the aforementioned RFC.
4170/// ## `str`
4171/// a string representing a UUID
4172///
4173/// # Returns
4174///
4175/// [`true`] if @str is a valid UUID, [`false`] otherwise.
4176#[doc(alias = "g_uuid_string_is_valid")]
4177pub fn uuid_string_is_valid(str: &str) -> bool {
4178 unsafe { from_glib(ffi::g_uuid_string_is_valid(str.to_glib_none().0)) }
4179}
4180
4181/// Generates a random UUID (RFC 4122 version 4) as a string. It has the same
4182/// randomness guarantees as #GRand, so must not be used for cryptographic
4183/// purposes such as key generation, nonces, salts or one-time pads.
4184///
4185/// # Returns
4186///
4187/// A string that should be freed with g_free().
4188// rustdoc-stripper-ignore-next-stop
4189/// Generates a random UUID (RFC 4122 version 4) as a string. It has the same
4190/// randomness guarantees as #GRand, so must not be used for cryptographic
4191/// purposes such as key generation, nonces, salts or one-time pads.
4192///
4193/// # Returns
4194///
4195/// A string that should be freed with g_free().
4196#[doc(alias = "g_uuid_string_random")]
4197pub fn uuid_string_random() -> crate::GString {
4198 unsafe { from_glib_full(ffi::g_uuid_string_random()) }
4199}