Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

action_entry: Add activate_async helper #903

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion gio/src/action_entry.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Take a look at the license at the top of the repository in the LICENSE file.

use glib::{prelude::*, Variant, VariantTy, VariantType};
use glib::{prelude::*, MainContext, Variant, VariantTy, VariantType};
use std::future::Future;

use crate::{ActionMap, SimpleAction};

Expand Down Expand Up @@ -87,6 +88,30 @@ where
self
}

pub fn activate_async<Fut, F>(mut self, callback: F) -> Self
where
F: Fn(&O, &SimpleAction, Option<&Variant>) -> Fut + 'static + Clone,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why require Clone here? I think it would be better if you would instead use an Rc instead of a Box for storing the callback. Then you get cloning for free and don't make it the user's problem.

Fut: Future<Output = ()>,
{
let future_cb = move |map: &O, action: &SimpleAction, variant: Option<&Variant>| {
let ctx = MainContext::thread_default().unwrap_or_else(|| {
let ctx = glib::MainContext::default();
assert!(ctx.is_owner(), "Current thread does not own the default main context and has no thread-default main context");
ctx
});

let variant = variant.map(ToOwned::to_owned);
ctx.spawn_local(
sdroege marked this conversation as resolved.
Show resolved Hide resolved
glib::clone!(@strong callback, @strong map, @strong action => async move {
callback(&map, &action, variant.as_ref()).await;
}),
);
};

self.0.activate = Some(Box::new(future_cb));
self
}

pub fn change_state<F: Fn(&O, &SimpleAction, Option<&Variant>) + 'static>(
mut self,
callback: F,
Expand Down