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#[doc(alias = "g_access")]
15pub fn access(filename: impl AsRef<std::path::Path>, mode: i32) -> i32 {
16    unsafe { ffi::g_access(filename.as_ref().to_glib_none().0, mode) }
17}
18
19#[doc(alias = "g_base64_decode")]
20pub fn base64_decode(text: &str) -> Vec<u8> {
21    unsafe {
22        let mut out_len = std::mem::MaybeUninit::uninit();
23        let ret = FromGlibContainer::from_glib_full_num(
24            ffi::g_base64_decode(text.to_glib_none().0, out_len.as_mut_ptr()),
25            out_len.assume_init() as _,
26        );
27        ret
28    }
29}
30
31//#[doc(alias = "g_base64_decode_inplace")]
32//pub fn base64_decode_inplace(text: /*Unimplemented*/Vec<u8>) -> u8 {
33//    unsafe { TODO: call ffi:g_base64_decode_inplace() }
34//}
35
36//#[doc(alias = "g_base64_decode_step")]
37//pub fn base64_decode_step(in_: &[u8], out: Vec<u8>, state: &mut i32, save: &mut u32) -> usize {
38//    unsafe { TODO: call ffi:g_base64_decode_step() }
39//}
40
41#[doc(alias = "g_base64_encode")]
42pub fn base64_encode(data: &[u8]) -> crate::GString {
43    let len = data.len() as _;
44    unsafe { from_glib_full(ffi::g_base64_encode(data.to_glib_none().0, len)) }
45}
46
47//#[doc(alias = "g_base64_encode_close")]
48//pub fn base64_encode_close(break_lines: bool, out: Vec<u8>, state: &mut i32, save: &mut i32) -> usize {
49//    unsafe { TODO: call ffi:g_base64_encode_close() }
50//}
51
52//#[doc(alias = "g_base64_encode_step")]
53//pub fn base64_encode_step(in_: &[u8], break_lines: bool, out: Vec<u8>, state: &mut i32, save: &mut i32) -> usize {
54//    unsafe { TODO: call ffi:g_base64_encode_step() }
55//}
56
57#[doc(alias = "glib_check_version")]
58pub fn check_version(
59    required_major: u32,
60    required_minor: u32,
61    required_micro: u32,
62) -> Option<crate::GString> {
63    unsafe {
64        from_glib_none(ffi::glib_check_version(
65            required_major,
66            required_minor,
67            required_micro,
68        ))
69    }
70}
71
72#[doc(alias = "g_compute_checksum_for_bytes")]
73pub fn compute_checksum_for_bytes(
74    checksum_type: ChecksumType,
75    data: &Bytes,
76) -> Option<crate::GString> {
77    unsafe {
78        from_glib_full(ffi::g_compute_checksum_for_bytes(
79            checksum_type.into_glib(),
80            data.to_glib_none().0,
81        ))
82    }
83}
84
85#[doc(alias = "g_compute_checksum_for_data")]
86pub fn compute_checksum_for_data(
87    checksum_type: ChecksumType,
88    data: &[u8],
89) -> Option<crate::GString> {
90    let length = data.len() as _;
91    unsafe {
92        from_glib_full(ffi::g_compute_checksum_for_data(
93            checksum_type.into_glib(),
94            data.to_glib_none().0,
95            length,
96        ))
97    }
98}
99
100#[doc(alias = "g_compute_hmac_for_bytes")]
101pub fn compute_hmac_for_bytes(
102    digest_type: ChecksumType,
103    key: &Bytes,
104    data: &Bytes,
105) -> crate::GString {
106    unsafe {
107        from_glib_full(ffi::g_compute_hmac_for_bytes(
108            digest_type.into_glib(),
109            key.to_glib_none().0,
110            data.to_glib_none().0,
111        ))
112    }
113}
114
115#[doc(alias = "g_compute_hmac_for_data")]
116pub fn compute_hmac_for_data(digest_type: ChecksumType, key: &[u8], data: &[u8]) -> crate::GString {
117    let key_len = key.len() as _;
118    let length = data.len() as _;
119    unsafe {
120        from_glib_full(ffi::g_compute_hmac_for_data(
121            digest_type.into_glib(),
122            key.to_glib_none().0,
123            key_len,
124            data.to_glib_none().0,
125            length,
126        ))
127    }
128}
129
130#[doc(alias = "g_dcgettext")]
131pub fn dcgettext(domain: Option<&str>, msgid: &str, category: i32) -> crate::GString {
132    unsafe {
133        from_glib_none(ffi::g_dcgettext(
134            domain.to_glib_none().0,
135            msgid.to_glib_none().0,
136            category,
137        ))
138    }
139}
140
141#[doc(alias = "g_dgettext")]
142pub fn dgettext(domain: Option<&str>, msgid: &str) -> crate::GString {
143    unsafe {
144        from_glib_none(ffi::g_dgettext(
145            domain.to_glib_none().0,
146            msgid.to_glib_none().0,
147        ))
148    }
149}
150
151#[doc(alias = "g_dngettext")]
152pub fn dngettext(
153    domain: Option<&str>,
154    msgid: &str,
155    msgid_plural: &str,
156    n: libc::c_ulong,
157) -> crate::GString {
158    unsafe {
159        from_glib_none(ffi::g_dngettext(
160            domain.to_glib_none().0,
161            msgid.to_glib_none().0,
162            msgid_plural.to_glib_none().0,
163            n,
164        ))
165    }
166}
167
168#[doc(alias = "g_dpgettext")]
169pub fn dpgettext(domain: Option<&str>, msgctxtid: &str, msgidoffset: usize) -> crate::GString {
170    unsafe {
171        from_glib_none(ffi::g_dpgettext(
172            domain.to_glib_none().0,
173            msgctxtid.to_glib_none().0,
174            msgidoffset,
175        ))
176    }
177}
178
179#[doc(alias = "g_dpgettext2")]
180pub fn dpgettext2(domain: Option<&str>, context: &str, msgid: &str) -> crate::GString {
181    unsafe {
182        from_glib_none(ffi::g_dpgettext2(
183            domain.to_glib_none().0,
184            context.to_glib_none().0,
185            msgid.to_glib_none().0,
186        ))
187    }
188}
189
190#[doc(alias = "g_file_set_contents")]
191pub fn file_set_contents(
192    filename: impl AsRef<std::path::Path>,
193    contents: &[u8],
194) -> Result<(), crate::Error> {
195    let length = contents.len() as _;
196    unsafe {
197        let mut error = std::ptr::null_mut();
198        let is_ok = ffi::g_file_set_contents(
199            filename.as_ref().to_glib_none().0,
200            contents.to_glib_none().0,
201            length,
202            &mut error,
203        );
204        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
205        if error.is_null() {
206            Ok(())
207        } else {
208            Err(from_glib_full(error))
209        }
210    }
211}
212
213#[cfg(feature = "v2_66")]
214#[cfg_attr(docsrs, doc(cfg(feature = "v2_66")))]
215#[doc(alias = "g_file_set_contents_full")]
216pub fn file_set_contents_full(
217    filename: impl AsRef<std::path::Path>,
218    contents: &[u8],
219    flags: FileSetContentsFlags,
220    mode: i32,
221) -> Result<(), crate::Error> {
222    let length = contents.len() as _;
223    unsafe {
224        let mut error = std::ptr::null_mut();
225        let is_ok = ffi::g_file_set_contents_full(
226            filename.as_ref().to_glib_none().0,
227            contents.to_glib_none().0,
228            length,
229            flags.into_glib(),
230            mode,
231            &mut error,
232        );
233        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
234        if error.is_null() {
235            Ok(())
236        } else {
237            Err(from_glib_full(error))
238        }
239    }
240}
241
242#[doc(alias = "g_file_test")]
243#[allow(dead_code)]
244pub(crate) fn file_test(filename: impl AsRef<std::path::Path>, test: FileTest) -> bool {
245    unsafe {
246        from_glib(ffi::g_file_test(
247            filename.as_ref().to_glib_none().0,
248            test.into_glib(),
249        ))
250    }
251}
252
253#[doc(alias = "g_filename_display_basename")]
254pub fn filename_display_basename(filename: impl AsRef<std::path::Path>) -> crate::GString {
255    unsafe {
256        from_glib_full(ffi::g_filename_display_basename(
257            filename.as_ref().to_glib_none().0,
258        ))
259    }
260}
261
262#[doc(alias = "g_filename_display_name")]
263pub fn filename_display_name(filename: impl AsRef<std::path::Path>) -> crate::GString {
264    unsafe {
265        from_glib_full(ffi::g_filename_display_name(
266            filename.as_ref().to_glib_none().0,
267        ))
268    }
269}
270
271#[doc(alias = "g_filename_from_uri")]
272pub fn filename_from_uri(
273    uri: &str,
274) -> Result<(std::path::PathBuf, Option<crate::GString>), crate::Error> {
275    unsafe {
276        let mut hostname = std::ptr::null_mut();
277        let mut error = std::ptr::null_mut();
278        let ret = ffi::g_filename_from_uri(uri.to_glib_none().0, &mut hostname, &mut error);
279        if error.is_null() {
280            Ok((from_glib_full(ret), from_glib_full(hostname)))
281        } else {
282            Err(from_glib_full(error))
283        }
284    }
285}
286
287#[doc(alias = "g_filename_to_uri")]
288pub fn filename_to_uri(
289    filename: impl AsRef<std::path::Path>,
290    hostname: Option<&str>,
291) -> Result<crate::GString, crate::Error> {
292    unsafe {
293        let mut error = std::ptr::null_mut();
294        let ret = ffi::g_filename_to_uri(
295            filename.as_ref().to_glib_none().0,
296            hostname.to_glib_none().0,
297            &mut error,
298        );
299        if error.is_null() {
300            Ok(from_glib_full(ret))
301        } else {
302            Err(from_glib_full(error))
303        }
304    }
305}
306
307#[doc(alias = "g_find_program_in_path")]
308pub fn find_program_in_path(program: impl AsRef<std::path::Path>) -> Option<std::path::PathBuf> {
309    unsafe {
310        from_glib_full(ffi::g_find_program_in_path(
311            program.as_ref().to_glib_none().0,
312        ))
313    }
314}
315
316#[doc(alias = "g_format_size")]
317pub fn format_size(size: u64) -> crate::GString {
318    unsafe { from_glib_full(ffi::g_format_size(size)) }
319}
320
321#[doc(alias = "g_format_size_full")]
322pub fn format_size_full(size: u64, flags: FormatSizeFlags) -> crate::GString {
323    unsafe { from_glib_full(ffi::g_format_size_full(size, flags.into_glib())) }
324}
325
326#[doc(alias = "g_get_application_name")]
327#[doc(alias = "get_application_name")]
328pub fn application_name() -> Option<crate::GString> {
329    unsafe { from_glib_none(ffi::g_get_application_name()) }
330}
331
332#[doc(alias = "g_get_codeset")]
333#[doc(alias = "get_codeset")]
334pub fn codeset() -> crate::GString {
335    unsafe { from_glib_full(ffi::g_get_codeset()) }
336}
337
338#[cfg(feature = "v2_62")]
339#[cfg_attr(docsrs, doc(cfg(feature = "v2_62")))]
340#[doc(alias = "g_get_console_charset")]
341#[doc(alias = "get_console_charset")]
342pub fn console_charset() -> Option<crate::GString> {
343    unsafe {
344        let mut charset = std::ptr::null();
345        let ret = from_glib(ffi::g_get_console_charset(&mut charset));
346        if ret {
347            Some(from_glib_none(charset))
348        } else {
349            None
350        }
351    }
352}
353
354#[doc(alias = "g_get_current_dir")]
355#[doc(alias = "get_current_dir")]
356pub fn current_dir() -> std::path::PathBuf {
357    unsafe { from_glib_full(ffi::g_get_current_dir()) }
358}
359
360#[doc(alias = "g_get_environ")]
361#[doc(alias = "get_environ")]
362pub fn environ() -> Vec<std::ffi::OsString> {
363    unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_get_environ()) }
364}
365
366#[doc(alias = "g_get_home_dir")]
367#[doc(alias = "get_home_dir")]
368pub fn home_dir() -> std::path::PathBuf {
369    unsafe { from_glib_none(ffi::g_get_home_dir()) }
370}
371
372#[doc(alias = "g_get_host_name")]
373#[doc(alias = "get_host_name")]
374pub fn host_name() -> crate::GString {
375    unsafe { from_glib_none(ffi::g_get_host_name()) }
376}
377
378#[doc(alias = "g_get_language_names")]
379#[doc(alias = "get_language_names")]
380pub fn language_names() -> Vec<crate::GString> {
381    unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_language_names()) }
382}
383
384#[cfg(feature = "v2_58")]
385#[cfg_attr(docsrs, doc(cfg(feature = "v2_58")))]
386#[doc(alias = "g_get_language_names_with_category")]
387#[doc(alias = "get_language_names_with_category")]
388pub fn language_names_with_category(category_name: &str) -> Vec<crate::GString> {
389    unsafe {
390        FromGlibPtrContainer::from_glib_none(ffi::g_get_language_names_with_category(
391            category_name.to_glib_none().0,
392        ))
393    }
394}
395
396#[doc(alias = "g_get_locale_variants")]
397#[doc(alias = "get_locale_variants")]
398pub fn locale_variants(locale: &str) -> Vec<crate::GString> {
399    unsafe {
400        FromGlibPtrContainer::from_glib_full(ffi::g_get_locale_variants(locale.to_glib_none().0))
401    }
402}
403
404#[doc(alias = "g_get_monotonic_time")]
405#[doc(alias = "get_monotonic_time")]
406pub fn monotonic_time() -> i64 {
407    unsafe { ffi::g_get_monotonic_time() }
408}
409
410#[doc(alias = "g_get_num_processors")]
411#[doc(alias = "get_num_processors")]
412pub fn num_processors() -> u32 {
413    unsafe { ffi::g_get_num_processors() }
414}
415
416#[cfg(feature = "v2_64")]
417#[cfg_attr(docsrs, doc(cfg(feature = "v2_64")))]
418#[doc(alias = "g_get_os_info")]
419#[doc(alias = "get_os_info")]
420pub fn os_info(key_name: &str) -> Option<crate::GString> {
421    unsafe { from_glib_full(ffi::g_get_os_info(key_name.to_glib_none().0)) }
422}
423
424#[doc(alias = "g_get_real_name")]
425#[doc(alias = "get_real_name")]
426pub fn real_name() -> std::ffi::OsString {
427    unsafe { from_glib_none(ffi::g_get_real_name()) }
428}
429
430#[doc(alias = "g_get_real_time")]
431#[doc(alias = "get_real_time")]
432pub fn real_time() -> i64 {
433    unsafe { ffi::g_get_real_time() }
434}
435
436#[doc(alias = "g_get_system_config_dirs")]
437#[doc(alias = "get_system_config_dirs")]
438pub fn system_config_dirs() -> Vec<std::path::PathBuf> {
439    unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_system_config_dirs()) }
440}
441
442#[doc(alias = "g_get_system_data_dirs")]
443#[doc(alias = "get_system_data_dirs")]
444pub fn system_data_dirs() -> Vec<std::path::PathBuf> {
445    unsafe { FromGlibPtrContainer::from_glib_none(ffi::g_get_system_data_dirs()) }
446}
447
448#[doc(alias = "g_get_tmp_dir")]
449#[doc(alias = "get_tmp_dir")]
450pub fn tmp_dir() -> std::path::PathBuf {
451    unsafe { from_glib_none(ffi::g_get_tmp_dir()) }
452}
453
454#[doc(alias = "g_get_user_cache_dir")]
455#[doc(alias = "get_user_cache_dir")]
456pub fn user_cache_dir() -> std::path::PathBuf {
457    unsafe { from_glib_none(ffi::g_get_user_cache_dir()) }
458}
459
460#[doc(alias = "g_get_user_config_dir")]
461#[doc(alias = "get_user_config_dir")]
462pub fn user_config_dir() -> std::path::PathBuf {
463    unsafe { from_glib_none(ffi::g_get_user_config_dir()) }
464}
465
466#[doc(alias = "g_get_user_data_dir")]
467#[doc(alias = "get_user_data_dir")]
468pub fn user_data_dir() -> std::path::PathBuf {
469    unsafe { from_glib_none(ffi::g_get_user_data_dir()) }
470}
471
472#[doc(alias = "g_get_user_name")]
473#[doc(alias = "get_user_name")]
474pub fn user_name() -> std::ffi::OsString {
475    unsafe { from_glib_none(ffi::g_get_user_name()) }
476}
477
478#[doc(alias = "g_get_user_runtime_dir")]
479#[doc(alias = "get_user_runtime_dir")]
480pub fn user_runtime_dir() -> std::path::PathBuf {
481    unsafe { from_glib_none(ffi::g_get_user_runtime_dir()) }
482}
483
484#[doc(alias = "g_get_user_special_dir")]
485#[doc(alias = "get_user_special_dir")]
486pub fn user_special_dir(directory: UserDirectory) -> Option<std::path::PathBuf> {
487    unsafe { from_glib_none(ffi::g_get_user_special_dir(directory.into_glib())) }
488}
489
490#[cfg(feature = "v2_72")]
491#[cfg_attr(docsrs, doc(cfg(feature = "v2_72")))]
492#[doc(alias = "g_get_user_state_dir")]
493#[doc(alias = "get_user_state_dir")]
494pub fn user_state_dir() -> std::path::PathBuf {
495    unsafe { from_glib_none(ffi::g_get_user_state_dir()) }
496}
497
498#[doc(alias = "g_getenv")]
499pub fn getenv(variable: impl AsRef<std::ffi::OsStr>) -> Option<std::ffi::OsString> {
500    unsafe { from_glib_none(ffi::g_getenv(variable.as_ref().to_glib_none().0)) }
501}
502
503/// Tests if @hostname contains segments with an ASCII-compatible
504/// encoding of an Internationalized Domain Name. If this returns
505/// [`true`], you should decode the hostname with g_hostname_to_unicode()
506/// before displaying it to the user.
507///
508/// Note that a hostname might contain a mix of encoded and unencoded
509/// segments, and so it is possible for g_hostname_is_non_ascii() and
510/// g_hostname_is_ascii_encoded() to both return [`true`] for a name.
511/// ## `hostname`
512/// a hostname
513///
514/// # Returns
515///
516/// [`true`] if @hostname contains any ASCII-encoded
517/// segments.
518#[doc(alias = "g_hostname_is_ascii_encoded")]
519pub fn hostname_is_ascii_encoded(hostname: &str) -> bool {
520    unsafe { from_glib(ffi::g_hostname_is_ascii_encoded(hostname.to_glib_none().0)) }
521}
522
523/// Tests if @hostname is the string form of an IPv4 or IPv6 address.
524/// (Eg, "192.168.0.1".)
525///
526/// Since 2.66, IPv6 addresses with a zone-id are accepted (RFC6874).
527/// ## `hostname`
528/// a hostname (or IP address in string form)
529///
530/// # Returns
531///
532/// [`true`] if @hostname is an IP address
533#[doc(alias = "g_hostname_is_ip_address")]
534pub fn hostname_is_ip_address(hostname: &str) -> bool {
535    unsafe { from_glib(ffi::g_hostname_is_ip_address(hostname.to_glib_none().0)) }
536}
537
538/// Tests if @hostname contains Unicode characters. If this returns
539/// [`true`], you need to encode the hostname with g_hostname_to_ascii()
540/// before using it in non-IDN-aware contexts.
541///
542/// Note that a hostname might contain a mix of encoded and unencoded
543/// segments, and so it is possible for g_hostname_is_non_ascii() and
544/// g_hostname_is_ascii_encoded() to both return [`true`] for a name.
545/// ## `hostname`
546/// a hostname
547///
548/// # Returns
549///
550/// [`true`] if @hostname contains any non-ASCII characters
551#[doc(alias = "g_hostname_is_non_ascii")]
552pub fn hostname_is_non_ascii(hostname: &str) -> bool {
553    unsafe { from_glib(ffi::g_hostname_is_non_ascii(hostname.to_glib_none().0)) }
554}
555
556/// Converts @hostname to its canonical ASCII form; an ASCII-only
557/// string containing no uppercase letters and not ending with a
558/// trailing dot.
559/// ## `hostname`
560/// a valid UTF-8 or ASCII hostname
561///
562/// # Returns
563///
564/// an ASCII hostname, which must be freed,
565///    or [`None`] if @hostname is in some way invalid.
566#[doc(alias = "g_hostname_to_ascii")]
567pub fn hostname_to_ascii(hostname: &str) -> Option<crate::GString> {
568    unsafe { from_glib_full(ffi::g_hostname_to_ascii(hostname.to_glib_none().0)) }
569}
570
571/// Converts @hostname to its canonical presentation form; a UTF-8
572/// string in Unicode normalization form C, containing no uppercase
573/// letters, no forbidden characters, and no ASCII-encoded segments,
574/// and not ending with a trailing dot.
575///
576/// Of course if @hostname is not an internationalized hostname, then
577/// the canonical presentation form will be entirely ASCII.
578/// ## `hostname`
579/// a valid UTF-8 or ASCII hostname
580///
581/// # Returns
582///
583/// a UTF-8 hostname, which must be freed,
584///    or [`None`] if @hostname is in some way invalid.
585#[doc(alias = "g_hostname_to_unicode")]
586pub fn hostname_to_unicode(hostname: &str) -> Option<crate::GString> {
587    unsafe { from_glib_full(ffi::g_hostname_to_unicode(hostname.to_glib_none().0)) }
588}
589
590/// Gets the names of all variables set in the environment.
591///
592/// Programs that want to be portable to Windows should typically use
593/// this function and g_getenv() instead of using the environ array
594/// from the C library directly. On Windows, the strings in the environ
595/// array are in system codepage encoding, while in most of the typical
596/// use cases for environment variables in GLib-using programs you want
597/// the UTF-8 encoding that this function and g_getenv() provide.
598///
599/// # Returns
600///
601///
602///     a [`None`]-terminated list of strings which must be freed with
603///     g_strfreev().
604#[doc(alias = "g_listenv")]
605pub fn listenv() -> Vec<std::ffi::OsString> {
606    unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_listenv()) }
607}
608
609/// Returns the currently firing source for this thread.
610///
611/// # Returns
612///
613/// The currently firing source or [`None`].
614#[doc(alias = "g_main_current_source")]
615pub fn main_current_source() -> Option<Source> {
616    unsafe { from_glib_none(ffi::g_main_current_source()) }
617}
618
619/// Returns the depth of the stack of calls to
620/// [`MainContext::dispatch()`][crate::MainContext::dispatch()] on any #GMainContext in the current thread.
621/// That is, when called from the toplevel, it gives 0. When
622/// called from within a callback from [`MainContext::iteration()`][crate::MainContext::iteration()]
623/// (or [`MainLoop::run()`][crate::MainLoop::run()], etc.) it returns 1. When called from within
624/// a callback to a recursive call to [`MainContext::iteration()`][crate::MainContext::iteration()],
625/// it returns 2. And so forth.
626///
627/// This function is useful in a situation like the following:
628/// Imagine an extremely simple "garbage collected" system.
629///
630///
631///
632/// **⚠️ The following code is in C ⚠️**
633///
634/// ```C
635/// static GList *free_list;
636///
637/// gpointer
638/// allocate_memory (gsize size)
639/// {
640///   gpointer result = g_malloc (size);
641///   free_list = g_list_prepend (free_list, result);
642///   return result;
643/// }
644///
645/// void
646/// free_allocated_memory (void)
647/// {
648///   GList *l;
649///   for (l = free_list; l; l = l->next);
650///     g_free (l->data);
651///   g_list_free (free_list);
652///   free_list = NULL;
653///  }
654///
655/// [...]
656///
657/// while (TRUE);
658///  {
659///    g_main_context_iteration (NULL, TRUE);
660///    free_allocated_memory();
661///   }
662/// ```
663///
664/// This works from an application, however, if you want to do the same
665/// thing from a library, it gets more difficult, since you no longer
666/// control the main loop. You might think you can simply use an idle
667/// function to make the call to free_allocated_memory(), but that
668/// doesn't work, since the idle function could be called from a
669/// recursive callback. This can be fixed by using [`main_depth()`][crate::main_depth()]
670///
671///
672///
673/// **⚠️ The following code is in C ⚠️**
674///
675/// ```C
676/// gpointer
677/// allocate_memory (gsize size)
678/// {
679///   FreeListBlock *block = g_new (FreeListBlock, 1);
680///   block->mem = g_malloc (size);
681///   block->depth = g_main_depth ();
682///   free_list = g_list_prepend (free_list, block);
683///   return block->mem;
684/// }
685///
686/// void
687/// free_allocated_memory (void)
688/// {
689///   GList *l;
690///
691///   int depth = g_main_depth ();
692///   for (l = free_list; l; );
693///     {
694///       GList *next = l->next;
695///       FreeListBlock *block = l->data;
696///       if (block->depth > depth)
697///         {
698///           g_free (block->mem);
699///           g_free (block);
700///           free_list = g_list_delete_link (free_list, l);
701///         }
702///
703///       l = next;
704///     }
705///   }
706/// ```
707///
708/// There is a temptation to use [`main_depth()`][crate::main_depth()] to solve
709/// problems with reentrancy. For instance, while waiting for data
710/// to be received from the network in response to a menu item,
711/// the menu item might be selected again. It might seem that
712/// one could make the menu item's callback return immediately
713/// and do nothing if [`main_depth()`][crate::main_depth()] returns a value greater than 1.
714/// However, this should be avoided since the user then sees selecting
715/// the menu item do nothing. Furthermore, you'll find yourself adding
716/// these checks all over your code, since there are doubtless many,
717/// many things that the user could do. Instead, you can use the
718/// following techniques:
719///
720/// 1. Use gtk_widget_set_sensitive() or modal dialogs to prevent
721///    the user from interacting with elements while the main
722///    loop is recursing.
723///
724/// 2. Avoid main loop recursion in situations where you can't handle
725///    arbitrary  callbacks. Instead, structure your code so that you
726///    simply return to the main loop and then get called again when
727///    there is more work to do.
728///
729/// # Returns
730///
731/// The main loop recursion level in the current thread
732#[doc(alias = "g_main_depth")]
733pub fn main_depth() -> i32 {
734    unsafe { ffi::g_main_depth() }
735}
736
737/// Escapes text so that the markup parser will parse it verbatim.
738/// Less than, greater than, ampersand, etc. are replaced with the
739/// corresponding entities. This function would typically be used
740/// when writing out a file to be parsed with the markup parser.
741///
742/// Note that this function doesn't protect whitespace and line endings
743/// from being processed according to the XML rules for normalization
744/// of line endings and attribute values.
745///
746/// Note also that this function will produce character references in
747/// the range of &#x1; ... &#x1f; for all control sequences
748/// except for tabstop, newline and carriage return.  The character
749/// references in this range are not valid XML 1.0, but they are
750/// valid XML 1.1 and will be accepted by the GMarkup parser.
751/// ## `text`
752/// some valid UTF-8 text
753/// ## `length`
754/// length of @text in bytes, or -1 if the text is nul-terminated
755///
756/// # Returns
757///
758/// a newly allocated string with the escaped text
759#[doc(alias = "g_markup_escape_text")]
760pub fn markup_escape_text(text: &str) -> crate::GString {
761    let length = text.len() as _;
762    unsafe { from_glib_full(ffi::g_markup_escape_text(text.to_glib_none().0, length)) }
763}
764
765/// Create a directory if it doesn't already exist. Create intermediate
766/// parent directories as needed, too.
767/// ## `pathname`
768/// a pathname in the GLib file name encoding
769/// ## `mode`
770/// permissions to use for newly created directories
771///
772/// # Returns
773///
774/// 0 if the directory already exists, or was successfully
775/// created. Returns -1 if an error occurred, with errno set.
776#[doc(alias = "g_mkdir_with_parents")]
777pub fn mkdir_with_parents(pathname: impl AsRef<std::path::Path>, mode: i32) -> i32 {
778    unsafe { ffi::g_mkdir_with_parents(pathname.as_ref().to_glib_none().0, mode) }
779}
780
781/// Prompts the user with
782/// `[E]xit, [H]alt, show [S]tack trace or [P]roceed`.
783/// This function is intended to be used for debugging use only.
784/// The following example shows how it can be used together with
785/// the g_log() functions.
786///
787///
788///
789/// **⚠️ The following code is in C ⚠️**
790///
791/// ```C
792/// #include <glib.h>
793///
794/// static void
795/// log_handler (const gchar   *log_domain,
796///              GLogLevelFlags log_level,
797///              const gchar   *message,
798///              gpointer       user_data)
799/// {
800///   g_log_default_handler (log_domain, log_level, message, user_data);
801///
802///   g_on_error_query (MY_PROGRAM_NAME);
803/// }
804///
805/// int
806/// main (int argc, char *argv[])
807/// {
808///   g_log_set_handler (MY_LOG_DOMAIN,
809///                      G_LOG_LEVEL_WARNING |
810///                      G_LOG_LEVEL_ERROR |
811///                      G_LOG_LEVEL_CRITICAL,
812///                      log_handler,
813///                      NULL);
814///   ...
815/// ```
816///
817/// If "[E]xit" is selected, the application terminates with a call
818/// to _exit(0).
819///
820/// If "[S]tack" trace is selected, g_on_error_stack_trace() is called.
821/// This invokes gdb, which attaches to the current process and shows
822/// a stack trace. The prompt is then shown again.
823///
824/// If "[P]roceed" is selected, the function returns.
825///
826/// This function may cause different actions on non-UNIX platforms.
827///
828/// On Windows consider using the `G_DEBUGGER` environment
829/// variable (see [Running GLib Applications](glib-running.html)) and
830/// calling g_on_error_stack_trace() instead.
831/// ## `prg_name`
832/// the program name, needed by gdb for the "[S]tack trace"
833///     option. If @prg_name is [`None`], g_get_prgname() is called to get
834///     the program name (which will work correctly if gdk_init() or
835///     gtk_init() has been called)
836#[doc(alias = "g_on_error_query")]
837pub fn on_error_query(prg_name: &str) {
838    unsafe {
839        ffi::g_on_error_query(prg_name.to_glib_none().0);
840    }
841}
842
843/// Invokes gdb, which attaches to the current process and shows a
844/// stack trace. Called by g_on_error_query() when the "[S]tack trace"
845/// option is selected. You can get the current process's program name
846/// with g_get_prgname(), assuming that you have called gtk_init() or
847/// gdk_init().
848///
849/// This function may cause different actions on non-UNIX platforms.
850///
851/// When running on Windows, this function is *not* called by
852/// g_on_error_query(). If called directly, it will raise an
853/// exception, which will crash the program. If the `G_DEBUGGER` environment
854/// variable is set, a debugger will be invoked to attach and
855/// handle that exception (see [Running GLib Applications](glib-running.html)).
856/// ## `prg_name`
857/// the program name, needed by gdb for the
858///   "[S]tack trace" option, or `NULL` to use a default string
859#[doc(alias = "g_on_error_stack_trace")]
860pub fn on_error_stack_trace(prg_name: Option<&str>) {
861    unsafe {
862        ffi::g_on_error_stack_trace(prg_name.to_glib_none().0);
863    }
864}
865
866/// Gets the last component of the filename.
867///
868/// If @file_name ends with a directory separator it gets the component
869/// before the last slash. If @file_name consists only of directory
870/// separators (and on Windows, possibly a drive letter), a single
871/// separator is returned. If @file_name is empty, it gets ".".
872/// ## `file_name`
873/// the name of the file
874///
875/// # Returns
876///
877/// a newly allocated string
878///   containing the last component of the filename
879#[doc(alias = "g_path_get_basename")]
880#[allow(dead_code)]
881pub(crate) fn path_get_basename(file_name: impl AsRef<std::path::Path>) -> std::path::PathBuf {
882    unsafe {
883        from_glib_full(ffi::g_path_get_basename(
884            file_name.as_ref().to_glib_none().0,
885        ))
886    }
887}
888
889/// Gets the directory components of a file name. For example, the directory
890/// component of `/usr/bin/test` is `/usr/bin`. The directory component of `/`
891/// is `/`.
892///
893/// If the file name has no directory components "." is returned.
894/// The returned string should be freed when no longer needed.
895/// ## `file_name`
896/// the name of the file
897///
898/// # Returns
899///
900/// the directory components of the file
901#[doc(alias = "g_path_get_dirname")]
902#[allow(dead_code)]
903pub(crate) fn path_get_dirname(file_name: impl AsRef<std::path::Path>) -> std::path::PathBuf {
904    unsafe { from_glib_full(ffi::g_path_get_dirname(file_name.as_ref().to_glib_none().0)) }
905}
906
907//#[doc(alias = "g_poll")]
908//pub fn poll(fds: /*Ignored*/&mut PollFD, nfds: u32, timeout: i32) -> i32 {
909//    unsafe { TODO: call ffi:g_poll() }
910//}
911
912/// Returns a random #gdouble equally distributed over the range [0..1).
913///
914/// # Returns
915///
916/// a random number
917#[doc(alias = "g_random_double")]
918pub fn random_double() -> f64 {
919    unsafe { ffi::g_random_double() }
920}
921
922/// Returns a random #gdouble equally distributed over the range
923/// [@begin..@end).
924/// ## `begin`
925/// lower closed bound of the interval
926/// ## `end`
927/// upper open bound of the interval
928///
929/// # Returns
930///
931/// a random number
932#[doc(alias = "g_random_double_range")]
933pub fn random_double_range(begin: f64, end: f64) -> f64 {
934    unsafe { ffi::g_random_double_range(begin, end) }
935}
936
937/// Return a random #guint32 equally distributed over the range
938/// [0..2^32-1].
939///
940/// # Returns
941///
942/// a random number
943#[doc(alias = "g_random_int")]
944pub fn random_int() -> u32 {
945    unsafe { ffi::g_random_int() }
946}
947
948/// Returns a random #gint32 equally distributed over the range
949/// [@begin..@end-1].
950/// ## `begin`
951/// lower closed bound of the interval
952/// ## `end`
953/// upper open bound of the interval
954///
955/// # Returns
956///
957/// a random number
958#[doc(alias = "g_random_int_range")]
959pub fn random_int_range(begin: i32, end: i32) -> i32 {
960    unsafe { ffi::g_random_int_range(begin, end) }
961}
962
963/// Sets the seed for the global random number generator, which is used
964/// by the g_random_* functions, to @seed.
965/// ## `seed`
966/// a value to reinitialize the global random number generator
967#[doc(alias = "g_random_set_seed")]
968pub fn random_set_seed(seed: u32) {
969    unsafe {
970        ffi::g_random_set_seed(seed);
971    }
972}
973
974/// Resets the cache used for g_get_user_special_dir(), so
975/// that the latest on-disk version is used. Call this only
976/// if you just changed the data on disk yourself.
977///
978/// Due to thread safety issues this may cause leaking of strings
979/// that were previously returned from g_get_user_special_dir()
980/// that can't be freed. We ensure to only leak the data for
981/// the directories that actually changed value though.
982#[doc(alias = "g_reload_user_special_dirs_cache")]
983pub fn reload_user_special_dirs_cache() {
984    unsafe {
985        ffi::g_reload_user_special_dirs_cache();
986    }
987}
988
989/// Sets a human-readable name for the application. This name should be
990/// localized if possible, and is intended for display to the user.
991/// Contrast with g_set_prgname(), which sets a non-localized name.
992/// g_set_prgname() will be called automatically by gtk_init(),
993/// but g_set_application_name() will not.
994///
995/// Note that for thread safety reasons, this function can only
996/// be called once.
997///
998/// The application name will be used in contexts such as error messages,
999/// or when displaying an application's name in the task list.
1000/// ## `application_name`
1001/// localized name of the application
1002#[doc(alias = "g_set_application_name")]
1003pub fn set_application_name(application_name: &str) {
1004    unsafe {
1005        ffi::g_set_application_name(application_name.to_glib_none().0);
1006    }
1007}
1008
1009/// Sets an environment variable. On UNIX, both the variable's name and
1010/// value can be arbitrary byte strings, except that the variable's name
1011/// cannot contain '='. On Windows, they should be in UTF-8.
1012///
1013/// Note that on some systems, when variables are overwritten, the memory
1014/// used for the previous variables and its value isn't reclaimed.
1015///
1016/// You should be mindful of the fact that environment variable handling
1017/// in UNIX is not thread-safe, and your program may crash if one thread
1018/// calls g_setenv() while another thread is calling getenv(). (And note
1019/// that many functions, such as gettext(), call getenv() internally.)
1020/// This function is only safe to use at the very start of your program,
1021/// before creating any other threads (or creating objects that create
1022/// worker threads of their own).
1023///
1024/// If you need to set up the environment for a child process, you can
1025/// use g_get_environ() to get an environment array, modify that with
1026/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
1027/// array directly to execvpe(), g_spawn_async(), or the like.
1028/// ## `variable`
1029/// the environment variable to set, must not
1030///     contain '='.
1031/// ## `value`
1032/// the value for to set the variable to.
1033/// ## `overwrite`
1034/// whether to change the variable if it already exists.
1035///
1036/// # Returns
1037///
1038/// [`false`] if the environment variable couldn't be set.
1039#[doc(alias = "g_setenv")]
1040pub fn setenv(
1041    variable: impl AsRef<std::ffi::OsStr>,
1042    value: impl AsRef<std::ffi::OsStr>,
1043    overwrite: bool,
1044) -> Result<(), crate::error::BoolError> {
1045    unsafe {
1046        crate::result_from_gboolean!(
1047            ffi::g_setenv(
1048                variable.as_ref().to_glib_none().0,
1049                value.as_ref().to_glib_none().0,
1050                overwrite.into_glib()
1051            ),
1052            "Failed to set environment variable"
1053        )
1054    }
1055}
1056
1057/// Parses a command line into an argument vector, in much the same way
1058/// the shell would, but without many of the expansions the shell would
1059/// perform (variable expansion, globs, operators, filename expansion,
1060/// etc. are not supported).
1061///
1062/// The results are defined to be the same as those you would get from
1063/// a UNIX98 `/bin/sh`, as long as the input contains none of the
1064/// unsupported shell expansions. If the input does contain such expansions,
1065/// they are passed through literally.
1066///
1067/// Possible errors are those from the `G_SHELL_ERROR` domain.
1068///
1069/// In particular, if @command_line is an empty string (or a string containing
1070/// only whitespace), `G_SHELL_ERROR_EMPTY_STRING` will be returned. It’s
1071/// guaranteed that @argvp will be a non-empty array if this function returns
1072/// successfully.
1073///
1074/// Free the returned vector with g_strfreev().
1075/// ## `command_line`
1076/// command line to parse
1077///
1078/// # Returns
1079///
1080/// [`true`] on success, [`false`] if error set
1081///
1082/// ## `argvp`
1083///
1084///   return location for array of args
1085#[doc(alias = "g_shell_parse_argv")]
1086pub fn shell_parse_argv(
1087    command_line: impl AsRef<std::ffi::OsStr>,
1088) -> Result<Vec<std::ffi::OsString>, crate::Error> {
1089    unsafe {
1090        let mut argcp = std::mem::MaybeUninit::uninit();
1091        let mut argvp = std::ptr::null_mut();
1092        let mut error = std::ptr::null_mut();
1093        let is_ok = ffi::g_shell_parse_argv(
1094            command_line.as_ref().to_glib_none().0,
1095            argcp.as_mut_ptr(),
1096            &mut argvp,
1097            &mut error,
1098        );
1099        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
1100        if error.is_null() {
1101            Ok(FromGlibContainer::from_glib_full_num(
1102                argvp,
1103                argcp.assume_init() as _,
1104            ))
1105        } else {
1106            Err(from_glib_full(error))
1107        }
1108    }
1109}
1110
1111/// Quotes a string so that the shell (/bin/sh) will interpret the
1112/// quoted string to mean @unquoted_string.
1113///
1114/// If you pass a filename to the shell, for example, you should first
1115/// quote it with this function.
1116///
1117/// The return value must be freed with g_free().
1118///
1119/// The quoting style used is undefined (single or double quotes may be
1120/// used).
1121/// ## `unquoted_string`
1122/// a literal string
1123///
1124/// # Returns
1125///
1126/// quoted string
1127#[doc(alias = "g_shell_quote")]
1128pub fn shell_quote(unquoted_string: impl AsRef<std::ffi::OsStr>) -> std::ffi::OsString {
1129    unsafe {
1130        from_glib_full(ffi::g_shell_quote(
1131            unquoted_string.as_ref().to_glib_none().0,
1132        ))
1133    }
1134}
1135
1136/// Unquotes a string as the shell (/bin/sh) would.
1137///
1138/// This function only handles quotes; if a string contains file globs,
1139/// arithmetic operators, variables, backticks, redirections, or other
1140/// special-to-the-shell features, the result will be different from the
1141/// result a real shell would produce (the variables, backticks, etc.
1142/// will be passed through literally instead of being expanded).
1143///
1144/// This function is guaranteed to succeed if applied to the result of
1145/// g_shell_quote(). If it fails, it returns [`None`] and sets the
1146/// error.
1147///
1148/// The @quoted_string need not actually contain quoted or escaped text;
1149/// g_shell_unquote() simply goes through the string and unquotes/unescapes
1150/// anything that the shell would. Both single and double quotes are
1151/// handled, as are escapes including escaped newlines.
1152///
1153/// The return value must be freed with g_free().
1154///
1155/// Possible errors are in the `G_SHELL_ERROR` domain.
1156///
1157/// Shell quoting rules are a bit strange. Single quotes preserve the
1158/// literal string exactly. escape sequences are not allowed; not even
1159/// `\'` - if you want a `'` in the quoted text, you have to do something
1160/// like `'foo'\''bar'`. Double quotes allow `$`, **⚠️ The following code is in , `"`, `\`, and ⚠️**
1161///
1162/// ```, `"`, `\`, and
1163/// newline to be escaped with backslash. Otherwise double quotes
1164/// preserve things literally.
1165/// ## `quoted_string`
1166/// shell-quoted string
1167///
1168/// # Returns
1169///
1170/// an unquoted string
1171#[doc(alias = "g_shell_unquote")]
1172pub fn shell_unquote(
1173    quoted_string: impl AsRef<std::ffi::OsStr>,
1174) -> Result<std::ffi::OsString, crate::Error> {
1175    unsafe {
1176        let mut error = std::ptr::null_mut();
1177        let ret = ffi::g_shell_unquote(quoted_string.as_ref().to_glib_none().0, &mut error);
1178        if error.is_null() {
1179            Ok(from_glib_full(ret))
1180        } else {
1181            Err(from_glib_full(error))
1182        }
1183    }
1184}
1185
1186//#[cfg(feature = "v2_82")]
1187//#[cfg_attr(docsrs, doc(cfg(feature = "v2_82")))]
1188//#[doc(alias = "g_sort_array")]
1189//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>) {
1190//    unsafe { TODO: call ffi:g_sort_array() }
1191//}
1192
1193/// Gets the smallest prime number from a built-in array of primes which
1194/// is larger than @num. This is used within GLib to calculate the optimum
1195/// size of a #GHashTable.
1196///
1197/// The built-in array of primes ranges from 11 to 13845163 such that
1198/// each prime is approximately 1.5-2 times the previous prime.
1199/// ## `num`
1200/// a #guint
1201///
1202/// # Returns
1203///
1204/// the smallest prime number from a built-in array of primes
1205///     which is larger than @num
1206#[doc(alias = "g_spaced_primes_closest")]
1207pub fn spaced_primes_closest(num: u32) -> u32 {
1208    unsafe { ffi::g_spaced_primes_closest(num) }
1209}
1210
1211/// Executes a child program asynchronously.
1212///
1213/// See g_spawn_async_with_pipes() for a full description; this function
1214/// simply calls the g_spawn_async_with_pipes() without any pipes.
1215///
1216/// You should call g_spawn_close_pid() on the returned child process
1217/// reference when you don't need it any more.
1218///
1219/// If you are writing a GTK application, and the program you are spawning is a
1220/// graphical application too, then to ensure that the spawned program opens its
1221/// windows on the right screen, you may want to use #GdkAppLaunchContext,
1222/// #GAppLaunchContext, or set the `DISPLAY` environment variable.
1223///
1224/// Note that the returned @child_pid on Windows is a handle to the child
1225/// process and not its identifier. Process handles and process identifiers
1226/// are different concepts on Windows.
1227/// ## `working_directory`
1228/// child's current working
1229///     directory, or [`None`] to inherit parent's
1230/// ## `argv`
1231///
1232///     child's argument vector
1233/// ## `envp`
1234///
1235///     child's environment, or [`None`] to inherit parent's
1236/// ## `flags`
1237/// flags from #GSpawnFlags
1238/// ## `child_setup`
1239/// function to run
1240///     in the child just before `exec()`
1241///
1242/// # Returns
1243///
1244/// [`true`] on success, [`false`] if error is set
1245///
1246/// ## `child_pid`
1247/// return location for child process reference, or [`None`]
1248#[doc(alias = "g_spawn_async")]
1249pub fn spawn_async(
1250    working_directory: Option<impl AsRef<std::path::Path>>,
1251    argv: &[&std::path::Path],
1252    envp: &[&std::path::Path],
1253    flags: SpawnFlags,
1254    child_setup: Option<Box_<dyn FnOnce() + 'static>>,
1255) -> Result<Pid, crate::Error> {
1256    let child_setup_data: Box_<Option<Box_<dyn FnOnce() + 'static>>> = Box_::new(child_setup);
1257    unsafe extern "C" fn child_setup_func(data: ffi::gpointer) {
1258        let callback = Box_::from_raw(data as *mut Option<Box_<dyn FnOnce() + 'static>>);
1259        let callback = (*callback).expect("cannot get closure...");
1260        callback()
1261    }
1262    let child_setup = if child_setup_data.is_some() {
1263        Some(child_setup_func as _)
1264    } else {
1265        None
1266    };
1267    let super_callback0: Box_<Option<Box_<dyn FnOnce() + 'static>>> = child_setup_data;
1268    unsafe {
1269        let mut child_pid = std::mem::MaybeUninit::uninit();
1270        let mut error = std::ptr::null_mut();
1271        let is_ok = ffi::g_spawn_async(
1272            working_directory
1273                .as_ref()
1274                .map(|p| p.as_ref())
1275                .to_glib_none()
1276                .0,
1277            argv.to_glib_none().0,
1278            envp.to_glib_none().0,
1279            flags.into_glib(),
1280            child_setup,
1281            Box_::into_raw(super_callback0) as *mut _,
1282            child_pid.as_mut_ptr(),
1283            &mut error,
1284        );
1285        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
1286        if error.is_null() {
1287            Ok(from_glib(child_pid.assume_init()))
1288        } else {
1289            Err(from_glib_full(error))
1290        }
1291    }
1292}
1293
1294//#[cfg(feature = "v2_68")]
1295//#[cfg_attr(docsrs, doc(cfg(feature = "v2_68")))]
1296//#[doc(alias = "g_spawn_async_with_pipes_and_fds")]
1297//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> {
1298//    unsafe { TODO: call ffi:g_spawn_async_with_pipes_and_fds() }
1299//}
1300
1301/// An old name for g_spawn_check_wait_status(), deprecated because its
1302/// name is misleading.
1303///
1304/// Despite the name of the function, @wait_status must be the wait status
1305/// as returned by g_spawn_sync(), g_subprocess_get_status(), `waitpid()`,
1306/// etc. On Unix platforms, it is incorrect for it to be the exit status
1307/// as passed to `exit()` or returned by g_subprocess_get_exit_status() or
1308/// `WEXITSTATUS()`.
1309///
1310/// # Deprecated since 2.70
1311///
1312/// Use g_spawn_check_wait_status() instead, and check whether your code is conflating wait and exit statuses.
1313/// ## `wait_status`
1314/// A status as returned from g_spawn_sync()
1315///
1316/// # Returns
1317///
1318/// [`true`] if child exited successfully, [`false`] otherwise (and
1319///     @error will be set)
1320#[cfg_attr(feature = "v2_70", deprecated = "Since 2.70")]
1321#[allow(deprecated)]
1322#[doc(alias = "g_spawn_check_exit_status")]
1323pub fn spawn_check_exit_status(wait_status: i32) -> Result<(), crate::Error> {
1324    unsafe {
1325        let mut error = std::ptr::null_mut();
1326        let is_ok = ffi::g_spawn_check_exit_status(wait_status, &mut error);
1327        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
1328        if error.is_null() {
1329            Ok(())
1330        } else {
1331            Err(from_glib_full(error))
1332        }
1333    }
1334}
1335
1336/// Set @error if @wait_status indicates the child exited abnormally
1337/// (e.g. with a nonzero exit code, or via a fatal signal).
1338///
1339/// The g_spawn_sync() and g_child_watch_add() family of APIs return the
1340/// status of subprocesses encoded in a platform-specific way.
1341/// On Unix, this is guaranteed to be in the same format waitpid() returns,
1342/// and on Windows it is guaranteed to be the result of GetExitCodeProcess().
1343///
1344/// Prior to the introduction of this function in GLib 2.34, interpreting
1345/// @wait_status required use of platform-specific APIs, which is problematic
1346/// for software using GLib as a cross-platform layer.
1347///
1348/// Additionally, many programs simply want to determine whether or not
1349/// the child exited successfully, and either propagate a #GError or
1350/// print a message to standard error. In that common case, this function
1351/// can be used. Note that the error message in @error will contain
1352/// human-readable information about the wait status.
1353///
1354/// The @domain and @code of @error have special semantics in the case
1355/// where the process has an "exit code", as opposed to being killed by
1356/// a signal. On Unix, this happens if WIFEXITED() would be true of
1357/// @wait_status. On Windows, it is always the case.
1358///
1359/// The special semantics are that the actual exit code will be the
1360/// code set in @error, and the domain will be `G_SPAWN_EXIT_ERROR`.
1361/// This allows you to differentiate between different exit codes.
1362///
1363/// If the process was terminated by some means other than an exit
1364/// status (for example if it was killed by a signal), the domain will be
1365/// `G_SPAWN_ERROR` and the code will be `G_SPAWN_ERROR_FAILED`.
1366///
1367/// This function just offers convenience; you can of course also check
1368/// the available platform via a macro such as `G_OS_UNIX`, and use
1369/// WIFEXITED() and WEXITSTATUS() on @wait_status directly. Do not attempt
1370/// to scan or parse the error message string; it may be translated and/or
1371/// change in future versions of GLib.
1372///
1373/// Prior to version 2.70, g_spawn_check_exit_status() provides the same
1374/// functionality, although under a misleading name.
1375/// ## `wait_status`
1376/// A platform-specific wait status as returned from g_spawn_sync()
1377///
1378/// # Returns
1379///
1380/// [`true`] if child exited successfully, [`false`] otherwise (and
1381///   @error will be set)
1382#[cfg(feature = "v2_70")]
1383#[cfg_attr(docsrs, doc(cfg(feature = "v2_70")))]
1384#[doc(alias = "g_spawn_check_wait_status")]
1385pub fn spawn_check_wait_status(wait_status: i32) -> Result<(), crate::Error> {
1386    unsafe {
1387        let mut error = std::ptr::null_mut();
1388        let is_ok = ffi::g_spawn_check_wait_status(wait_status, &mut error);
1389        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
1390        if error.is_null() {
1391            Ok(())
1392        } else {
1393            Err(from_glib_full(error))
1394        }
1395    }
1396}
1397
1398/// A simple version of g_spawn_async() that parses a command line with
1399/// g_shell_parse_argv() and passes it to g_spawn_async().
1400///
1401/// Runs a command line in the background. Unlike g_spawn_async(), the
1402/// [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] flag is enabled, other flags are not. Note
1403/// that [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] can have security implications, so
1404/// consider using g_spawn_async() directly if appropriate. Possible
1405/// errors are those from g_shell_parse_argv() and g_spawn_async().
1406///
1407/// The same concerns on Windows apply as for g_spawn_command_line_sync().
1408/// ## `command_line`
1409/// a command line
1410///
1411/// # Returns
1412///
1413/// [`true`] on success, [`false`] if error is set
1414// rustdoc-stripper-ignore-next-stop
1415/// A simple version of g_spawn_async() that parses a command line with
1416/// g_shell_parse_argv() and passes it to g_spawn_async().
1417///
1418/// Runs a command line in the background. Unlike g_spawn_async(), the
1419/// [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] flag is enabled, other flags are not. Note
1420/// that [`SpawnFlags::SEARCH_PATH`][crate::SpawnFlags::SEARCH_PATH] can have security implications, so
1421/// consider using g_spawn_async() directly if appropriate. Possible
1422/// errors are those from g_shell_parse_argv() and g_spawn_async().
1423///
1424/// The same concerns on Windows apply as for g_spawn_command_line_sync().
1425/// ## `command_line`
1426/// a command line
1427///
1428/// # Returns
1429///
1430/// [`true`] on success, [`false`] if error is set
1431#[cfg(unix)]
1432#[cfg_attr(docsrs, doc(cfg(unix)))]
1433#[doc(alias = "g_spawn_command_line_async")]
1434pub fn spawn_command_line_async(
1435    command_line: impl AsRef<std::ffi::OsStr>,
1436) -> Result<(), crate::Error> {
1437    unsafe {
1438        let mut error = std::ptr::null_mut();
1439        let is_ok =
1440            ffi::g_spawn_command_line_async(command_line.as_ref().to_glib_none().0, &mut error);
1441        debug_assert_eq!(is_ok == crate::ffi::GFALSE, !error.is_null());
1442        if error.is_null() {
1443            Ok(())
1444        } else {
1445            Err(from_glib_full(error))
1446        }
1447    }
1448}
1449
1450//#[doc(alias = "g_spawn_command_line_sync")]
1451//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> {
1452//    unsafe { TODO: call ffi:g_spawn_command_line_sync() }
1453//}
1454
1455//#[doc(alias = "g_spawn_sync")]
1456//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> {
1457//    unsafe { TODO: call ffi:g_spawn_sync() }
1458//}
1459
1460//#[doc(alias = "g_stat")]
1461//pub fn stat(filename: impl AsRef<std::path::Path>, buf: /*Ignored*/&mut StatBuf) -> i32 {
1462//    unsafe { TODO: call ffi:g_stat() }
1463//}
1464
1465//#[cfg(unix)]
1466//#[cfg_attr(docsrs, doc(cfg(unix)))]
1467//#[cfg(feature = "v2_64")]
1468//#[cfg_attr(docsrs, doc(cfg(feature = "v2_64")))]
1469//#[doc(alias = "g_unix_get_passwd_entry")]
1470//pub fn unix_get_passwd_entry(user_name: &str) -> Result</*Unimplemented*/Option<Basic: Pointer>, crate::Error> {
1471//    unsafe { TODO: call ffi:g_unix_get_passwd_entry() }
1472//}
1473
1474/// A wrapper for the POSIX unlink() function. The unlink() function
1475/// deletes a name from the filesystem. If this was the last link to the
1476/// file and no processes have it opened, the diskspace occupied by the
1477/// file is freed.
1478///
1479/// See your C library manual for more details about unlink(). Note
1480/// that on Windows, it is in general not possible to delete files that
1481/// are open to some process, or mapped into memory.
1482/// ## `filename`
1483/// a pathname in the GLib file name encoding
1484///     (UTF-8 on Windows)
1485///
1486/// # Returns
1487///
1488/// 0 if the name was successfully deleted, -1 if an error
1489///    occurred
1490// rustdoc-stripper-ignore-next-stop
1491/// A wrapper for the POSIX unlink() function. The unlink() function
1492/// deletes a name from the filesystem. If this was the last link to the
1493/// file and no processes have it opened, the diskspace occupied by the
1494/// file is freed.
1495///
1496/// See your C library manual for more details about unlink(). Note
1497/// that on Windows, it is in general not possible to delete files that
1498/// are open to some process, or mapped into memory.
1499/// ## `filename`
1500/// a pathname in the GLib file name encoding
1501///     (UTF-8 on Windows)
1502///
1503/// # Returns
1504///
1505/// 0 if the name was successfully deleted, -1 if an error
1506///    occurred
1507#[doc(alias = "g_unlink")]
1508pub fn unlink(filename: impl AsRef<std::path::Path>) -> i32 {
1509    unsafe { ffi::g_unlink(filename.as_ref().to_glib_none().0) }
1510}
1511
1512/// Removes an environment variable from the environment.
1513///
1514/// Note that on some systems, when variables are overwritten, the
1515/// memory used for the previous variables and its value isn't reclaimed.
1516///
1517/// You should be mindful of the fact that environment variable handling
1518/// in UNIX is not thread-safe, and your program may crash if one thread
1519/// calls g_unsetenv() while another thread is calling getenv(). (And note
1520/// that many functions, such as gettext(), call getenv() internally.) This
1521/// function is only safe to use at the very start of your program, before
1522/// creating any other threads (or creating objects that create worker
1523/// threads of their own).
1524///
1525/// If you need to set up the environment for a child process, you can
1526/// use g_get_environ() to get an environment array, modify that with
1527/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
1528/// array directly to execvpe(), g_spawn_async(), or the like.
1529/// ## `variable`
1530/// the environment variable to remove, must
1531///     not contain '='
1532// rustdoc-stripper-ignore-next-stop
1533/// Removes an environment variable from the environment.
1534///
1535/// Note that on some systems, when variables are overwritten, the
1536/// memory used for the previous variables and its value isn't reclaimed.
1537///
1538/// You should be mindful of the fact that environment variable handling
1539/// in UNIX is not thread-safe, and your program may crash if one thread
1540/// calls g_unsetenv() while another thread is calling getenv(). (And note
1541/// that many functions, such as gettext(), call getenv() internally.) This
1542/// function is only safe to use at the very start of your program, before
1543/// creating any other threads (or creating objects that create worker
1544/// threads of their own).
1545///
1546/// If you need to set up the environment for a child process, you can
1547/// use g_get_environ() to get an environment array, modify that with
1548/// g_environ_setenv() and g_environ_unsetenv(), and then pass that
1549/// array directly to execvpe(), g_spawn_async(), or the like.
1550/// ## `variable`
1551/// the environment variable to remove, must
1552///     not contain '='
1553#[doc(alias = "g_unsetenv")]
1554pub fn unsetenv(variable: impl AsRef<std::ffi::OsStr>) {
1555    unsafe {
1556        ffi::g_unsetenv(variable.as_ref().to_glib_none().0);
1557    }
1558}
1559
1560/// Pauses the current thread for the given number of microseconds.
1561///
1562/// There are 1 million microseconds per second (represented by the
1563/// `G_USEC_PER_SEC` macro). g_usleep() may have limited precision,
1564/// depending on hardware and operating system; don't rely on the exact
1565/// length of the sleep.
1566/// ## `microseconds`
1567/// number of microseconds to pause
1568// rustdoc-stripper-ignore-next-stop
1569/// Pauses the current thread for the given number of microseconds.
1570///
1571/// There are 1 million microseconds per second (represented by the
1572/// `G_USEC_PER_SEC` macro). g_usleep() may have limited precision,
1573/// depending on hardware and operating system; don't rely on the exact
1574/// length of the sleep.
1575/// ## `microseconds`
1576/// number of microseconds to pause
1577#[doc(alias = "g_usleep")]
1578pub fn usleep(microseconds: libc::c_ulong) {
1579    unsafe {
1580        ffi::g_usleep(microseconds);
1581    }
1582}
1583
1584/// Parses the string @str and verify if it is a UUID.
1585///
1586/// The function accepts the following syntax:
1587///
1588/// - simple forms (e.g. `f81d4fae-7dec-11d0-a765-00a0c91e6bf6`)
1589///
1590/// Note that hyphens are required within the UUID string itself,
1591/// as per the aforementioned RFC.
1592/// ## `str`
1593/// a string representing a UUID
1594///
1595/// # Returns
1596///
1597/// [`true`] if @str is a valid UUID, [`false`] otherwise.
1598// rustdoc-stripper-ignore-next-stop
1599/// Parses the string @str and verify if it is a UUID.
1600///
1601/// The function accepts the following syntax:
1602///
1603/// - simple forms (e.g. `f81d4fae-7dec-11d0-a765-00a0c91e6bf6`)
1604///
1605/// Note that hyphens are required within the UUID string itself,
1606/// as per the aforementioned RFC.
1607/// ## `str`
1608/// a string representing a UUID
1609///
1610/// # Returns
1611///
1612/// [`true`] if @str is a valid UUID, [`false`] otherwise.
1613#[doc(alias = "g_uuid_string_is_valid")]
1614pub fn uuid_string_is_valid(str: &str) -> bool {
1615    unsafe { from_glib(ffi::g_uuid_string_is_valid(str.to_glib_none().0)) }
1616}
1617
1618/// Generates a random UUID (RFC 4122 version 4) as a string. It has the same
1619/// randomness guarantees as #GRand, so must not be used for cryptographic
1620/// purposes such as key generation, nonces, salts or one-time pads.
1621///
1622/// # Returns
1623///
1624/// A string that should be freed with g_free().
1625// rustdoc-stripper-ignore-next-stop
1626/// Generates a random UUID (RFC 4122 version 4) as a string. It has the same
1627/// randomness guarantees as #GRand, so must not be used for cryptographic
1628/// purposes such as key generation, nonces, salts or one-time pads.
1629///
1630/// # Returns
1631///
1632/// A string that should be freed with g_free().
1633#[doc(alias = "g_uuid_string_random")]
1634pub fn uuid_string_random() -> crate::GString {
1635    unsafe { from_glib_full(ffi::g_uuid_string_random()) }
1636}