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