gio/auto/subprocess.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
5use crate::{AsyncResult, Cancellable, Initable, InputStream, OutputStream, ffi};
6use glib::{prelude::*, translate::*};
7use std::{boxed::Box as Box_, pin::Pin};
8
9glib::wrapper! {
10 /// `GSubprocess` allows the creation of and interaction with child
11 /// processes.
12 ///
13 /// Processes can be communicated with using standard GIO-style APIs (ie:
14 /// [`InputStream`][crate::InputStream], [`OutputStream`][crate::OutputStream]). There are GIO-style APIs
15 /// to wait for process termination (ie: cancellable and with an asynchronous
16 /// variant).
17 ///
18 /// There is an API to force a process to terminate, as well as a
19 /// race-free API for sending UNIX signals to a subprocess.
20 ///
21 /// One major advantage that GIO brings over the core GLib library is
22 /// comprehensive API for asynchronous I/O, such
23 /// [`OutputStreamExt::splice_async()`][crate::prelude::OutputStreamExt::splice_async()]. This makes `GSubprocess`
24 /// significantly more powerful and flexible than equivalent APIs in
25 /// some other languages such as the `subprocess.py`
26 /// included with Python. For example, using `GSubprocess` one could
27 /// create two child processes, reading standard output from the first,
28 /// processing it, and writing to the input stream of the second, all
29 /// without blocking the main loop.
30 ///
31 /// A powerful [`communicate()`][Self::communicate()] API is provided similar to the
32 /// `communicate()` method of `subprocess.py`. This enables very easy
33 /// interaction with a subprocess that has been opened with pipes.
34 ///
35 /// `GSubprocess` defaults to tight control over the file descriptors open
36 /// in the child process, avoiding dangling-FD issues that are caused by
37 /// a simple `fork()`/`exec()`. The only open file descriptors in the
38 /// spawned process are ones that were explicitly specified by the
39 /// `GSubprocess` API (unless `G_SUBPROCESS_FLAGS_INHERIT_FDS` was
40 /// specified).
41 ///
42 /// `GSubprocess` will quickly reap all child processes as they exit,
43 /// avoiding ‘zombie processes’ remaining around for long periods of
44 /// time. [`wait()`][Self::wait()] can be used to wait for this to happen,
45 /// but it will happen even without the call being explicitly made.
46 ///
47 /// As a matter of principle, `GSubprocess` has no API that accepts
48 /// shell-style space-separated strings. It will, however, match the
49 /// typical shell behaviour of searching the `PATH` for executables that do
50 /// not contain a directory separator in their name. By default, the `PATH`
51 /// of the current process is used. You can specify
52 /// `G_SUBPROCESS_FLAGS_SEARCH_PATH_FROM_ENVP` to use the `PATH` of the
53 /// launcher environment instead.
54 ///
55 /// `GSubprocess` attempts to have a very simple API for most uses (ie:
56 /// spawning a subprocess with arguments and support for most typical
57 /// kinds of input and output redirection). See `Gio::Subprocess::new()`. The
58 /// [`SubprocessLauncher`][crate::SubprocessLauncher] API is provided for more complicated cases
59 /// (advanced types of redirection, environment variable manipulation,
60 /// change of working directory, child setup functions, etc).
61 ///
62 /// A typical use of `GSubprocess` will involve calling
63 /// `Gio::Subprocess::new()`, followed by [`wait_async()`][Self::wait_async()] or
64 /// [`wait()`][Self::wait()]. After the process exits, the status can be
65 /// checked using functions such as [`has_exited()`][Self::has_exited()] (which
66 /// are similar to the familiar `WIFEXITED`-style POSIX macros).
67 ///
68 /// Note that as of GLib 2.82, creating a `GSubprocess` causes the signal
69 /// `SIGPIPE` to be ignored for the remainder of the program. If you are writing
70 /// a command-line utility that uses `GSubprocess`, you may need to take into
71 /// account the fact that your program will not automatically be killed
72 /// if it tries to write to `stdout` after it has been closed.
73 ///
74 /// ## Properties
75 ///
76 ///
77 /// #### `argv`
78 /// Argument vector.
79 ///
80 /// Writable | Construct Only
81 ///
82 ///
83 /// #### `flags`
84 /// Subprocess flags.
85 ///
86 /// Writable | Construct Only
87 ///
88 /// # Implements
89 ///
90 /// [`trait@glib::ObjectExt`], [`InitableExt`][trait@crate::prelude::InitableExt]
91 #[doc(alias = "GSubprocess")]
92 pub struct Subprocess(Object<ffi::GSubprocess>) @implements Initable;
93
94 match fn {
95 type_ => || ffi::g_subprocess_get_type(),
96 }
97}
98
99impl Subprocess {
100 //#[doc(alias = "g_subprocess_new")]
101 //pub fn new(flags: SubprocessFlags, error: Option<&mut glib::Error>, argv0: &str, : /*Unknown conversion*//*Unimplemented*/Basic: VarArgs) -> Subprocess {
102 // unsafe { TODO: call ffi:g_subprocess_new() }
103 //}
104
105 /// Communicate with the subprocess until it terminates, and all input
106 /// and output has been completed.
107 ///
108 /// If @stdin_buf is given, the subprocess must have been created with
109 /// [`SubprocessFlags::STDIN_PIPE`][crate::SubprocessFlags::STDIN_PIPE]. The given data is fed to the
110 /// stdin of the subprocess and the pipe is closed (ie: EOF).
111 ///
112 /// At the same time (as not to cause blocking when dealing with large
113 /// amounts of data), if [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE] or
114 /// [`SubprocessFlags::STDERR_PIPE`][crate::SubprocessFlags::STDERR_PIPE] were used, reads from those
115 /// streams. The data that was read is returned in @stdout and/or
116 /// the @stderr.
117 ///
118 /// If the subprocess was created with [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE],
119 /// @stdout_buf will contain the data read from stdout. Otherwise, for
120 /// subprocesses not created with [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE],
121 /// @stdout_buf will be set to [`None`]. Similar provisions apply to
122 /// @stderr_buf and [`SubprocessFlags::STDERR_PIPE`][crate::SubprocessFlags::STDERR_PIPE].
123 ///
124 /// As usual, any output variable may be given as [`None`] to ignore it.
125 ///
126 /// If you desire the stdout and stderr data to be interleaved, create
127 /// the subprocess with [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE] and
128 /// [`SubprocessFlags::STDERR_MERGE`][crate::SubprocessFlags::STDERR_MERGE]. The merged result will be returned
129 /// in @stdout_buf and @stderr_buf will be set to [`None`].
130 ///
131 /// In case of any error (including cancellation), [`false`] will be
132 /// returned with @error set. Some or all of the stdin data may have
133 /// been written. Any stdout or stderr data that has been read will be
134 /// discarded. None of the out variables (aside from @error) will have
135 /// been set to anything in particular and should not be inspected.
136 ///
137 /// In the case that [`true`] is returned, the subprocess has exited and the
138 /// exit status inspection APIs (eg: g_subprocess_get_if_exited(),
139 /// g_subprocess_get_exit_status()) may be used.
140 ///
141 /// You should not attempt to use any of the subprocess pipes after
142 /// starting this function, since they may be left in strange states,
143 /// even if the operation was cancelled. You should especially not
144 /// attempt to interact with the pipes while the operation is in progress
145 /// (either from another thread or if using the asynchronous version).
146 /// ## `stdin_buf`
147 /// data to send to the stdin of the subprocess, or [`None`]
148 /// ## `cancellable`
149 /// a #GCancellable
150 ///
151 /// # Returns
152 ///
153 /// [`true`] if successful
154 ///
155 /// ## `stdout_buf`
156 /// data read from the subprocess stdout
157 ///
158 /// ## `stderr_buf`
159 /// data read from the subprocess stderr
160 #[doc(alias = "g_subprocess_communicate")]
161 pub fn communicate(
162 &self,
163 stdin_buf: Option<&glib::Bytes>,
164 cancellable: Option<&impl IsA<Cancellable>>,
165 ) -> Result<(Option<glib::Bytes>, Option<glib::Bytes>), glib::Error> {
166 unsafe {
167 let mut stdout_buf = std::ptr::null_mut();
168 let mut stderr_buf = std::ptr::null_mut();
169 let mut error = std::ptr::null_mut();
170 let is_ok = ffi::g_subprocess_communicate(
171 self.to_glib_none().0,
172 stdin_buf.to_glib_none().0,
173 cancellable.map(|p| p.as_ref()).to_glib_none().0,
174 &mut stdout_buf,
175 &mut stderr_buf,
176 &mut error,
177 );
178 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
179 if error.is_null() {
180 Ok((from_glib_full(stdout_buf), from_glib_full(stderr_buf)))
181 } else {
182 Err(from_glib_full(error))
183 }
184 }
185 }
186
187 /// Asynchronous version of g_subprocess_communicate(). Complete
188 /// invocation with g_subprocess_communicate_finish().
189 /// ## `stdin_buf`
190 /// Input data, or [`None`]
191 /// ## `cancellable`
192 /// Cancellable
193 /// ## `callback`
194 /// Callback
195 #[doc(alias = "g_subprocess_communicate_async")]
196 pub fn communicate_async<
197 P: FnOnce(Result<(Option<glib::Bytes>, Option<glib::Bytes>), glib::Error>) + 'static,
198 >(
199 &self,
200 stdin_buf: Option<&glib::Bytes>,
201 cancellable: Option<&impl IsA<Cancellable>>,
202 callback: P,
203 ) {
204 let main_context = glib::MainContext::ref_thread_default();
205 let is_main_context_owner = main_context.is_owner();
206 let has_acquired_main_context = (!is_main_context_owner)
207 .then(|| main_context.acquire().ok())
208 .flatten();
209 assert!(
210 is_main_context_owner || has_acquired_main_context.is_some(),
211 "Async operations only allowed if the thread is owning the MainContext"
212 );
213
214 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
215 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
216 unsafe extern "C" fn communicate_async_trampoline<
217 P: FnOnce(Result<(Option<glib::Bytes>, Option<glib::Bytes>), glib::Error>) + 'static,
218 >(
219 _source_object: *mut glib::gobject_ffi::GObject,
220 res: *mut crate::ffi::GAsyncResult,
221 user_data: glib::ffi::gpointer,
222 ) {
223 unsafe {
224 let mut error = std::ptr::null_mut();
225 let mut stdout_buf = std::ptr::null_mut();
226 let mut stderr_buf = std::ptr::null_mut();
227 ffi::g_subprocess_communicate_finish(
228 _source_object as *mut _,
229 res,
230 &mut stdout_buf,
231 &mut stderr_buf,
232 &mut error,
233 );
234 let result = if error.is_null() {
235 Ok((from_glib_full(stdout_buf), from_glib_full(stderr_buf)))
236 } else {
237 Err(from_glib_full(error))
238 };
239 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
240 Box_::from_raw(user_data as *mut _);
241 let callback: P = callback.into_inner();
242 callback(result);
243 }
244 }
245 let callback = communicate_async_trampoline::<P>;
246 unsafe {
247 ffi::g_subprocess_communicate_async(
248 self.to_glib_none().0,
249 stdin_buf.to_glib_none().0,
250 cancellable.map(|p| p.as_ref()).to_glib_none().0,
251 Some(callback),
252 Box_::into_raw(user_data) as *mut _,
253 );
254 }
255 }
256
257 pub fn communicate_future(
258 &self,
259 stdin_buf: Option<&glib::Bytes>,
260 ) -> Pin<
261 Box_<
262 dyn std::future::Future<
263 Output = Result<(Option<glib::Bytes>, Option<glib::Bytes>), glib::Error>,
264 > + 'static,
265 >,
266 > {
267 let stdin_buf = stdin_buf.map(ToOwned::to_owned);
268 Box_::pin(crate::GioFuture::new(
269 self,
270 move |obj, cancellable, send| {
271 obj.communicate_async(
272 stdin_buf.as_ref().map(::std::borrow::Borrow::borrow),
273 Some(cancellable),
274 move |res| {
275 send.resolve(res);
276 },
277 );
278 },
279 ))
280 }
281
282 /// Like g_subprocess_communicate(), but validates the output of the
283 /// process as UTF-8, and returns it as a regular NUL terminated string.
284 ///
285 /// On error, @stdout_buf and @stderr_buf will be set to undefined values and
286 /// should not be used.
287 /// ## `stdin_buf`
288 /// data to send to the stdin of the subprocess, or [`None`]
289 /// ## `cancellable`
290 /// a #GCancellable
291 ///
292 /// # Returns
293 ///
294 ///
295 /// ## `stdout_buf`
296 /// data read from the subprocess stdout
297 ///
298 /// ## `stderr_buf`
299 /// data read from the subprocess stderr
300 #[doc(alias = "g_subprocess_communicate_utf8")]
301 pub fn communicate_utf8(
302 &self,
303 stdin_buf: Option<&str>,
304 cancellable: Option<&impl IsA<Cancellable>>,
305 ) -> Result<(Option<glib::GString>, Option<glib::GString>), glib::Error> {
306 unsafe {
307 let mut stdout_buf = std::ptr::null_mut();
308 let mut stderr_buf = std::ptr::null_mut();
309 let mut error = std::ptr::null_mut();
310 let is_ok = ffi::g_subprocess_communicate_utf8(
311 self.to_glib_none().0,
312 stdin_buf.to_glib_none().0,
313 cancellable.map(|p| p.as_ref()).to_glib_none().0,
314 &mut stdout_buf,
315 &mut stderr_buf,
316 &mut error,
317 );
318 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
319 if error.is_null() {
320 Ok((from_glib_full(stdout_buf), from_glib_full(stderr_buf)))
321 } else {
322 Err(from_glib_full(error))
323 }
324 }
325 }
326
327 /// Use an operating-system specific method to attempt an immediate,
328 /// forceful termination of the process. There is no mechanism to
329 /// determine whether or not the request itself was successful;
330 /// however, you can use g_subprocess_wait() to monitor the status of
331 /// the process after calling this function.
332 ///
333 /// On Unix, this function sends `SIGKILL`.
334 #[doc(alias = "g_subprocess_force_exit")]
335 pub fn force_exit(&self) {
336 unsafe {
337 ffi::g_subprocess_force_exit(self.to_glib_none().0);
338 }
339 }
340
341 /// Check the exit status of the subprocess, given that it exited
342 /// normally. This is the value passed to the exit() system call or the
343 /// return value from main.
344 ///
345 /// This is equivalent to the system WEXITSTATUS macro.
346 ///
347 /// It is an error to call this function before g_subprocess_wait() and
348 /// unless g_subprocess_get_if_exited() returned [`true`].
349 ///
350 /// # Returns
351 ///
352 /// the exit status
353 #[doc(alias = "g_subprocess_get_exit_status")]
354 #[doc(alias = "get_exit_status")]
355 pub fn exit_status(&self) -> i32 {
356 unsafe { ffi::g_subprocess_get_exit_status(self.to_glib_none().0) }
357 }
358
359 /// On UNIX, returns the process ID as a decimal string.
360 /// On Windows, returns the result of GetProcessId() also as a string.
361 /// If the subprocess has terminated, this will return [`None`].
362 ///
363 /// # Returns
364 ///
365 /// the subprocess identifier, or [`None`] if the subprocess
366 /// has terminated
367 #[doc(alias = "g_subprocess_get_identifier")]
368 #[doc(alias = "get_identifier")]
369 pub fn identifier(&self) -> Option<glib::GString> {
370 unsafe { from_glib_none(ffi::g_subprocess_get_identifier(self.to_glib_none().0)) }
371 }
372
373 /// Check if the given subprocess exited normally (ie: by way of exit()
374 /// or return from main()).
375 ///
376 /// This is equivalent to the system WIFEXITED macro.
377 ///
378 /// It is an error to call this function before g_subprocess_wait() has
379 /// returned.
380 ///
381 /// # Returns
382 ///
383 /// [`true`] if the case of a normal exit
384 #[doc(alias = "g_subprocess_get_if_exited")]
385 #[doc(alias = "get_if_exited")]
386 pub fn has_exited(&self) -> bool {
387 unsafe { from_glib(ffi::g_subprocess_get_if_exited(self.to_glib_none().0)) }
388 }
389
390 /// Check if the given subprocess terminated in response to a signal.
391 ///
392 /// This is equivalent to the system WIFSIGNALED macro.
393 ///
394 /// It is an error to call this function before g_subprocess_wait() has
395 /// returned.
396 ///
397 /// # Returns
398 ///
399 /// [`true`] if the case of termination due to a signal
400 #[doc(alias = "g_subprocess_get_if_signaled")]
401 #[doc(alias = "get_if_signaled")]
402 pub fn has_signaled(&self) -> bool {
403 unsafe { from_glib(ffi::g_subprocess_get_if_signaled(self.to_glib_none().0)) }
404 }
405
406 /// Gets the raw status code of the process, as from waitpid().
407 ///
408 /// This value has no particular meaning, but it can be used with the
409 /// macros defined by the system headers such as WIFEXITED. It can also
410 /// be used with g_spawn_check_wait_status().
411 ///
412 /// It is more likely that you want to use g_subprocess_get_if_exited()
413 /// followed by g_subprocess_get_exit_status().
414 ///
415 /// It is an error to call this function before g_subprocess_wait() has
416 /// returned.
417 ///
418 /// # Returns
419 ///
420 /// the (meaningless) waitpid() exit status from the kernel
421 #[doc(alias = "g_subprocess_get_status")]
422 #[doc(alias = "get_status")]
423 pub fn status(&self) -> i32 {
424 unsafe { ffi::g_subprocess_get_status(self.to_glib_none().0) }
425 }
426
427 /// Gets the #GInputStream from which to read the stderr output of
428 /// @self.
429 ///
430 /// The process must have been created with [`SubprocessFlags::STDERR_PIPE`][crate::SubprocessFlags::STDERR_PIPE],
431 /// otherwise [`None`] will be returned.
432 ///
433 /// # Returns
434 ///
435 /// the stderr pipe
436 #[doc(alias = "g_subprocess_get_stderr_pipe")]
437 #[doc(alias = "get_stderr_pipe")]
438 pub fn stderr_pipe(&self) -> Option<InputStream> {
439 unsafe { from_glib_none(ffi::g_subprocess_get_stderr_pipe(self.to_glib_none().0)) }
440 }
441
442 /// Gets the #GOutputStream that you can write to in order to give data
443 /// to the stdin of @self.
444 ///
445 /// The process must have been created with [`SubprocessFlags::STDIN_PIPE`][crate::SubprocessFlags::STDIN_PIPE] and
446 /// not [`SubprocessFlags::STDIN_INHERIT`][crate::SubprocessFlags::STDIN_INHERIT], otherwise [`None`] will be returned.
447 ///
448 /// # Returns
449 ///
450 /// the stdout pipe
451 #[doc(alias = "g_subprocess_get_stdin_pipe")]
452 #[doc(alias = "get_stdin_pipe")]
453 pub fn stdin_pipe(&self) -> Option<OutputStream> {
454 unsafe { from_glib_none(ffi::g_subprocess_get_stdin_pipe(self.to_glib_none().0)) }
455 }
456
457 /// Gets the #GInputStream from which to read the stdout output of
458 /// @self.
459 ///
460 /// The process must have been created with [`SubprocessFlags::STDOUT_PIPE`][crate::SubprocessFlags::STDOUT_PIPE],
461 /// otherwise [`None`] will be returned.
462 ///
463 /// # Returns
464 ///
465 /// the stdout pipe
466 #[doc(alias = "g_subprocess_get_stdout_pipe")]
467 #[doc(alias = "get_stdout_pipe")]
468 pub fn stdout_pipe(&self) -> Option<InputStream> {
469 unsafe { from_glib_none(ffi::g_subprocess_get_stdout_pipe(self.to_glib_none().0)) }
470 }
471
472 /// Checks if the process was "successful". A process is considered
473 /// successful if it exited cleanly with an exit status of 0, either by
474 /// way of the exit() system call or return from main().
475 ///
476 /// It is an error to call this function before g_subprocess_wait() has
477 /// returned.
478 ///
479 /// # Returns
480 ///
481 /// [`true`] if the process exited cleanly with a exit status of 0
482 #[doc(alias = "g_subprocess_get_successful")]
483 #[doc(alias = "get_successful")]
484 pub fn is_successful(&self) -> bool {
485 unsafe { from_glib(ffi::g_subprocess_get_successful(self.to_glib_none().0)) }
486 }
487
488 /// Get the signal number that caused the subprocess to terminate, given
489 /// that it terminated due to a signal.
490 ///
491 /// This is equivalent to the system WTERMSIG macro.
492 ///
493 /// It is an error to call this function before g_subprocess_wait() and
494 /// unless g_subprocess_get_if_signaled() returned [`true`].
495 ///
496 /// # Returns
497 ///
498 /// the signal causing termination
499 #[doc(alias = "g_subprocess_get_term_sig")]
500 #[doc(alias = "get_term_sig")]
501 pub fn term_sig(&self) -> i32 {
502 unsafe { ffi::g_subprocess_get_term_sig(self.to_glib_none().0) }
503 }
504
505 /// Sends the UNIX signal @signal_num to the subprocess, if it is still
506 /// running.
507 ///
508 /// This API is race-free. If the subprocess has terminated, it will not
509 /// be signalled.
510 ///
511 /// This API is not available on Windows.
512 /// ## `signal_num`
513 /// the signal number to send
514 #[cfg(not(windows))]
515 #[cfg_attr(docsrs, doc(cfg(not(windows))))]
516 #[doc(alias = "g_subprocess_send_signal")]
517 pub fn send_signal(&self, signal_num: i32) {
518 unsafe {
519 ffi::g_subprocess_send_signal(self.to_glib_none().0, signal_num);
520 }
521 }
522
523 /// Synchronously wait for the subprocess to terminate.
524 ///
525 /// After the process terminates you can query its exit status with
526 /// functions such as g_subprocess_get_if_exited() and
527 /// g_subprocess_get_exit_status().
528 ///
529 /// This function does not fail in the case of the subprocess having
530 /// abnormal termination. See g_subprocess_wait_check() for that.
531 ///
532 /// Cancelling @cancellable doesn't kill the subprocess. Call
533 /// g_subprocess_force_exit() if it is desirable.
534 /// ## `cancellable`
535 /// a #GCancellable
536 ///
537 /// # Returns
538 ///
539 /// [`true`] on success, [`false`] if @cancellable was cancelled
540 #[doc(alias = "g_subprocess_wait")]
541 pub fn wait(&self, cancellable: Option<&impl IsA<Cancellable>>) -> Result<(), glib::Error> {
542 unsafe {
543 let mut error = std::ptr::null_mut();
544 let is_ok = ffi::g_subprocess_wait(
545 self.to_glib_none().0,
546 cancellable.map(|p| p.as_ref()).to_glib_none().0,
547 &mut error,
548 );
549 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
550 if error.is_null() {
551 Ok(())
552 } else {
553 Err(from_glib_full(error))
554 }
555 }
556 }
557
558 /// Wait for the subprocess to terminate.
559 ///
560 /// This is the asynchronous version of g_subprocess_wait().
561 /// ## `cancellable`
562 /// a #GCancellable, or [`None`]
563 /// ## `callback`
564 /// a #GAsyncReadyCallback to call when the operation is complete
565 #[doc(alias = "g_subprocess_wait_async")]
566 pub fn wait_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
567 &self,
568 cancellable: Option<&impl IsA<Cancellable>>,
569 callback: P,
570 ) {
571 let main_context = glib::MainContext::ref_thread_default();
572 let is_main_context_owner = main_context.is_owner();
573 let has_acquired_main_context = (!is_main_context_owner)
574 .then(|| main_context.acquire().ok())
575 .flatten();
576 assert!(
577 is_main_context_owner || has_acquired_main_context.is_some(),
578 "Async operations only allowed if the thread is owning the MainContext"
579 );
580
581 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
582 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
583 unsafe extern "C" fn wait_async_trampoline<P: FnOnce(Result<(), glib::Error>) + 'static>(
584 _source_object: *mut glib::gobject_ffi::GObject,
585 res: *mut crate::ffi::GAsyncResult,
586 user_data: glib::ffi::gpointer,
587 ) {
588 unsafe {
589 let mut error = std::ptr::null_mut();
590 ffi::g_subprocess_wait_finish(_source_object as *mut _, res, &mut error);
591 let result = if error.is_null() {
592 Ok(())
593 } else {
594 Err(from_glib_full(error))
595 };
596 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
597 Box_::from_raw(user_data as *mut _);
598 let callback: P = callback.into_inner();
599 callback(result);
600 }
601 }
602 let callback = wait_async_trampoline::<P>;
603 unsafe {
604 ffi::g_subprocess_wait_async(
605 self.to_glib_none().0,
606 cancellable.map(|p| p.as_ref()).to_glib_none().0,
607 Some(callback),
608 Box_::into_raw(user_data) as *mut _,
609 );
610 }
611 }
612
613 pub fn wait_future(
614 &self,
615 ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
616 Box_::pin(crate::GioFuture::new(
617 self,
618 move |obj, cancellable, send| {
619 obj.wait_async(Some(cancellable), move |res| {
620 send.resolve(res);
621 });
622 },
623 ))
624 }
625
626 /// Combines g_subprocess_wait() with g_spawn_check_wait_status().
627 /// ## `cancellable`
628 /// a #GCancellable
629 ///
630 /// # Returns
631 ///
632 /// [`true`] on success, [`false`] if process exited abnormally, or
633 /// @cancellable was cancelled
634 #[doc(alias = "g_subprocess_wait_check")]
635 pub fn wait_check(
636 &self,
637 cancellable: Option<&impl IsA<Cancellable>>,
638 ) -> Result<(), glib::Error> {
639 unsafe {
640 let mut error = std::ptr::null_mut();
641 let is_ok = ffi::g_subprocess_wait_check(
642 self.to_glib_none().0,
643 cancellable.map(|p| p.as_ref()).to_glib_none().0,
644 &mut error,
645 );
646 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
647 if error.is_null() {
648 Ok(())
649 } else {
650 Err(from_glib_full(error))
651 }
652 }
653 }
654
655 /// Combines g_subprocess_wait_async() with g_spawn_check_wait_status().
656 ///
657 /// This is the asynchronous version of g_subprocess_wait_check().
658 /// ## `cancellable`
659 /// a #GCancellable, or [`None`]
660 /// ## `callback`
661 /// a #GAsyncReadyCallback to call when the operation is complete
662 #[doc(alias = "g_subprocess_wait_check_async")]
663 pub fn wait_check_async<P: FnOnce(Result<(), glib::Error>) + 'static>(
664 &self,
665 cancellable: Option<&impl IsA<Cancellable>>,
666 callback: P,
667 ) {
668 let main_context = glib::MainContext::ref_thread_default();
669 let is_main_context_owner = main_context.is_owner();
670 let has_acquired_main_context = (!is_main_context_owner)
671 .then(|| main_context.acquire().ok())
672 .flatten();
673 assert!(
674 is_main_context_owner || has_acquired_main_context.is_some(),
675 "Async operations only allowed if the thread is owning the MainContext"
676 );
677
678 let user_data: Box_<glib::thread_guard::ThreadGuard<P>> =
679 Box_::new(glib::thread_guard::ThreadGuard::new(callback));
680 unsafe extern "C" fn wait_check_async_trampoline<
681 P: FnOnce(Result<(), glib::Error>) + 'static,
682 >(
683 _source_object: *mut glib::gobject_ffi::GObject,
684 res: *mut crate::ffi::GAsyncResult,
685 user_data: glib::ffi::gpointer,
686 ) {
687 unsafe {
688 let mut error = std::ptr::null_mut();
689 ffi::g_subprocess_wait_check_finish(_source_object as *mut _, res, &mut error);
690 let result = if error.is_null() {
691 Ok(())
692 } else {
693 Err(from_glib_full(error))
694 };
695 let callback: Box_<glib::thread_guard::ThreadGuard<P>> =
696 Box_::from_raw(user_data as *mut _);
697 let callback: P = callback.into_inner();
698 callback(result);
699 }
700 }
701 let callback = wait_check_async_trampoline::<P>;
702 unsafe {
703 ffi::g_subprocess_wait_check_async(
704 self.to_glib_none().0,
705 cancellable.map(|p| p.as_ref()).to_glib_none().0,
706 Some(callback),
707 Box_::into_raw(user_data) as *mut _,
708 );
709 }
710 }
711
712 pub fn wait_check_future(
713 &self,
714 ) -> Pin<Box_<dyn std::future::Future<Output = Result<(), glib::Error>> + 'static>> {
715 Box_::pin(crate::GioFuture::new(
716 self,
717 move |obj, cancellable, send| {
718 obj.wait_check_async(Some(cancellable), move |res| {
719 send.resolve(res);
720 });
721 },
722 ))
723 }
724}