Skip to main content

gio/
subprocess.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{ffi::OsStr, pin::Pin, ptr};
4
5use glib::{GString, prelude::*, translate::*};
6use libc::c_char;
7
8use crate::{Cancellable, IOErrorEnum, Subprocess, SubprocessFlags, ffi};
9
10impl Subprocess {
11    /// Create a new process with the given flags and argument list.
12    ///
13    /// The argument list is expected to be [`None`]-terminated.
14    /// ## `argv`
15    /// commandline arguments for the subprocess
16    /// ## `flags`
17    /// flags that define the behaviour of the subprocess
18    ///
19    /// # Returns
20    ///
21    /// A newly created #GSubprocess, or [`None`] on error (and @error
22    ///   will be set)
23    #[doc(alias = "g_subprocess_newv")]
24    pub fn newv(argv: &[&OsStr], flags: SubprocessFlags) -> Result<Subprocess, glib::Error> {
25        if argv.is_empty() || argv[0].is_empty() {
26            return Err(glib::Error::new(
27                IOErrorEnum::InvalidArgument,
28                "argv must contain at least one non-empty element",
29            ));
30        }
31
32        unsafe {
33            let mut error = ptr::null_mut();
34            let ret = ffi::g_subprocess_newv(argv.to_glib_none().0, flags.into_glib(), &mut error);
35            if !error.is_null() {
36                Err(from_glib_full(error))
37            } else if ret.is_null() {
38                Err(glib::Error::new(
39                    IOErrorEnum::InvalidArgument,
40                    "g_subprocess_newv() returned NULL without setting an error",
41                ))
42            } else {
43                Ok(from_glib_full(ret))
44            }
45        }
46    }
47
48    /// Asynchronous version of g_subprocess_communicate_utf8().  Complete
49    /// invocation with g_subprocess_communicate_utf8_finish().
50    /// ## `stdin_buf`
51    /// Input data, or [`None`]
52    /// ## `cancellable`
53    /// Cancellable
54    /// ## `callback`
55    /// Callback
56    #[doc(alias = "g_subprocess_communicate_utf8_async")]
57    pub fn communicate_utf8_async<
58        R: FnOnce(Result<(Option<GString>, Option<GString>), glib::Error>) + 'static,
59        C: IsA<Cancellable>,
60    >(
61        &self,
62        stdin_buf: Option<String>,
63        cancellable: Option<&C>,
64        callback: R,
65    ) {
66        let main_context = glib::MainContext::ref_thread_default();
67        let is_main_context_owner = main_context.is_owner();
68        let has_acquired_main_context = (!is_main_context_owner)
69            .then(|| main_context.acquire().ok())
70            .flatten();
71        assert!(
72            is_main_context_owner || has_acquired_main_context.is_some(),
73            "Async operations only allowed if the thread is owning the MainContext"
74        );
75
76        let stdin_buf = stdin_buf.to_glib_full();
77        let cancellable = cancellable.map(|c| c.as_ref());
78        let gcancellable = cancellable.to_glib_none();
79        let user_data: Box<(glib::thread_guard::ThreadGuard<R>, *mut c_char)> =
80            Box::new((glib::thread_guard::ThreadGuard::new(callback), stdin_buf));
81        unsafe extern "C" fn communicate_utf8_async_trampoline<
82            R: FnOnce(Result<(Option<GString>, Option<GString>), glib::Error>) + 'static,
83        >(
84            _source_object: *mut glib::gobject_ffi::GObject,
85            res: *mut ffi::GAsyncResult,
86            user_data: glib::ffi::gpointer,
87        ) {
88            unsafe {
89                let mut error = ptr::null_mut();
90                let mut stdout_buf = ptr::null_mut();
91                let mut stderr_buf = ptr::null_mut();
92                let _ = ffi::g_subprocess_communicate_utf8_finish(
93                    _source_object as *mut _,
94                    res,
95                    &mut stdout_buf,
96                    &mut stderr_buf,
97                    &mut error,
98                );
99                let result = if error.is_null() {
100                    Ok((from_glib_full(stdout_buf), from_glib_full(stderr_buf)))
101                } else {
102                    Err(from_glib_full(error))
103                };
104                let callback: Box<(glib::thread_guard::ThreadGuard<R>, *mut c_char)> =
105                    Box::from_raw(user_data as *mut _);
106                glib::ffi::g_free(callback.1 as *mut _);
107                (callback.0.into_inner())(result);
108            }
109        }
110        unsafe {
111            ffi::g_subprocess_communicate_utf8_async(
112                self.to_glib_none().0,
113                stdin_buf,
114                gcancellable.0,
115                Some(communicate_utf8_async_trampoline::<R>),
116                Box::into_raw(user_data) as *mut _,
117            );
118        }
119    }
120
121    pub fn communicate_utf8_future(
122        &self,
123        stdin_buf: Option<String>,
124    ) -> Pin<
125        Box<
126            dyn std::future::Future<
127                    Output = Result<(Option<GString>, Option<GString>), glib::Error>,
128                > + 'static,
129        >,
130    > {
131        Box::pin(crate::GioFuture::new(
132            self,
133            move |obj, cancellable, send| {
134                obj.communicate_utf8_async(stdin_buf, Some(cancellable), move |res| {
135                    send.resolve(res);
136                });
137            },
138        ))
139    }
140}