Skip to content

Commit ad5f0a4

Browse files
committed
action_entry: Add activate_async helper
This is a helper function in a similar vein to gtk4-rs's `install_action_async ()` for widgets. It allows applications to install actions that use async/await without having to manually create a glib::MainContext in the callback.
1 parent 3a7bf73 commit ad5f0a4

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

gio/src/action_entry.rs

+20
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Take a look at the license at the top of the repository in the LICENSE file.
22

33
use glib::{prelude::*, Variant, VariantTy, VariantType};
4+
use std::future::Future;
45

56
use crate::{ActionMap, SimpleAction};
67

@@ -87,6 +88,25 @@ where
8788
self
8889
}
8990

91+
pub fn activate_async<Fut, F>(mut self, callback: F) -> Self
92+
where
93+
F: Fn(&O, &SimpleAction, Option<&Variant>) -> Fut + 'static + Clone,
94+
Fut: Future<Output = ()>,
95+
{
96+
let future_cb = move |map: &O, action: &SimpleAction, variant: Option<&Variant>| {
97+
let ctx = glib::MainContext::default();
98+
let variant = variant.map(ToOwned::to_owned);
99+
ctx.spawn_local(
100+
glib::clone!(@strong callback, @strong map, @strong action => async move {
101+
callback(&map, &action, variant.as_ref()).await;
102+
}),
103+
);
104+
};
105+
106+
self.0.activate = Some(Box::new(future_cb));
107+
self
108+
}
109+
90110
pub fn change_state<F: Fn(&O, &SimpleAction, Option<&Variant>) + 'static>(
91111
mut self,
92112
callback: F,

0 commit comments

Comments
 (0)