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

Remove one shot commands. #959

Merged
merged 7 commits into from
May 18, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ This means that druid no longer requires cairo on macOS and uses Core Graphics i
- `AppDelegate::command` now receives a `Target` instead of a `&Target`. ([#909] by [@xStrom])
- `SHOW_WINDOW` and `CLOSE_WINDOW` commands now only use `Target` to determine the affected window. ([#928] by [@finnerale])
- Replaced `NEW_WINDOW`, `SET_MENU` and `SHOW_CONTEXT_MENU` commands with methods on `EventCtx` and `DelegateCtx`. ([#931] by [@finnerale])
- Replaced `Command::one_shot` and `::take_object` with a `SingleUse` payload wrapper type. ([#959] by [@finnerale])

### Deprecated

Expand Down Expand Up @@ -198,6 +199,7 @@ This means that druid no longer requires cairo on macOS and uses Core Graphics i
[#951]: https://github.com/xi-editor/druid/pull/951
[#953]: https://github.com/xi-editor/druid/pull/953
[#954]: https://github.com/xi-editor/druid/pull/954
[#959]: https://github.com/xi-editor/druid/pull/959

## [0.5.0] - 2020-04-01

Expand Down
6 changes: 4 additions & 2 deletions druid/src/app_delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ use std::{
collections::VecDeque,
};

use crate::{commands, Command, Data, Env, Event, MenuDesc, Target, WindowDesc, WindowId};
use crate::{
command::SingleUse, commands, Command, Data, Env, Event, MenuDesc, Target, WindowDesc, WindowId,
luleyleo marked this conversation as resolved.
Show resolved Hide resolved
};

/// A context passed in to [`AppDelegate`] functions.
///
Expand Down Expand Up @@ -55,7 +57,7 @@ impl<'a> DelegateCtx<'a> {
pub fn new_window<T: Any>(&mut self, desc: WindowDesc<T>) {
if self.app_data_type == TypeId::of::<T>() {
self.submit_command(
Command::one_shot(commands::NEW_WINDOW, desc),
Command::new(commands::NEW_WINDOW, SingleUse::new(desc)),
Target::Global,
);
} else {
Expand Down
92 changes: 20 additions & 72 deletions druid/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,8 @@ pub struct Selector(&'static str);
/// A `Command` consists of a [`Selector`], that indicates what the command is,
/// and an optional argument, that can be used to pass arbitrary data.
///
///
/// # One-shot and reusable `Commands`
///
/// Commands come in two varieties, 'reusable' and 'one-shot'.
///
/// Regular commands are created with [`Command::new`], and their argument
/// objects may be accessed repeatedly, via [`Command::get_object`].
///
/// One-shot commands are intended for cases where an object should only be
/// used once; an example would be if you have some resource that cannot be
/// cloned, and you wish to send it to another widget.
/// If the payload can't or shouldn't be cloned,
/// wrapping it with [`SingleUse`] allows `take`ing the object.
luleyleo marked this conversation as resolved.
Show resolved Hide resolved
///
/// # Examples
/// ```
Expand All @@ -59,31 +50,27 @@ pub struct Selector(&'static str);
///
/// [`Command::new`]: #method.new
/// [`Command::get_object`]: #method.get_object
/// [`SingleUse`]: struct.SingleUse.html
/// [`Selector`]: struct.Selector.html
#[derive(Debug, Clone)]
pub struct Command {
/// The command's `Selector`.
pub selector: Selector,
object: Option<Arg>,
object: Option<Arc<dyn Any>>,
}

#[derive(Debug, Clone)]
enum Arg {
Reusable(Arc<dyn Any>),
OneShot(Arc<Mutex<Option<Box<dyn Any>>>>),
}
/// `SingleUse` is intended for cases where a command payload should only be
Copy link
Member

Choose a reason for hiding this comment

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

huh I think I lost a comment here?? anyway, to try again:

Doc comments are kind of like git commit messages; you want the first paragraph to be a short general overview that doesn't need a lot of context, and then a blank line, and then a more detailed explanation.

This is because the first paragraph is displayed beside the type name in the module or crate level docs.

For this type, for instance, I would try a first paragraph of something to the effect of,

"A wrapper type for Command arguments that should only be used once."

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Thanks, I should have actually built the docs 😅

I've added the suggested head paragraph, and while I was at it also an example how to make use of SingleUse.

/// used once; an example would be if you have some resource that cannot be
/// cloned, and you wish to send it to another widget.
pub struct SingleUse<T>(Mutex<Option<T>>);
Copy link
Member

Choose a reason for hiding this comment

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

this type isn's actually exposed anywhere, so I don't think external crates can access it?

Also I would expect this to need to be in an Arc, since the Event itself still needs to be cloneable?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good catch, I've reexported it from lib now.

Not sure what you mean regarding the Arc. When using SingleUse the payload will be stored the exact same way as it used to with Arg::OneShot, minus the Box<Any> wrapper as it is now directly stored as Arc<Any>.

Copy link
Member

Choose a reason for hiding this comment

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

ah okay I missed that the Arc has moved into the signature of the object field on Command.


/// Errors that can occur when attempting to retrieve the a command's argument.
#[derive(Debug, Clone, PartialEq)]
pub enum ArgumentError {
/// The command did not have an argument.
NoArgument,
/// The argument was expected to be reusable and wasn't, or vice-versa.
WrongVariant,
/// The argument could not be downcast to the specified type.
IncorrectType,
/// The one-shot argument has already been taken.
Consumed,
}

/// The target of a command.
Expand Down Expand Up @@ -231,67 +218,34 @@ impl Command {
pub fn new(selector: Selector, arg: impl Any) -> Self {
Command {
selector,
object: Some(Arg::Reusable(Arc::new(arg))),
}
}

/// Create a new 'one-shot' `Command`.
///
/// Unlike those created with `Command::new`, one-shot commands cannot
/// be reused; their argument is consumed when it is accessed, via
/// [`take_object`].
///
/// [`take_object`]: #method.take_object
pub fn one_shot(selector: Selector, arg: impl Any) -> Self {
Command {
selector,
object: Some(Arg::OneShot(Arc::new(Mutex::new(Some(Box::new(arg)))))),
object: Some(Arc::new(arg)),
}
}

/// Used to create a command from the types sent via an `ExtEventSink`.
pub(crate) fn from_ext(selector: Selector, object: Option<Box<dyn Any + Send>>) -> Self {
let object: Option<Box<dyn Any>> = object.map(|obj| obj as Box<dyn Any>);
let object = object.map(|o| Arg::Reusable(o.into()));
let object = object.map(|o| o.into());
Command { selector, object }
}

/// Return a reference to this `Command`'s object, if it has one.
///
/// This only works for 'reusable' commands; it does not work for commands
/// created with [`one_shot`].
///
/// [`one_shot`]: #method.one_shot
pub fn get_object<T: Any>(&self) -> Result<&T, ArgumentError> {
match self.object.as_ref() {
Some(Arg::Reusable(o)) => o.downcast_ref().ok_or(ArgumentError::IncorrectType),
Some(Arg::OneShot(_)) => Err(ArgumentError::WrongVariant),
Some(o) => o.downcast_ref().ok_or(ArgumentError::IncorrectType),
None => Err(ArgumentError::NoArgument),
}
}
}

/// Attempt to take the object of a [`one-shot`] command.
///
/// [`one-shot`]: #method.one_shot
pub fn take_object<T: Any>(&self) -> Result<Box<T>, ArgumentError> {
match self.object.as_ref() {
Some(Arg::Reusable(_)) => Err(ArgumentError::WrongVariant),
Some(Arg::OneShot(inner)) => {
let obj = inner
.lock()
.unwrap()
.take()
.ok_or(ArgumentError::Consumed)?;
match obj.downcast::<T>() {
Ok(obj) => Ok(obj),
Err(obj) => {
inner.lock().unwrap().replace(obj);
Err(ArgumentError::IncorrectType)
}
}
}
None => Err(ArgumentError::NoArgument),
}
impl<T: Any> SingleUse<T> {
pub fn new(data: T) -> Self {
SingleUse(Mutex::new(Some(data)))
}

/// Takes the value, leaving a None in its place.
pub fn take(&self) -> Option<T> {
self.0.lock().unwrap().take()
}
}

Expand All @@ -315,12 +269,6 @@ impl std::fmt::Display for ArgumentError {
match self {
ArgumentError::NoArgument => write!(f, "Command has no argument"),
ArgumentError::IncorrectType => write!(f, "Downcast failed: wrong concrete type"),
ArgumentError::Consumed => write!(f, "One-shot command arguemnt already consumed"),
ArgumentError::WrongVariant => write!(
f,
"Incorrect access method for argument type; \
check Command::one_shot docs for more detail."
),
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions druid/src/contexts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ use crate::core::{BaseState, CommandQueue, FocusChange};
use crate::piet::Piet;
use crate::piet::RenderContext;
use crate::{
commands, Affine, Command, ContextMenu, Cursor, Insets, MenuDesc, Point, Rect, Size, Target,
Text, TimerToken, Vec2, WidgetId, WindowDesc, WindowHandle, WindowId,
command::SingleUse, commands, Affine, Command, ContextMenu, Cursor, Insets, MenuDesc, Point,
Rect, Size, Target, Text, TimerToken, Vec2, WidgetId, WindowDesc, WindowHandle, WindowId,
};

/// A mutable context provided to event handling methods of widgets.
Expand Down Expand Up @@ -255,7 +255,7 @@ impl<'a> EventCtx<'a> {
pub fn new_window<T: Any>(&mut self, desc: WindowDesc<T>) {
if self.app_data_type == TypeId::of::<T>() {
self.submit_command(
Command::one_shot(commands::NEW_WINDOW, desc),
Command::new(commands::NEW_WINDOW, SingleUse::new(desc)),
Target::Global,
);
} else {
Expand Down
7 changes: 5 additions & 2 deletions druid/src/win_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use crate::{
WindowId,
};

use crate::command::sys as sys_cmd;
use crate::command::{sys as sys_cmd, SingleUse};

pub(crate) const RUN_COMMANDS_TOKEN: IdleToken = IdleToken::new(1);

Expand Down Expand Up @@ -591,7 +591,10 @@ impl<T: Data> AppState<T> {
}

fn new_window(&mut self, cmd: Command) -> Result<(), Box<dyn std::error::Error>> {
let desc = cmd.take_object::<WindowDesc<T>>()?;
let desc = cmd.get_object::<SingleUse<WindowDesc<T>>>()?;
// The NEW_WINDOW command is private and only druid can receive it by normal means,
// thus unwrapping can be considered save or deserves a panic.
luleyleo marked this conversation as resolved.
Show resolved Hide resolved
let desc = desc.take().unwrap();
let window = desc.build_native(self)?;
window.show();
Ok(())
Expand Down