use std::{
any::TypeId,
collections::{HashMap, hash_map},
mem, ops,
thread::ThreadId,
};
use crate::{APP, shortcut::CommandShortcutExt, update::UpdatesTrace, widget::info::WidgetInfo, window::WindowId};
use super::*;
#[macro_export]
macro_rules! command {
($(
$(#[$attr:meta])*
$vis:vis static $COMMAND:ident $(=> |$cmd:ident|$custom_meta_init:expr ;)? $(= { $($meta_ident:ident $(!)? : $meta_init:expr),* $(,)? };)? $(;)?
)+) => {
$(
$crate::__command! {
$(#[$attr])*
$vis static $COMMAND $(=> |$cmd|$custom_meta_init)? $(= {
$($meta_ident: $meta_init,)+
})? ;
}
)+
}
}
#[doc(inline)]
pub use command;
use zng_app_context::AppId;
use zng_state_map::{OwnedStateMap, StateId, StateMapMut, StateValue};
use zng_txt::Txt;
use zng_unique_id::{static_id, unique_id_64};
use zng_var::{Var, VarValue, impl_from_and_into_var, var};
#[doc(hidden)]
pub use zng_app_context::app_local;
#[doc(hidden)]
pub use pastey::paste;
#[doc(hidden)]
#[macro_export]
macro_rules! __command {
(
$(#[$attr:meta])*
$vis:vis static $COMMAND:ident => |$cmd:ident| $meta_init:expr;
) => {
$(#[$attr])*
$vis static $COMMAND: $crate::event::Command = {
fn __meta_init__($cmd: $crate::event::Command) {
$meta_init
}
$crate::event::app_local! {
static EVENT: $crate::event::EventData = const { $crate::event::EventData::new(std::stringify!($COMMAND)) };
static DATA: $crate::event::CommandData = $crate::event::CommandData::new(__meta_init__);
}
$crate::event::Command::new(&EVENT, &DATA)
};
};
(
$(#[$attr:meta])*
$vis:vis static $COMMAND:ident = { l10n: $l10n_arg:expr, $($meta_ident:ident : $meta_init:expr),* $(,)? };
) => {
$crate::event::paste! {
$crate::__command! {
$(#[$attr])*
$(#[doc = concat!("<tr> <td>", stringify!($meta_ident), "</td> <td>", stringify!($meta_init), "</td> </tr>")])+
$vis static $COMMAND => |cmd| {
let __l10n_arg = $l10n_arg;
$(
cmd.[<init_ $meta_ident>]($meta_init);
$crate::event::init_meta_l10n(std::env!("CARGO_PKG_NAME"), std::env!("CARGO_PKG_VERSION"), &__l10n_arg, cmd, stringify!($meta_ident), &cmd.$meta_ident());
)*
};
}
}
};
(
$(#[$attr:meta])*
$vis:vis static $COMMAND:ident = { $($meta_ident:ident : $meta_init:expr),* $(,)? };
) => {
$crate::event::paste! {
$crate::__command! {
$(#[$attr])*
$(#[doc = concat!("<tr> <td>", stringify!($meta_ident), "</td> <td>", stringify!($meta_init), "</td> </tr>")])+
$vis static $COMMAND => |cmd| {
$(
cmd.[<init_ $meta_ident>]($meta_init);
)*
};
}
}
};
(
$(#[$attr:meta])*
$vis:vis static $COMMAND:ident;
) => {
$crate::__command! {
$(#[$attr])*
$vis static $COMMAND => |_cmd|{};
}
};
}
#[doc(hidden)]
pub fn init_meta_l10n(
pkg_name: &'static str,
pkg_version: &'static str,
l10n_arg: &dyn Any,
cmd: Command,
meta_name: &'static str,
meta_value: &dyn Any,
) {
if let Some(txt) = meta_value.downcast_ref::<CommandMetaVar<Txt>>() {
let mut l10n_file = "";
if let Some(&enabled) = l10n_arg.downcast_ref::<bool>() {
if !enabled {
return;
}
} else if let Some(&file) = l10n_arg.downcast_ref::<&'static str>() {
l10n_file = file;
} else {
tracing::error!("unknown l10n value in {}", cmd.event().as_any().name());
return;
}
EVENTS_L10N.init_meta_l10n([pkg_name, pkg_version, l10n_file], cmd, meta_name, txt.clone());
}
}
#[derive(Clone, Copy)]
pub struct Command {
event: Event<CommandArgs>,
local: &'static AppLocal<CommandData>,
scope: CommandScope,
}
impl fmt::Debug for Command {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
f.debug_struct("Command")
.field("event", &self.event)
.field("scope", &self.scope)
.finish_non_exhaustive()
} else {
write!(f, "{}", self.event.name())?;
match self.scope {
CommandScope::App => Ok(()),
CommandScope::Window(id) => write!(f, "({id})"),
CommandScope::Widget(id) => write!(f, "({id})"),
}
}
}
}
impl Command {
#[doc(hidden)]
pub const fn new(event_local: &'static AppLocal<EventData>, command_local: &'static AppLocal<CommandData>) -> Self {
Command {
event: Event::new(event_local),
local: command_local,
scope: CommandScope::App,
}
}
pub fn subscribe(&self, enabled: bool) -> CommandHandle {
let mut evs = EVENTS_SV.write();
self.local.write().subscribe(&mut evs, *self, enabled, None)
}
pub fn subscribe_wgt(&self, enabled: bool, target: WidgetId) -> CommandHandle {
let mut evs = EVENTS_SV.write();
self.local.write().subscribe(&mut evs, *self, enabled, Some(target))
}
pub fn event(&self) -> Event<CommandArgs> {
self.event
}
pub fn scope(&self) -> CommandScope {
self.scope
}
pub fn scoped(mut self, scope: impl Into<CommandScope>) -> Command {
self.scope = scope.into();
self
}
pub fn with_meta<R>(&self, visit: impl FnOnce(&mut CommandMeta) -> R) -> R {
fn init_meta(self_: &Command) -> parking_lot::MappedRwLockReadGuard<'static, CommandData> {
{
let mut write = self_.local.write();
match write.meta_init.clone() {
MetaInit::Init(init) => {
let lock = Arc::new((std::thread::current().id(), Mutex::new(())));
write.meta_init = MetaInit::Initing(lock.clone());
let _init_guard = lock.1.lock();
drop(write);
init(*self_);
self_.local.write().meta_init = MetaInit::Inited;
}
MetaInit::Initing(l) => {
drop(write);
if l.0 != std::thread::current().id() {
let _wait = l.1.lock();
}
}
MetaInit::Inited => {}
}
}
if !matches!(self_.scope, CommandScope::App) {
let mut write = self_.local.write();
write.scopes.entry(self_.scope).or_default();
}
self_.local.read()
}
let local_read = init_meta(self);
let mut meta_lock = local_read.meta.lock();
match self.scope {
CommandScope::App => visit(&mut CommandMeta {
meta: meta_lock.borrow_mut(),
scope: None,
}),
scope => {
let scope = local_read.scopes.get(&scope).unwrap();
visit(&mut CommandMeta {
meta: meta_lock.borrow_mut(),
scope: Some(scope.meta.lock().borrow_mut()),
})
}
}
}
pub fn has(&self, update: &EventUpdate) -> bool {
self.on(update).is_some()
}
pub fn on<'a>(&self, update: &'a EventUpdate) -> Option<&'a CommandArgs> {
self.event.on(update).filter(|a| a.scope == self.scope)
}
pub fn on_unhandled<'a>(&self, update: &'a EventUpdate) -> Option<&'a CommandArgs> {
self.event
.on(update)
.filter(|a| a.scope == self.scope && !a.propagation().is_stopped())
}
pub fn handle<R>(&self, update: &EventUpdate, handler: impl FnOnce(&CommandArgs) -> R) -> Option<R> {
if let Some(args) = self.on(update) {
args.handle(handler)
} else {
None
}
}
pub fn has_handlers(&self) -> Var<bool> {
let mut write = self.local.write();
match self.scope {
CommandScope::App => write.has_handlers.read_only(),
scope => write.scopes.entry(scope).or_default().has_handlers.read_only(),
}
}
pub fn is_enabled(&self) -> Var<bool> {
let mut write = self.local.write();
match self.scope {
CommandScope::App => write.is_enabled.read_only(),
scope => write.scopes.entry(scope).or_default().is_enabled.read_only(),
}
}
pub fn has_handlers_value(&self) -> bool {
let read = self.local.read();
match self.scope {
CommandScope::App => read.handle_count > 0,
scope => read.scopes.get(&scope).map(|l| l.handle_count > 0).unwrap_or(false),
}
}
pub fn is_enabled_value(&self) -> bool {
let read = self.local.read();
match self.scope {
CommandScope::App => read.enabled_count > 0,
scope => read.scopes.get(&scope).map(|l| l.enabled_count > 0).unwrap_or(false),
}
}
pub fn visit_scopes<T>(&self, mut visitor: impl FnMut(Command) -> ControlFlow<T>) -> Option<T> {
let read = self.local.read();
for &scope in read.scopes.keys() {
match visitor(self.scoped(scope)) {
ControlFlow::Continue(_) => continue,
ControlFlow::Break(r) => return Some(r),
}
}
None
}
pub fn notify(&self) {
self.event.notify(CommandArgs::now(None, self.scope, self.is_enabled_value()))
}
pub fn notify_descendants(&self, parent: &WidgetInfo) {
self.visit_scopes::<()>(|parse_cmd| {
if let CommandScope::Widget(id) = parse_cmd.scope()
&& let Some(scope) = parent.tree().get(id)
&& scope.is_descendant(parent)
{
parse_cmd.notify();
}
ControlFlow::Continue(())
});
}
pub fn notify_param(&self, param: impl Any + Send + Sync) {
self.event
.notify(CommandArgs::now(CommandParam::new(param), self.scope, self.is_enabled_value()));
}
pub fn notify_linked(&self, propagation: EventPropagationHandle, param: Option<CommandParam>) {
self.event.notify(CommandArgs::new(
crate::INSTANT.now(),
propagation,
param,
self.scope,
self.is_enabled_value(),
))
}
pub fn new_update(&self) -> EventUpdate {
self.event.new_update(CommandArgs::now(None, self.scope, self.is_enabled_value()))
}
pub fn new_update_param(&self, param: impl Any + Send + Sync) -> EventUpdate {
self.event
.new_update(CommandArgs::now(CommandParam::new(param), self.scope, self.is_enabled_value()))
}
pub fn on_pre_event(&self, enabled: bool, handler: Handler<AppCommandArgs>) -> EventHandle {
self.event().on_pre_event(self.handler(enabled, handler))
}
pub fn on_event(&self, enabled: bool, handler: Handler<AppCommandArgs>) -> EventHandle {
self.event().on_event(self.handler(enabled, handler))
}
fn handler(&self, enabled: bool, mut handler: Handler<AppCommandArgs>) -> Handler<CommandArgs> {
let handle = Arc::new(self.subscribe(enabled));
Box::new(move |args| {
handler(&AppCommandArgs {
args: args.clone(),
handle: handle.clone(),
})
})
}
#[must_use]
pub(crate) fn update_state(&self) -> bool {
let mut write = self.local.write();
if let CommandScope::App = self.scope {
let has_handlers = write.handle_count > 0;
if has_handlers != write.has_handlers.get() {
write.has_handlers.set(has_handlers);
}
let is_enabled = has_handlers && write.enabled_count > 0;
if is_enabled != write.is_enabled.get() {
write.is_enabled.set(is_enabled);
}
true
} else if let hash_map::Entry::Occupied(entry) = write.scopes.entry(self.scope) {
let scope = entry.get();
if scope.handle_count == 0 && scope.has_handlers.strong_count() == 1 && scope.is_enabled.strong_count() == 1 {
entry.remove();
return false;
}
let has_handlers = scope.handle_count > 0;
if has_handlers != scope.has_handlers.get() {
scope.has_handlers.set(has_handlers);
}
let is_enabled = has_handlers && scope.enabled_count > 0;
if is_enabled != scope.is_enabled.get() {
scope.is_enabled.set(is_enabled);
}
true
} else {
false
}
}
}
impl Deref for Command {
type Target = Event<CommandArgs>;
fn deref(&self) -> &Self::Target {
&self.event
}
}
impl PartialEq for Command {
fn eq(&self, other: &Self) -> bool {
self.event == other.event && self.scope == other.scope
}
}
impl Eq for Command {}
impl std::hash::Hash for Command {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
std::hash::Hash::hash(&self.event.as_any(), state);
std::hash::Hash::hash(&self.scope, state);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum CommandScope {
App,
Window(WindowId),
Widget(WidgetId),
}
impl_from_and_into_var! {
fn from(id: WidgetId) -> CommandScope {
CommandScope::Widget(id)
}
fn from(id: WindowId) -> CommandScope {
CommandScope::Window(id)
}
fn from(widget_name: &'static str) -> CommandScope {
WidgetId::named(widget_name).into()
}
fn from(widget_name: Txt) -> CommandScope {
WidgetId::named(widget_name).into()
}
}
event_args! {
pub struct CommandArgs {
pub param: Option<CommandParam>,
pub scope: CommandScope,
pub enabled: bool,
..
fn delivery_list(&self, list: &mut UpdateDeliveryList) {
match self.scope {
CommandScope::Widget(id) => list.search_widget(id),
CommandScope::Window(id) => list.insert_window(id),
CommandScope::App => list.search_all(),
}
}
}
}
impl CommandArgs {
pub fn param<T: Any>(&self) -> Option<&T> {
self.param.as_ref().and_then(|p| p.downcast_ref::<T>())
}
pub fn enabled_param<T: Any>(&self) -> Option<&T> {
if self.enabled { self.param::<T>() } else { None }
}
pub fn disabled_param<T: Any>(&self) -> Option<&T> {
if !self.enabled { self.param::<T>() } else { None }
}
pub fn handle_enabled<F, R>(&self, local_handle: &CommandHandle, handler: F) -> Option<R>
where
F: FnOnce(&Self) -> R,
{
if self.propagation().is_stopped() || !self.enabled || !local_handle.is_enabled() {
None
} else {
let r = handler(self);
self.propagation().stop();
Some(r)
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct AppCommandArgs {
pub args: CommandArgs,
pub handle: Arc<CommandHandle>,
}
impl ops::Deref for AppCommandArgs {
type Target = CommandArgs;
fn deref(&self) -> &Self::Target {
&self.args
}
}
impl AnyEventArgs for AppCommandArgs {
fn clone_any(&self) -> Box<dyn AnyEventArgs> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn timestamp(&self) -> crate::DInstant {
self.args.timestamp()
}
fn delivery_list(&self, list: &mut UpdateDeliveryList) {
self.args.delivery_list(list)
}
fn propagation(&self) -> &EventPropagationHandle {
self.args.propagation()
}
}
impl EventArgs for AppCommandArgs {}
pub struct CommandHandle {
command: Option<Command>,
local_enabled: AtomicBool,
app_id: Option<AppId>,
_event_handle: EventHandle,
}
impl CommandHandle {
pub fn command(&self) -> Option<Command> {
self.command
}
pub fn set_enabled(&self, enabled: bool) {
if let Some(command) = self.command
&& self.local_enabled.swap(enabled, Ordering::Relaxed) != enabled
{
if self.app_id != APP.id() {
return;
}
UpdatesTrace::log_var(std::any::type_name::<bool>());
let mut write = command.local.write();
match command.scope {
CommandScope::App => {
if enabled {
write.enabled_count += 1;
} else {
write.enabled_count -= 1;
}
}
scope => {
if let Some(data) = write.scopes.get_mut(&scope) {
if enabled {
data.enabled_count += 1;
} else {
data.enabled_count -= 1;
}
}
}
}
}
}
pub fn is_enabled(&self) -> bool {
self.local_enabled.load(Ordering::Relaxed)
}
pub fn dummy() -> Self {
CommandHandle {
command: None,
app_id: None,
local_enabled: AtomicBool::new(false),
_event_handle: EventHandle::dummy(),
}
}
pub fn is_dummy(&self) -> bool {
self.command.is_none()
}
}
impl fmt::Debug for CommandHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CommandHandle")
.field("command", &self.command)
.field("local_enabled", &self.local_enabled.load(Ordering::Relaxed))
.finish()
}
}
impl Drop for CommandHandle {
fn drop(&mut self) {
if let Some(command) = self.command {
if self.app_id != APP.id() {
return;
}
let mut write = command.local.write();
match command.scope {
CommandScope::App => {
write.handle_count -= 1;
if self.local_enabled.load(Ordering::Relaxed) {
write.enabled_count -= 1;
}
}
scope => {
if let Some(data) = write.scopes.get_mut(&scope) {
data.handle_count -= 1;
if self.local_enabled.load(Ordering::Relaxed) {
data.enabled_count -= 1;
}
}
}
}
}
}
}
impl Default for CommandHandle {
fn default() -> Self {
Self::dummy()
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct CommandParam(pub Arc<dyn Any + Send + Sync>);
impl PartialEq for CommandParam {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for CommandParam {}
impl CommandParam {
pub fn new(param: impl Any + Send + Sync + 'static) -> Self {
let p: &dyn Any = ¶m;
if let Some(p) = p.downcast_ref::<Self>() {
p.clone()
} else if let Some(p) = p.downcast_ref::<Arc<dyn Any + Send + Sync>>() {
CommandParam(p.clone())
} else {
CommandParam(Arc::new(param))
}
}
pub fn type_id(&self) -> TypeId {
self.0.type_id()
}
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
self.0.downcast_ref()
}
pub fn is<T: Any>(&self) -> bool {
self.0.is::<T>()
}
}
impl fmt::Debug for CommandParam {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("CommandParam").field(&self.0.type_id()).finish()
}
}
zng_var::impl_from_and_into_var! {
fn from(param: CommandParam) -> Option<CommandParam>;
}
#[rustfmt::skip] unique_id_64! {
pub struct CommandMetaVarId<T: (StateValue + VarValue)>: StateId;
}
zng_unique_id::impl_unique_id_bytemuck!(CommandMetaVarId<T: (StateValue + VarValue)>);
impl<T: StateValue + VarValue> CommandMetaVarId<T> {
fn app(self) -> StateId<Var<T>> {
let id = self.get();
StateId::from_raw(id)
}
fn scope(self) -> StateId<Var<T>> {
let id = self.get();
StateId::from_raw(id)
}
}
impl<T: StateValue + VarValue> fmt::Debug for CommandMetaVarId<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
#[cfg(debug_assertions)]
let t = pretty_type_name::pretty_type_name::<T>();
#[cfg(not(debug_assertions))]
let t = "$T";
if f.alternate() {
writeln!(f, "CommandMetaVarId<{t} {{")?;
writeln!(f, " id: {},", self.get())?;
writeln!(f, " sequential: {}", self.sequential())?;
writeln!(f, "}}")
} else {
write!(f, "CommandMetaVarId<{t}>({})", self.sequential())
}
}
}
pub struct CommandMeta<'a> {
meta: StateMapMut<'a, CommandMetaState>,
scope: Option<StateMapMut<'a, CommandMetaState>>,
}
impl CommandMeta<'_> {
pub fn get_or_insert<T, F>(&mut self, id: impl Into<StateId<T>>, init: F) -> T
where
T: StateValue + Clone,
F: FnOnce() -> T,
{
let id = id.into();
if let Some(scope) = &mut self.scope {
if let Some(value) = scope.get(id) {
value.clone()
} else if let Some(value) = self.meta.get(id) {
value.clone()
} else {
let value = init();
let r = value.clone();
scope.set(id, value);
r
}
} else {
self.meta.entry(id).or_insert_with(init).clone()
}
}
pub fn get_or_default<T>(&mut self, id: impl Into<StateId<T>>) -> T
where
T: StateValue + Clone + Default,
{
self.get_or_insert(id, Default::default)
}
pub fn get<T>(&self, id: impl Into<StateId<T>>) -> Option<T>
where
T: StateValue + Clone,
{
let id = id.into();
if let Some(scope) = &self.scope {
scope.get(id).or_else(|| self.meta.get(id))
} else {
self.meta.get(id)
}
.cloned()
}
pub fn set<T>(&mut self, id: impl Into<StateId<T>>, value: impl Into<T>)
where
T: StateValue + Clone,
{
if let Some(scope) = &mut self.scope {
scope.set(id, value);
} else {
self.meta.set(id, value);
}
}
pub fn init<T>(&mut self, id: impl Into<StateId<T>>, value: impl Into<T>)
where
T: StateValue + Clone,
{
self.meta.entry(id).or_insert(value);
}
pub fn get_var_or_insert<T, F>(&mut self, id: impl Into<CommandMetaVarId<T>>, init: F) -> CommandMetaVar<T>
where
T: StateValue + VarValue,
F: FnOnce() -> T,
{
let id = id.into();
if let Some(scope) = &mut self.scope {
let meta = &mut self.meta;
scope
.entry(id.scope())
.or_insert_with(|| {
let var = meta.entry(id.app()).or_insert_with(|| var(init())).clone();
var.cow()
})
.clone()
} else {
self.meta.entry(id.app()).or_insert_with(|| var(init())).clone()
}
}
pub fn get_var<T>(&self, id: impl Into<CommandMetaVarId<T>>) -> Option<CommandMetaVar<T>>
where
T: StateValue + VarValue,
{
let id = id.into();
if let Some(scope) = &self.scope {
let meta = &self.meta;
scope.get(id.scope()).cloned().or_else(|| meta.get(id.app()).cloned())
} else {
self.meta.get(id.app()).cloned()
}
}
pub fn get_var_or_default<T>(&mut self, id: impl Into<CommandMetaVarId<T>>) -> CommandMetaVar<T>
where
T: StateValue + VarValue + Default,
{
self.get_var_or_insert(id, Default::default)
}
pub fn init_var<T>(&mut self, id: impl Into<CommandMetaVarId<T>>, value: impl Into<T>)
where
T: StateValue + VarValue,
{
self.meta.entry(id.into().app()).or_insert_with(|| var(value.into()));
}
}
pub type CommandMetaVar<T> = Var<T>;
pub type ReadOnlyCommandMetaVar<T> = Var<T>;
pub trait CommandNameExt {
fn name(self) -> CommandMetaVar<Txt>;
fn init_name(self, name: impl Into<Txt>) -> Self;
fn name_with_shortcut(self) -> Var<Txt>
where
Self: crate::shortcut::CommandShortcutExt;
}
static_id! {
static ref COMMAND_NAME_ID: CommandMetaVarId<Txt>;
}
impl CommandNameExt for Command {
fn name(self) -> CommandMetaVar<Txt> {
self.with_meta(|m| {
m.get_var_or_insert(*COMMAND_NAME_ID, || {
let name = self.event.name();
let name = name.strip_suffix("_CMD").unwrap_or(name);
let mut title = String::with_capacity(name.len());
let mut lower = false;
for c in name.chars() {
if c == '_' {
if !title.ends_with(' ') {
title.push(' ');
}
lower = false;
} else if lower {
for l in c.to_lowercase() {
title.push(l);
}
} else {
title.push(c);
lower = true;
}
}
Txt::from(title)
})
})
}
fn init_name(self, name: impl Into<Txt>) -> Self {
self.with_meta(|m| m.init_var(*COMMAND_NAME_ID, name.into()));
self
}
fn name_with_shortcut(self) -> Var<Txt>
where
Self: crate::shortcut::CommandShortcutExt,
{
crate::var::merge_var!(self.name(), self.shortcut(), |name, shortcut| {
if shortcut.is_empty() {
name.clone()
} else {
zng_txt::formatx!("{name} ({})", shortcut[0])
}
})
}
}
pub trait CommandInfoExt {
fn info(self) -> CommandMetaVar<Txt>;
fn init_info(self, info: impl Into<Txt>) -> Self;
}
static_id! {
static ref COMMAND_INFO_ID: CommandMetaVarId<Txt>;
}
impl CommandInfoExt for Command {
fn info(self) -> CommandMetaVar<Txt> {
self.with_meta(|m| m.get_var_or_insert(*COMMAND_INFO_ID, Txt::default))
}
fn init_info(self, info: impl Into<Txt>) -> Self {
self.with_meta(|m| m.init_var(*COMMAND_INFO_ID, info.into()));
self
}
}
enum CommandMetaState {}
#[derive(Clone)]
enum MetaInit {
Init(fn(Command)),
Initing(Arc<(ThreadId, Mutex<()>)>),
Inited,
}
#[doc(hidden)]
pub struct CommandData {
meta_init: MetaInit,
meta: Mutex<OwnedStateMap<CommandMetaState>>,
handle_count: usize,
enabled_count: usize,
registered: bool,
has_handlers: Var<bool>,
is_enabled: Var<bool>,
scopes: HashMap<CommandScope, ScopedValue>,
}
impl CommandData {
pub fn new(meta_init: fn(Command)) -> Self {
CommandData {
meta_init: MetaInit::Init(meta_init),
meta: Mutex::new(OwnedStateMap::new()),
handle_count: 0,
enabled_count: 0,
registered: false,
has_handlers: var(false),
is_enabled: var(false),
scopes: HashMap::default(),
}
}
fn subscribe(&mut self, events: &mut EventsService, command: Command, enabled: bool, mut target: Option<WidgetId>) -> CommandHandle {
match command.scope {
CommandScope::App => {
if !mem::replace(&mut self.registered, true) {
events.register_command(command);
}
self.handle_count += 1;
if enabled {
self.enabled_count += 1;
}
}
scope => {
let data = self.scopes.entry(scope).or_default();
if !mem::replace(&mut data.registered, true) {
events.register_command(command);
}
data.handle_count += 1;
if enabled {
data.enabled_count += 1;
}
if let CommandScope::Widget(id) = scope {
target = Some(id);
}
}
};
CommandHandle {
command: Some(command),
app_id: APP.id(),
local_enabled: AtomicBool::new(enabled),
_event_handle: target.map(|t| command.event.subscribe(t)).unwrap_or_else(EventHandle::dummy),
}
}
}
struct ScopedValue {
handle_count: usize,
enabled_count: usize,
is_enabled: Var<bool>,
has_handlers: Var<bool>,
meta: Mutex<OwnedStateMap<CommandMetaState>>,
registered: bool,
}
impl Default for ScopedValue {
fn default() -> Self {
ScopedValue {
is_enabled: var(false),
has_handlers: var(false),
handle_count: 0,
enabled_count: 0,
meta: Mutex::new(OwnedStateMap::default()),
registered: false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
command! {
static FOO_CMD;
}
#[test]
fn parameter_none() {
let _ = CommandArgs::now(None, CommandScope::App, true);
}
#[test]
fn enabled() {
let _app = APP.minimal().run_headless(false);
assert!(!FOO_CMD.has_handlers_value());
let handle = FOO_CMD.subscribe(true);
assert!(FOO_CMD.is_enabled_value());
handle.set_enabled(false);
assert!(FOO_CMD.has_handlers_value());
assert!(!FOO_CMD.is_enabled_value());
handle.set_enabled(true);
assert!(FOO_CMD.is_enabled_value());
drop(handle);
assert!(!FOO_CMD.has_handlers_value());
}
#[test]
fn enabled_scoped() {
let _app = APP.minimal().run_headless(false);
let cmd = FOO_CMD;
let cmd_scoped = FOO_CMD.scoped(WindowId::named("enabled_scoped"));
assert!(!cmd.has_handlers_value());
assert!(!cmd_scoped.has_handlers_value());
let handle_scoped = cmd_scoped.subscribe(true);
assert!(!cmd.has_handlers_value());
assert!(cmd_scoped.is_enabled_value());
handle_scoped.set_enabled(false);
assert!(!cmd.has_handlers_value());
assert!(!cmd_scoped.is_enabled_value());
assert!(cmd_scoped.has_handlers_value());
handle_scoped.set_enabled(true);
assert!(!cmd.has_handlers_value());
assert!(cmd_scoped.is_enabled_value());
drop(handle_scoped);
assert!(!cmd.has_handlers_value());
assert!(!cmd_scoped.has_handlers_value());
}
#[test]
fn has_handlers() {
let _app = APP.minimal().run_headless(false);
assert!(!FOO_CMD.has_handlers_value());
let handle = FOO_CMD.subscribe(false);
assert!(FOO_CMD.has_handlers_value());
drop(handle);
assert!(!FOO_CMD.has_handlers_value());
}
#[test]
fn has_handlers_scoped() {
let _app = APP.minimal().run_headless(false);
let cmd = FOO_CMD;
let cmd_scoped = FOO_CMD.scoped(WindowId::named("has_handlers_scoped"));
assert!(!cmd.has_handlers_value());
assert!(!cmd_scoped.has_handlers_value());
let handle = cmd_scoped.subscribe(false);
assert!(!cmd.has_handlers_value());
assert!(cmd_scoped.has_handlers_value());
drop(handle);
assert!(!cmd.has_handlers_value());
assert!(!cmd_scoped.has_handlers_value());
}
}