use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug};
use std::rc::Rc;
use waft_foundation::{
App, Handle, HandleId, Listener, OptionRetained, Ref, Retained, ValueChanged,
};
use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
use waft_services::{MouseCursor, MouseCursorRef};
use crate::framework::{
BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
WidgetRef,
};
use crate::view::View;
use crate::widgets::basic::MouseRegion;
use crate::widgets::focus_manager::{
FocusHighlightMode, FocusManager, FocusNodeRef, HighlightModeListener, KeyEventResult,
primary_focus,
};
use crate::widgets::focus_scope::Focus;
use crate::widgets::media_query::{MediaQuery, NavigationMode};
use crate::widgets::shortcuts::{ShortcutMap, Shortcuts};
fn get_parent(app: &App, context: BuildContext) -> Option<BuildContext> {
let mut parent = None;
context.visit_ancestor_elements(app, &mut |ancestor| {
parent = Some(ancestor);
false
});
parent
}
pub trait Intent: Debug + 'static {
fn as_any(&self) -> &dyn Any;
fn intent_type(&self) -> TypeId {
self.as_any().type_id()
}
}
pub type IntentRef = Rc<dyn Intent>;
pub const DO_NOTHING: DoNothingIntent = DoNothingIntent::new();
pub trait ActionIntent: 'static {
fn cast_intent(intent: &dyn Intent) -> Option<&Self>;
fn as_intent(&self) -> &dyn Intent;
}
impl<T: Intent> ActionIntent for T {
fn cast_intent(intent: &dyn Intent) -> Option<&T> {
intent.as_any().downcast_ref::<T>()
}
fn as_intent(&self) -> &dyn Intent {
self
}
}
impl ActionIntent for dyn Intent {
fn cast_intent(intent: &dyn Intent) -> Option<&dyn Intent> {
Some(intent)
}
fn as_intent(&self) -> &dyn Intent {
self
}
}
pub type ActionListenerCallback = Rc<dyn Fn(&mut App, AnyAction)>;
pub struct ActionData {
listeners: Vec<ActionListenerCallback>,
current_calling_action: Option<ActionRef>,
}
impl ActionData {
pub fn new() -> ActionData {
ActionData {
listeners: Vec::new(),
current_calling_action: None,
}
}
}
impl Default for ActionData {
fn default() -> ActionData {
ActionData::new()
}
}
#[macro_export]
macro_rules! action_accessors {
() => {
fn action_data(
self: ::waft_foundation::Handle<Self>,
app: &::waft_foundation::App,
) -> &$crate::ActionData {
&app.get(self).action
}
fn action_data_mut(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
) -> &mut $crate::ActionData {
&mut app.get_mut(self).action
}
};
}
#[macro_export]
macro_rules! context_action_overrides {
() => {
fn as_action(self: ::waft_foundation::Handle<Self>) -> $crate::AnyAction {
$crate::AnyAction::of_context::<Self>(self)
}
fn is_enabled(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
intent: &Self::Intent,
) -> bool {
$crate::ContextAction::is_enabled(self, app, intent, None)
}
fn invoke(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
intent: &Self::Intent,
) -> Option<::std::rc::Rc<dyn ::std::any::Any>> {
$crate::ContextAction::invoke(self, app, intent, None)
}
fn make_overridable_action(
self: ::waft_foundation::Handle<Self>,
app: &mut ::waft_foundation::App,
context: $crate::BuildContext,
) -> $crate::ActionRef {
let default_action: $crate::ActionRef = self.keep(app).into_erased();
$crate::OverridableContextAction::<Self::Intent>::new(app, default_action, context)
.into_erased()
}
};
}
pub trait Action: Sized + 'static {
type Intent: ActionIntent + ?Sized;
fn action_data(self: Handle<Self>, app: &App) -> &ActionData;
fn action_data_mut(self: Handle<Self>, app: &mut App) -> &mut ActionData;
fn as_action(self: Handle<Self>) -> AnyAction {
AnyAction::of::<Self>(self)
}
fn intent_type() -> TypeId {
TypeId::of::<Self::Intent>()
}
fn calling_action(self: Handle<Self>, app: &App) -> Option<AnyAction> {
self.action_data(app).current_calling_action.handle()
}
fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
self.action_data_mut(app).current_calling_action = value;
}
fn is_enabled(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
let _ = intent;
self.is_action_enabled(app)
}
fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
let _ = app;
true
}
fn consumes_key(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
let _ = (app, intent);
true
}
fn to_key_event_result(
self: Handle<Self>,
app: &mut App,
intent: &Self::Intent,
invoke_result: Option<&Rc<dyn Any>>,
) -> KeyEventResult {
let _ = invoke_result;
if self.consumes_key(app, intent) {
KeyEventResult::Handled
} else {
KeyEventResult::SkipRemainingHandlers
}
}
fn invoke(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> Option<Rc<dyn Any>>;
fn add_action_listener(self: Handle<Self>, app: &mut App, listener: ActionListenerCallback) {
self.action_data_mut(app).listeners.push(listener);
}
fn remove_action_listener(
self: Handle<Self>,
app: &mut App,
listener: &ActionListenerCallback,
) {
let listeners = &mut self.action_data_mut(app).listeners;
if let Some(index) = listeners
.iter()
.position(|registered| Rc::ptr_eq(registered, listener))
{
listeners.remove(index);
}
}
fn notify_action_listeners(self: Handle<Self>, app: &mut App) {
if self.action_data(app).listeners.is_empty() {
return;
}
let local_listeners = self.action_data(app).listeners.clone();
let this = self.as_action();
for listener in local_listeners {
let still_registered = self
.action_data(app)
.listeners
.iter()
.any(|registered| Rc::ptr_eq(registered, &listener));
if still_registered {
listener(app, this);
}
}
}
fn make_overridable_action(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
) -> ActionRef {
let default_action: ActionRef = self.keep(app).into_erased();
OverridableAction::<Self::Intent>::new(app, default_action, context).into_erased()
}
}
pub trait ContextAction: Action {
fn is_enabled(
self: Handle<Self>,
app: &mut App,
intent: &Self::Intent,
context: Option<BuildContext>,
) -> bool {
let _ = (intent, context);
Action::is_action_enabled(self, app)
}
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &Self::Intent,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>>;
}
type ToKeyEventResultFn =
fn(&mut App, HandleId, &dyn Intent, Option<&Rc<dyn Any>>) -> KeyEventResult;
type InvokeFn = fn(&mut App, HandleId, &dyn Intent, Option<BuildContext>) -> Option<Rc<dyn Any>>;
struct ActionVTable {
type_name: fn() -> &'static str,
intent_type: fn() -> TypeId,
calling_action: fn(&App, HandleId) -> Option<AnyAction>,
update_calling_action: fn(&mut App, HandleId, Option<ActionRef>),
is_enabled: fn(&mut App, HandleId, &dyn Intent, Option<BuildContext>) -> bool,
is_action_enabled: fn(&mut App, HandleId) -> bool,
consumes_key: fn(&mut App, HandleId, &dyn Intent) -> bool,
to_key_event_result: ToKeyEventResultFn,
invoke: InvokeFn,
add_action_listener: fn(&mut App, HandleId, ActionListenerCallback),
remove_action_listener: fn(&mut App, HandleId, &ActionListenerCallback),
notify_action_listeners: fn(&mut App, HandleId),
make_overridable_action: fn(&mut App, HandleId, BuildContext) -> ActionRef,
}
fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
Handle::from_id(id)
}
fn cast_intent<L: Action>(intent: &dyn Intent) -> &L::Intent {
<L::Intent as ActionIntent>::cast_intent(intent).unwrap_or_else(|| {
panic!(
"An Intent of type {:?} cannot be handled by {}: the Intent must be of a subtype \
of {}.",
intent,
std::any::type_name::<L>(),
std::any::type_name::<L::Intent>()
)
})
}
impl ActionVTable {
const fn of<L: Action>() -> ActionVTable {
ActionVTable {
type_name: std::any::type_name::<L>,
intent_type: L::intent_type,
calling_action: |app, id| L::calling_action(resolve(id), app),
update_calling_action: |app, id, value| {
L::update_calling_action(resolve(id), app, value)
},
is_enabled: |app, id, intent, _context| {
L::is_enabled(resolve(id), app, cast_intent::<L>(intent))
},
is_action_enabled: |app, id| L::is_action_enabled(resolve(id), app),
consumes_key: |app, id, intent| {
L::consumes_key(resolve(id), app, cast_intent::<L>(intent))
},
to_key_event_result: |app, id, intent, invoke_result| {
L::to_key_event_result(resolve(id), app, cast_intent::<L>(intent), invoke_result)
},
invoke: |app, id, intent, _context| {
L::invoke(resolve(id), app, cast_intent::<L>(intent))
},
add_action_listener: |app, id, listener| {
L::add_action_listener(resolve(id), app, listener)
},
remove_action_listener: |app, id, listener| {
L::remove_action_listener(resolve(id), app, listener)
},
notify_action_listeners: |app, id| L::notify_action_listeners(resolve(id), app),
make_overridable_action: |app, id, context| {
L::make_overridable_action(resolve(id), app, context)
},
}
}
const fn of_context<L: ContextAction>() -> ActionVTable {
ActionVTable {
is_enabled: |app, id, intent, context| {
ContextAction::is_enabled(resolve::<L>(id), app, cast_intent::<L>(intent), context)
},
invoke: |app, id, intent, context| {
ContextAction::invoke(resolve::<L>(id), app, cast_intent::<L>(intent), context)
},
..ActionVTable::of::<L>()
}
}
}
#[derive(Clone, Copy)]
pub struct AnyAction {
id: HandleId,
vtable: &'static ActionVTable,
}
pub type ActionRef = Retained<AnyAction>;
waft_foundation::erased_handle!(AnyAction: Action => Action::as_action);
impl fmt::Debug for AnyAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
}
}
impl AnyAction {
pub fn of<L: Action>(action: Handle<L>) -> AnyAction {
AnyAction {
id: action.id(),
vtable: const { &ActionVTable::of::<L>() },
}
}
pub fn of_context<L: ContextAction>(action: Handle<L>) -> AnyAction {
AnyAction {
id: action.id(),
vtable: const { &ActionVTable::of_context::<L>() },
}
}
pub fn overridable(
app: &mut App,
default_action: ActionRef,
context: BuildContext,
) -> ActionRef {
default_action.make_overridable_action(app, context)
}
pub fn id(self) -> HandleId {
self.id
}
pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
app.handle::<T>(self.id)
}
pub fn intent_type(self) -> TypeId {
(self.vtable.intent_type)()
}
pub fn calling_action(self, app: &App) -> Option<AnyAction> {
(self.vtable.calling_action)(app, self.id)
}
pub fn update_calling_action(self, app: &mut App, value: Option<ActionRef>) {
(self.vtable.update_calling_action)(app, self.id, value);
}
pub fn is_enabled(
self,
app: &mut App,
intent: &dyn Intent,
context: Option<BuildContext>,
) -> bool {
(self.vtable.is_enabled)(app, self.id, intent, context)
}
pub fn is_action_enabled(self, app: &mut App) -> bool {
(self.vtable.is_action_enabled)(app, self.id)
}
pub fn consumes_key(self, app: &mut App, intent: &dyn Intent) -> bool {
(self.vtable.consumes_key)(app, self.id, intent)
}
pub fn to_key_event_result(
self,
app: &mut App,
intent: &dyn Intent,
invoke_result: Option<&Rc<dyn Any>>,
) -> KeyEventResult {
(self.vtable.to_key_event_result)(app, self.id, intent, invoke_result)
}
pub fn invoke(
self,
app: &mut App,
intent: &dyn Intent,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
(self.vtable.invoke)(app, self.id, intent, context)
}
pub fn add_action_listener(self, app: &mut App, listener: ActionListenerCallback) {
(self.vtable.add_action_listener)(app, self.id, listener);
}
pub fn remove_action_listener(self, app: &mut App, listener: &ActionListenerCallback) {
(self.vtable.remove_action_listener)(app, self.id, listener);
}
pub fn notify_action_listeners(self, app: &mut App) {
(self.vtable.notify_action_listeners)(app, self.id);
}
fn make_overridable_action(self, app: &mut App, context: BuildContext) -> ActionRef {
(self.vtable.make_overridable_action)(app, self.id, context)
}
}
pub struct ActionListener {
pub key: Option<KeyRef>,
pub listener: ActionListenerCallback,
pub action: ActionRef,
pub child: WidgetRef,
}
impl ActionListener {
pub fn new<K>(
listener: ActionListenerCallback,
action: ActionRef,
child: impl IntoWidget<K>,
) -> ActionListener {
ActionListener {
key: None,
listener,
action,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> ActionListener {
self.key = Some(key);
self
}
}
impl fmt::Debug for ActionListener {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ActionListener")
.field("action", &self.action)
.finish_non_exhaustive()
}
}
impl StatefulWidget for ActionListener {
type State = ActionListenerState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> ActionListenerState {
ActionListenerState {
state: StateData::new(),
}
}
}
pub struct ActionListenerState {
state: StateData<ActionListener>,
}
impl State for ActionListenerState {
type Widget = ActionListener;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let widget = self.widget(app);
let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
action.add_action_listener(app, listener);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ActionListener) {
let widget = self.widget(app);
let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
if old_widget.action == action && Rc::ptr_eq(&old_widget.listener, &listener) {
return;
}
let (old_action, old_listener) =
(old_widget.action.handle(), Rc::clone(&old_widget.listener));
old_action.remove_action_listener(app, &old_listener);
action.add_action_listener(app, listener);
}
fn dispose(self: Handle<Self>, app: &mut App) {
let widget = self.widget(app);
let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
action.remove_action_listener(app, &listener);
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
self.widget(app).child.clone()
}
}
pub type OnInvokeCallback<T> = Rc<dyn Fn(&mut App, &T) -> Option<Rc<dyn Any>>>;
pub struct CallbackAction<T: Intent> {
action: ActionData,
on_invoke: OnInvokeCallback<T>,
}
impl<T: Intent> CallbackAction<T> {
pub fn new(app: &mut App, on_invoke: OnInvokeCallback<T>) -> Ref<CallbackAction<T>> {
app.create(CallbackAction {
action: ActionData::new(),
on_invoke,
})
}
}
impl<T: Intent> Action for CallbackAction<T> {
type Intent = T;
crate::action_accessors!();
fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
let on_invoke = Rc::clone(&app.get(self).on_invoke);
on_invoke(app, intent)
}
}
pub type ActionDispatcherRef = Rc<dyn ActionDispatcher>;
pub trait ActionDispatcher: Debug {
fn invoke_action(
&self,
app: &mut App,
action: AnyAction,
intent: &dyn Intent,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let target = context.or_else(|| primary_focus(app).and_then(|node| node.context(app)));
debug_assert!(
action.is_enabled(app, intent, target),
"Action must be enabled when calling invokeAction"
);
action.invoke(app, intent, target)
}
fn invoke_action_if_enabled(
&self,
app: &mut App,
action: AnyAction,
intent: &dyn Intent,
context: Option<BuildContext>,
) -> (bool, Option<Rc<dyn Any>>) {
let target = context.or_else(|| primary_focus(app).and_then(|node| node.context(app)));
if action.is_enabled(app, intent, target) {
return (true, action.invoke(app, intent, target));
}
(false, None)
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct PlainActionDispatcher;
impl PlainActionDispatcher {
pub fn new() -> PlainActionDispatcher {
PlainActionDispatcher
}
}
impl ActionDispatcher for PlainActionDispatcher {}
pub struct Actions {
pub key: Option<KeyRef>,
pub dispatcher: Option<ActionDispatcherRef>,
pub actions: HashMap<TypeId, ActionRef>,
pub child: WidgetRef,
}
impl Actions {
pub fn new<K>(actions: HashMap<TypeId, ActionRef>, child: impl IntoWidget<K>) -> Actions {
Actions {
key: None,
dispatcher: None,
actions,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> Actions {
self.key = Some(key);
self
}
pub fn dispatcher(mut self, dispatcher: ActionDispatcherRef) -> Actions {
self.dispatcher = Some(dispatcher);
self
}
fn visit_actions_ancestors(
app: &mut App,
context: BuildContext,
visitor: &mut dyn FnMut(&mut App, BuildContext) -> bool,
) -> bool {
if !context.mounted(app) {
return false;
}
let mut actions_element =
context.get_element_for_inherited_widget_of_exact_type::<ActionsScope>(app);
while let Some(element) = actions_element {
if visitor(app, element) {
break;
}
actions_element = get_parent(app, element).and_then(|parent| {
parent.get_element_for_inherited_widget_of_exact_type::<ActionsScope>(app)
});
}
actions_element.is_some()
}
fn find_dispatcher(app: &mut App, context: BuildContext) -> ActionDispatcherRef {
let mut dispatcher: Option<ActionDispatcherRef> = None;
Actions::visit_actions_ancestors(app, context, &mut |app, element| {
let found = Actions::scope_of(app, element).dispatcher.clone();
match found {
Some(found) => {
dispatcher = Some(found);
true
}
None => false,
}
});
dispatcher.unwrap_or_else(|| Rc::new(PlainActionDispatcher::new()))
}
fn scope_of(app: &App, element: BuildContext) -> &ActionsScope {
crate::framework::downcast_widget::<ActionsScope>(&**element.widget(app))
.expect("the element of an _ActionsScope holds one")
}
pub fn handler(app: &mut App, context: BuildContext, intent: IntentRef) -> Option<Listener> {
let action = Actions::maybe_find(app, context, intent.intent_type())?;
if action.is_enabled(app, &*intent, Some(context)) {
let action = action.keep(app);
return Some(Listener::new(move |app| {
if action.is_enabled(app, &*intent, Some(context)) {
Actions::of(app, context).invoke_action(
app,
action.handle(),
&*intent,
Some(context),
);
}
}));
}
None
}
pub fn find(app: &mut App, context: BuildContext, intent_type: TypeId) -> AnyAction {
Actions::maybe_find(app, context, intent_type).expect(
"Unable to find an action for the given intent type in an Actions widget in the \
given context.\nActions.find() was called on a context that doesn't contain an \
Actions widget with a mapping for the given intent type.",
)
}
pub fn maybe_find(
app: &mut App,
context: BuildContext,
intent_type: TypeId,
) -> Option<AnyAction> {
let mut action: Option<AnyAction> = None;
Actions::visit_actions_ancestors(app, context, &mut |app, element| {
let result = Actions::get_action_for_intent(app, element, intent_type);
match result {
Some(result) => {
context.depend_on_inherited_element(app, element, None);
action = Some(result);
true
}
None => false,
}
});
action
}
fn maybe_find_without_depending_on(
app: &mut App,
context: BuildContext,
intent_type: TypeId,
) -> Option<AnyAction> {
let mut action: Option<AnyAction> = None;
Actions::visit_actions_ancestors(app, context, &mut |app, element| {
let result = Actions::get_action_for_intent(app, element, intent_type);
match result {
Some(result) => {
action = Some(result);
true
}
None => false,
}
});
action
}
fn get_action_for_intent(
app: &App,
element: BuildContext,
intent_type: TypeId,
) -> Option<AnyAction> {
Actions::scope_of(app, element)
.actions
.get(&intent_type)
.map(Retained::handle)
}
pub fn of(app: &mut App, context: BuildContext) -> ActionDispatcherRef {
let marker = context
.depend_on_inherited_widget_of_exact_type::<ActionsScope>(app)
.and_then(|scope| scope.dispatcher.clone());
match marker {
Some(dispatcher) => dispatcher,
None => Actions::find_dispatcher(app, context),
}
}
pub fn invoke(
app: &mut App,
context: BuildContext,
intent: &dyn Intent,
) -> Option<Rc<dyn Any>> {
let mut return_value: Option<Rc<dyn Any>> = None;
let action_found = Actions::visit_actions_ancestors(app, context, &mut |app, element| {
let result = Actions::get_action_for_intent(app, element, intent.intent_type());
if let Some(result) = result
&& result.is_enabled(app, intent, Some(context))
{
return_value = Actions::find_dispatcher(app, element).invoke_action(
app,
result,
intent,
Some(context),
);
}
result.is_some()
});
debug_assert!(
action_found,
"Unable to find an action for an Intent with type {intent:?} in an Actions widget in \
the given context."
);
return_value
}
pub fn maybe_invoke(
app: &mut App,
context: BuildContext,
intent: &dyn Intent,
) -> Option<Rc<dyn Any>> {
let mut return_value: Option<Rc<dyn Any>> = None;
Actions::visit_actions_ancestors(app, context, &mut |app, element| {
let result = Actions::get_action_for_intent(app, element, intent.intent_type());
if let Some(result) = result
&& result.is_enabled(app, intent, Some(context))
{
return_value = Actions::find_dispatcher(app, element).invoke_action(
app,
result,
intent,
Some(context),
);
}
result.is_some()
});
return_value
}
}
impl fmt::Debug for Actions {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Actions")
.field("dispatcher", &self.dispatcher)
.field("actions", &self.actions)
.finish_non_exhaustive()
}
}
impl StatefulWidget for Actions {
type State = ActionsState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> ActionsState {
ActionsState {
state: StateData::new(),
listened_actions: HashSet::new(),
action_changed: None,
rebuild_key: 0,
}
}
}
pub struct ActionsState {
state: StateData<Actions>,
listened_actions: HashSet<ActionRef>,
action_changed: Option<ActionListenerCallback>,
rebuild_key: u64,
}
impl ActionsState {
fn handle_action_changed(self: Handle<Self>, app: &mut App) {
self.set_state(app, |state| state.rebuild_key += 1);
}
fn update_action_listeners(self: Handle<Self>, app: &mut App) {
let widget_actions: HashSet<ActionRef> =
self.widget(app).actions.values().cloned().collect();
let listened = app.get(self).listened_actions.clone();
let removed_actions: Vec<AnyAction> = listened
.difference(&widget_actions)
.map(Retained::handle)
.collect();
let added_actions: Vec<AnyAction> = widget_actions
.difference(&listened)
.map(Retained::handle)
.collect();
let handler = self.action_changed(app);
for action in removed_actions {
action.remove_action_listener(app, &handler);
}
for action in added_actions {
action.add_action_listener(app, Rc::clone(&handler));
}
app.get_mut(self).listened_actions = widget_actions;
}
fn action_changed(self: Handle<Self>, app: &mut App) -> ActionListenerCallback {
if let Some(handler) = app.get(self).action_changed.clone() {
return handler;
}
let handler: ActionListenerCallback =
Rc::new(move |app: &mut App, _action: AnyAction| self.handle_action_changed(app));
app.get_mut(self).action_changed = Some(Rc::clone(&handler));
handler
}
}
impl State for ActionsState {
type Widget = Actions;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
self.update_action_listeners(app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &Actions) {
self.update_action_listeners(app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
let handler = self.action_changed(app);
for action in std::mem::take(&mut app.get_mut(self).listened_actions) {
action.remove_action_listener(app, &handler);
}
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let rebuild_key = app.get(self).rebuild_key;
let widget = self.widget(app);
ActionsScope {
dispatcher: widget.dispatcher.clone(),
actions: widget.actions.clone(),
rebuild_key,
child: widget.child.clone(),
}
.into_widget()
}
}
#[derive(Debug)]
struct ActionsScope {
dispatcher: Option<ActionDispatcherRef>,
actions: HashMap<TypeId, ActionRef>,
rebuild_key: u64,
child: WidgetRef,
}
impl InheritedWidget for ActionsScope {
fn child(&self) -> &WidgetRef {
&self.child
}
fn update_should_notify(&self, old_widget: &ActionsScope) -> bool {
self.rebuild_key != old_widget.rebuild_key
|| !same_dispatcher(&old_widget.dispatcher, &self.dispatcher)
|| old_widget.actions != self.actions
}
}
fn same_dispatcher(a: &Option<ActionDispatcherRef>, b: &Option<ActionDispatcherRef>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => Rc::ptr_eq(a, b),
_ => false,
}
}
pub struct FocusableActionDetector {
pub key: Option<KeyRef>,
pub enabled: bool,
pub focus_node: Option<FocusNodeRef>,
pub autofocus: bool,
pub descendants_are_focusable: bool,
pub descendants_are_traversable: bool,
pub actions: Option<HashMap<TypeId, ActionRef>>,
pub shortcuts: Option<ShortcutMap>,
pub on_show_focus_highlight: Option<ValueChanged<bool>>,
pub on_show_hover_highlight: Option<ValueChanged<bool>>,
pub on_focus_change: Option<ValueChanged<bool>>,
pub mouse_cursor: MouseCursorRef,
pub include_focus_semantics: bool,
pub child: WidgetRef,
}
impl FocusableActionDetector {
pub fn new<K>(child: impl IntoWidget<K>) -> FocusableActionDetector {
FocusableActionDetector {
key: None,
enabled: true,
focus_node: None,
autofocus: false,
descendants_are_focusable: true,
descendants_are_traversable: true,
actions: None,
shortcuts: None,
on_show_focus_highlight: None,
on_show_hover_highlight: None,
on_focus_change: None,
mouse_cursor: <dyn MouseCursor>::defer(),
include_focus_semantics: true,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> FocusableActionDetector {
self.key = Some(key);
self
}
pub fn enabled(mut self, enabled: bool) -> FocusableActionDetector {
self.enabled = enabled;
self
}
pub fn focus_node(mut self, focus_node: FocusNodeRef) -> FocusableActionDetector {
self.focus_node = Some(focus_node);
self
}
pub fn autofocus(mut self, autofocus: bool) -> FocusableActionDetector {
self.autofocus = autofocus;
self
}
pub fn descendants_are_focusable(
mut self,
descendants_are_focusable: bool,
) -> FocusableActionDetector {
self.descendants_are_focusable = descendants_are_focusable;
self
}
pub fn descendants_are_traversable(
mut self,
descendants_are_traversable: bool,
) -> FocusableActionDetector {
self.descendants_are_traversable = descendants_are_traversable;
self
}
pub fn actions(mut self, actions: HashMap<TypeId, ActionRef>) -> FocusableActionDetector {
self.actions = Some(actions);
self
}
pub fn shortcuts(mut self, shortcuts: ShortcutMap) -> FocusableActionDetector {
self.shortcuts = Some(shortcuts);
self
}
pub fn on_show_focus_highlight(
mut self,
on_show_focus_highlight: impl Fn(&mut App, bool) + 'static,
) -> FocusableActionDetector {
self.on_show_focus_highlight = Some(Rc::new(on_show_focus_highlight));
self
}
pub fn on_show_hover_highlight(
mut self,
on_show_hover_highlight: impl Fn(&mut App, bool) + 'static,
) -> FocusableActionDetector {
self.on_show_hover_highlight = Some(Rc::new(on_show_hover_highlight));
self
}
pub fn on_focus_change(
mut self,
on_focus_change: impl Fn(&mut App, bool) + 'static,
) -> FocusableActionDetector {
self.on_focus_change = Some(Rc::new(on_focus_change));
self
}
pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> FocusableActionDetector {
self.mouse_cursor = mouse_cursor;
self
}
pub fn include_focus_semantics(
mut self,
include_focus_semantics: bool,
) -> FocusableActionDetector {
self.include_focus_semantics = include_focus_semantics;
self
}
}
impl fmt::Debug for FocusableActionDetector {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FocusableActionDetector")
.field("enabled", &self.enabled)
.field("focusNode", &self.focus_node)
.finish_non_exhaustive()
}
}
impl StatefulWidget for FocusableActionDetector {
type State = FocusableActionDetectorState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> FocusableActionDetectorState {
FocusableActionDetectorState {
state: StateData::new(),
can_show_highlight: false,
hovering: false,
focused: false,
highlight_mode_listener: None,
mouse_region_key: GlobalKey::new(),
}
}
}
pub struct FocusableActionDetectorState {
state: StateData<FocusableActionDetector>,
can_show_highlight: bool,
hovering: bool,
focused: bool,
highlight_mode_listener: Option<HighlightModeListener>,
mouse_region_key: GlobalKey,
}
type HighlightTask<'a> = &'a dyn Fn(Handle<FocusableActionDetectorState>, &mut App);
#[derive(Clone, Copy)]
struct HighlightState {
hover: bool,
focus: bool,
}
impl FocusableActionDetectorState {
fn update_highlight_mode(self: Handle<Self>, app: &mut App, _mode: FocusHighlightMode) {
self.may_trigger_callback(
app,
None,
Some(&|this, app| {
let mode = FocusManager::instance(app).highlight_mode(app);
app.get_mut(this).can_show_highlight = match mode {
FocusHighlightMode::Touch => false,
FocusHighlightMode::Traditional => true,
};
}),
);
}
fn handle_focus_highlight_mode_change(
self: Handle<Self>,
app: &mut App,
mode: FocusHighlightMode,
) {
if !self.mounted(app) {
return;
}
self.update_highlight_mode(app, mode);
}
fn handle_mouse_enter(self: Handle<Self>, app: &mut App) {
if !app.get(self).hovering {
self.may_trigger_callback(
app,
None,
Some(&|this, app| {
app.get_mut(this).hovering = true;
}),
);
}
}
fn handle_mouse_exit(self: Handle<Self>, app: &mut App) {
if app.get(self).hovering {
self.may_trigger_callback(
app,
None,
Some(&|this, app| {
app.get_mut(this).hovering = false;
}),
);
}
}
fn handle_focus_change(self: Handle<Self>, app: &mut App, focused: bool) {
if app.get(self).focused != focused {
self.may_trigger_callback(
app,
None,
Some(&|this, app| {
app.get_mut(this).focused = focused;
}),
);
if let Some(on_focus_change) = self.widget(app).on_focus_change.clone() {
let focused = app.get(self).focused;
on_focus_change(app, focused);
}
}
}
fn should_show_hover_highlight(self: Handle<Self>, app: &App, target_enabled: bool) -> bool {
app.get(self).hovering && target_enabled && app.get(self).can_show_highlight
}
fn can_request_focus(self: Handle<Self>, app: &mut App, target_enabled: bool) -> bool {
let context = self.context(app);
match MediaQuery::maybe_navigation_mode_of(app, context) {
None | Some(NavigationMode::Traditional) => target_enabled,
Some(NavigationMode::Directional) => true,
}
}
fn should_show_focus_highlight(
self: Handle<Self>,
app: &mut App,
target_enabled: bool,
) -> bool {
app.get(self).focused
&& app.get(self).can_show_highlight
&& self.can_request_focus(app, target_enabled)
}
fn highlight_state(self: Handle<Self>, app: &mut App, target_enabled: bool) -> HighlightState {
HighlightState {
hover: self.should_show_hover_highlight(app, target_enabled),
focus: self.should_show_focus_highlight(app, target_enabled),
}
}
fn may_trigger_callback(
self: Handle<Self>,
app: &mut App,
old_enabled: Option<bool>,
task: Option<HighlightTask<'_>>,
) {
debug_assert!(
SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks
);
let old_enabled = old_enabled.unwrap_or_else(|| self.widget(app).enabled);
let did = self.highlight_state(app, old_enabled);
if let Some(task) = task {
task(self, app);
}
let enabled = self.widget(app).enabled;
let do_show = self.highlight_state(app, enabled);
if did.focus != do_show.focus
&& let Some(callback) = self.widget(app).on_show_focus_highlight.clone()
{
callback(app, do_show.focus);
}
if did.hover != do_show.hover
&& let Some(callback) = self.widget(app).on_show_hover_highlight.clone()
{
callback(app, do_show.hover);
}
}
}
impl State for FocusableActionDetectorState {
type Widget = FocusableActionDetector;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _duration| {
if !self.mounted(app) {
return;
}
let mode = FocusManager::instance(app).highlight_mode(app);
self.update_highlight_mode(app, mode);
}),
View::maybe_id_of(app, self.context(app)),
);
let listener: HighlightModeListener =
Rc::new(move |app: &mut App, mode| self.handle_focus_highlight_mode_change(app, mode));
app.get_mut(self).highlight_mode_listener = Some(Rc::clone(&listener));
FocusManager::instance(app).add_highlight_mode_listener(app, listener);
}
fn dispose(self: Handle<Self>, app: &mut App) {
if let Some(listener) = app.get_mut(self).highlight_mode_listener.take() {
FocusManager::instance(app).remove_highlight_mode_listener(app, &listener);
}
}
fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FocusableActionDetector) {
if self.widget(app).enabled != old_widget.enabled {
let old_enabled = old_widget.enabled;
SchedulerBinding::add_post_frame_callback(
app,
FrameCallback::new(move |app, _duration| {
self.may_trigger_callback(app, Some(old_enabled), None);
}),
View::maybe_id_of(app, self.context(app)),
);
}
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let can_request_focus = {
let enabled = self.widget(app).enabled;
self.can_request_focus(app, enabled)
};
let widget = self.widget(app);
let (
focus_node,
autofocus,
descendants_are_focusable,
descendants_are_traversable,
include_focus_semantics,
mouse_cursor,
child,
enabled,
) = (
widget.focus_node.clone(),
widget.autofocus,
widget.descendants_are_focusable,
widget.descendants_are_traversable,
widget.include_focus_semantics,
Rc::clone(&widget.mouse_cursor),
widget.child.clone(),
widget.enabled,
);
let mouse_region_key = app.get(self).mouse_region_key.clone();
let mut focus = Focus::new(child)
.autofocus(autofocus)
.descendants_are_focusable(descendants_are_focusable)
.descendants_are_traversable(descendants_are_traversable)
.can_request_focus(can_request_focus)
.on_focus_change(move |app, focused| self.handle_focus_change(app, focused))
.include_semantics(include_focus_semantics);
if let Some(focus_node) = focus_node {
focus = focus.focus_node(focus_node);
}
let mut child: WidgetRef = MouseRegion::new()
.key(mouse_region_key.into())
.on_enter(Rc::new(move |app, _event| self.handle_mouse_enter(app)))
.on_exit(Rc::new(move |app, _event| self.handle_mouse_exit(app)))
.cursor(mouse_cursor)
.child(focus)
.into_widget();
let actions = self.widget(app).actions.clone();
if let Some(actions) = actions.filter(|actions| enabled && !actions.is_empty()) {
child = Actions::new(actions, child).into_widget();
}
let shortcuts = self.widget(app).shortcuts.clone();
if let Some(shortcuts) = shortcuts.filter(|shortcuts| enabled && !shortcuts.is_empty()) {
child = Shortcuts::new(shortcuts, child).into_widget();
}
child
}
}
pub struct VoidCallbackIntent {
pub callback: Listener,
}
impl VoidCallbackIntent {
pub fn new(callback: Listener) -> VoidCallbackIntent {
VoidCallbackIntent { callback }
}
}
impl fmt::Debug for VoidCallbackIntent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VoidCallbackIntent").finish()
}
}
impl Intent for VoidCallbackIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
pub struct VoidCallbackAction {
action: ActionData,
}
impl VoidCallbackAction {
pub fn new(app: &mut App) -> Ref<VoidCallbackAction> {
app.create(VoidCallbackAction {
action: ActionData::new(),
})
}
}
impl Action for VoidCallbackAction {
type Intent = VoidCallbackIntent;
crate::action_accessors!();
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &VoidCallbackIntent,
) -> Option<Rc<dyn Any>> {
intent.callback.call(app);
None
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DoNothingIntent;
impl DoNothingIntent {
pub const fn new() -> DoNothingIntent {
DoNothingIntent
}
}
impl Intent for DoNothingIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DoNothingAndStopPropagationIntent;
impl DoNothingAndStopPropagationIntent {
pub const fn new() -> DoNothingAndStopPropagationIntent {
DoNothingAndStopPropagationIntent
}
}
impl Intent for DoNothingAndStopPropagationIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
pub struct DoNothingAction {
action: ActionData,
consumes_key: bool,
}
impl DoNothingAction {
pub fn new(app: &mut App) -> Ref<DoNothingAction> {
app.create(DoNothingAction {
action: ActionData::new(),
consumes_key: true,
})
}
pub fn set_consumes_key(self: Handle<Self>, app: &mut App, consumes_key: bool) {
app.get_mut(self).consumes_key = consumes_key;
}
}
impl Action for DoNothingAction {
type Intent = dyn Intent;
crate::action_accessors!();
fn consumes_key(self: Handle<Self>, app: &mut App, _intent: &dyn Intent) -> bool {
app.get(self).consumes_key
}
fn invoke(self: Handle<Self>, _app: &mut App, _intent: &dyn Intent) -> Option<Rc<dyn Any>> {
None
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ActivateIntent;
impl ActivateIntent {
pub const fn new() -> ActivateIntent {
ActivateIntent
}
}
impl Intent for ActivateIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ButtonActivateIntent;
impl ButtonActivateIntent {
pub const fn new() -> ButtonActivateIntent {
ButtonActivateIntent
}
}
impl Intent for ButtonActivateIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
pub trait ActivateAction: Action<Intent = ActivateIntent> {}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SelectIntent;
impl SelectIntent {
pub const fn new() -> SelectIntent {
SelectIntent
}
}
impl Intent for SelectIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
pub trait SelectAction: Action<Intent = SelectIntent> {}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DismissIntent;
impl DismissIntent {
pub const fn new() -> DismissIntent {
DismissIntent
}
}
impl Intent for DismissIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
pub trait DismissAction: Action<Intent = DismissIntent> {}
#[derive(Debug)]
pub struct PrioritizedIntents {
pub ordered_intents: Vec<IntentRef>,
}
impl PrioritizedIntents {
pub fn new(ordered_intents: Vec<IntentRef>) -> PrioritizedIntents {
PrioritizedIntents { ordered_intents }
}
}
impl Intent for PrioritizedIntents {
fn as_any(&self) -> &dyn Any {
self
}
}
pub struct PrioritizedAction {
action: ActionData,
selected_action: Option<ActionRef>,
selected_intent: Option<IntentRef>,
}
impl PrioritizedAction {
pub fn new(app: &mut App) -> Ref<PrioritizedAction> {
app.create(PrioritizedAction {
action: ActionData::new(),
selected_action: None,
selected_intent: None,
})
}
}
impl Action for PrioritizedAction {
type Intent = PrioritizedIntents;
crate::action_accessors!();
crate::context_action_overrides!();
}
impl ContextAction for PrioritizedAction {
fn is_enabled(
self: Handle<Self>,
app: &mut App,
intent: &PrioritizedIntents,
context: Option<BuildContext>,
) -> bool {
let Some(focus) = primary_focus(app) else {
return false;
};
let Some(focus_context) = focus.context(app) else {
return false;
};
for candidate_intent in intent.ordered_intents.iter() {
let candidate_action =
Actions::maybe_find(app, focus_context, candidate_intent.intent_type());
if let Some(candidate_action) = candidate_action
&& candidate_action.is_enabled(app, &**candidate_intent, context)
{
let candidate_action = candidate_action.keep(app);
let this = app.get_mut(self);
this.selected_action = Some(candidate_action);
this.selected_intent = Some(Rc::clone(candidate_intent));
return true;
}
}
false
}
fn invoke(
self: Handle<Self>,
app: &mut App,
_intent: &PrioritizedIntents,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let selected_action = app
.get(self)
.selected_action
.handle()
.expect("isEnabled selected an action");
let selected_intent = app
.get(self)
.selected_intent
.clone()
.expect("isEnabled selected an intent");
selected_action.invoke(app, &*selected_intent, context);
None
}
}
struct OverridableActionData {
default_action: ActionRef,
lookup_context: BuildContext,
debug_assert_mutually_recursive: bool,
debug_assert_is_action_enabled_mutually_recursive: bool,
debug_assert_is_enabled_mutually_recursive: bool,
debug_assert_consume_key_mutually_recursive: bool,
}
impl OverridableActionData {
fn new(default_action: ActionRef, lookup_context: BuildContext) -> OverridableActionData {
OverridableActionData {
default_action,
lookup_context,
debug_assert_mutually_recursive: false,
debug_assert_is_action_enabled_mutually_recursive: false,
debug_assert_is_enabled_mutually_recursive: false,
debug_assert_consume_key_mutually_recursive: false,
}
}
}
trait OverridableActionMixin: ContextAction {
fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData;
fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData;
fn invoke_default_action(
self: Handle<Self>,
app: &mut App,
intent: &Self::Intent,
from_action: Option<AnyAction>,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>>;
fn get_override_action(
self: Handle<Self>,
app: &mut App,
intent_type: TypeId,
declare_dependency: bool,
) -> Option<AnyAction> {
let lookup_context = self.overridable_data(app).lookup_context;
let override_action = if declare_dependency {
Actions::maybe_find(app, lookup_context, intent_type)
} else {
Actions::maybe_find_without_depending_on(app, lookup_context, intent_type)
};
debug_assert!(override_action != Some(Action::as_action(self)));
override_action
}
fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
self.action_data_mut(app).current_calling_action = value.clone();
let default_action = self.overridable_data(app).default_action.handle();
default_action.update_calling_action(app, value);
}
fn invoke_override(
self: Handle<Self>,
app: &mut App,
override_action: AnyAction,
intent: &Self::Intent,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
debug_assert!(!self.overridable_data(app).debug_assert_mutually_recursive);
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_mutually_recursive = true;
}
let default_action = self.overridable_data(app).default_action.clone();
override_action.update_calling_action(app, Some(default_action));
let return_value = override_action.invoke(app, intent.as_intent(), context);
override_action.update_calling_action(app, None);
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_mutually_recursive = false;
}
return_value
}
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &Self::Intent,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let intent_type = intent.as_intent().intent_type();
let override_action = self.get_override_action(app, intent_type, false);
match override_action {
None => {
let calling = self.action_data(app).current_calling_action.handle();
self.invoke_default_action(app, intent, calling, context)
}
Some(override_action) => self.invoke_override(app, override_action, intent, context),
}
}
fn is_override_action_enabled(
self: Handle<Self>,
app: &mut App,
override_action: AnyAction,
) -> bool {
debug_assert!(
!self
.overridable_data(app)
.debug_assert_is_action_enabled_mutually_recursive
);
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_is_action_enabled_mutually_recursive = true;
}
let default_action = self.overridable_data(app).default_action.clone();
override_action.update_calling_action(app, Some(default_action));
let is_override_enabled = override_action.is_action_enabled(app);
override_action.update_calling_action(app, None);
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_is_action_enabled_mutually_recursive = false;
}
is_override_enabled
}
fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
let intent_type = TypeId::of::<Self::Intent>();
let override_action = self.get_override_action(app, intent_type, true);
match override_action {
Some(override_action) => self.is_override_action_enabled(app, override_action),
None => self
.overridable_data(app)
.default_action
.is_action_enabled(app),
}
}
fn is_enabled(
self: Handle<Self>,
app: &mut App,
intent: &Self::Intent,
context: Option<BuildContext>,
) -> bool {
debug_assert!(
!self
.overridable_data(app)
.debug_assert_is_enabled_mutually_recursive
);
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_is_enabled_mutually_recursive = true;
}
let erased = intent.as_intent();
let override_action = self.get_override_action(app, erased.intent_type(), false);
let default_action = self.overridable_data(app).default_action.clone();
if let Some(override_action) = override_action {
override_action.update_calling_action(app, Some(default_action.clone()));
}
let return_value = override_action
.unwrap_or(default_action.handle())
.is_enabled(app, intent.as_intent(), context);
if let Some(override_action) = override_action {
override_action.update_calling_action(app, None);
}
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_is_enabled_mutually_recursive = false;
}
return_value
}
fn consumes_key(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
debug_assert!(
!self
.overridable_data(app)
.debug_assert_consume_key_mutually_recursive
);
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_consume_key_mutually_recursive = true;
}
let erased = intent.as_intent();
let override_action = self.get_override_action(app, erased.intent_type(), false);
let default_action = self.overridable_data(app).default_action.clone();
if let Some(override_action) = override_action {
override_action.update_calling_action(app, Some(default_action.clone()));
}
let is_enabled = override_action
.unwrap_or(default_action.handle())
.consumes_key(app, intent.as_intent());
if let Some(override_action) = override_action {
override_action.update_calling_action(app, None);
}
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_consume_key_mutually_recursive = false;
}
is_enabled
}
}
pub struct OverridableAction<T: ActionIntent + ?Sized> {
action: ActionData,
overridable: OverridableActionData,
intent: std::marker::PhantomData<fn(&T)>,
}
impl<T: ActionIntent + ?Sized> OverridableAction<T> {
pub fn new(
app: &mut App,
default_action: ActionRef,
lookup_context: BuildContext,
) -> Ref<OverridableAction<T>> {
app.create(OverridableAction::<T> {
action: ActionData::new(),
overridable: OverridableActionData::new(default_action, lookup_context),
intent: std::marker::PhantomData,
})
}
}
impl<T: ActionIntent + ?Sized> Action for OverridableAction<T> {
type Intent = T;
crate::action_accessors!();
fn as_action(self: Handle<Self>) -> AnyAction {
AnyAction::of_context::<Self>(self)
}
fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
ContextAction::is_enabled(self, app, intent, None)
}
fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
ContextAction::invoke(self, app, intent, None)
}
fn make_overridable_action(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
) -> ActionRef {
let default_action = self.overridable_data(app).default_action.clone();
OverridableAction::<T>::new(app, default_action, context).into_erased()
}
fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
OverridableActionMixin::update_calling_action(self, app, value);
}
fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
OverridableActionMixin::is_action_enabled(self, app)
}
fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
OverridableActionMixin::consumes_key(self, app, intent)
}
}
impl<T: ActionIntent + ?Sized> ContextAction for OverridableAction<T> {
fn is_enabled(
self: Handle<Self>,
app: &mut App,
intent: &T,
context: Option<BuildContext>,
) -> bool {
OverridableActionMixin::is_enabled(self, app, intent, context)
}
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &T,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
OverridableActionMixin::invoke(self, app, intent, context)
}
}
impl<T: ActionIntent + ?Sized> OverridableActionMixin for OverridableAction<T> {
fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData {
&app.get(self).overridable
}
fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData {
&mut app.get_mut(self).overridable
}
fn invoke_default_action(
self: Handle<Self>,
app: &mut App,
intent: &T,
_from_action: Option<AnyAction>,
_context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let default_action = self.overridable_data(app).default_action.handle();
default_action.invoke(app, intent.as_intent(), None)
}
}
pub struct OverridableContextAction<T: ActionIntent + ?Sized> {
action: ActionData,
overridable: OverridableActionData,
intent: std::marker::PhantomData<fn(&T)>,
}
impl<T: ActionIntent + ?Sized> OverridableContextAction<T> {
pub fn new(
app: &mut App,
default_action: ActionRef,
lookup_context: BuildContext,
) -> Ref<OverridableContextAction<T>> {
app.create(OverridableContextAction::<T> {
action: ActionData::new(),
overridable: OverridableActionData::new(default_action, lookup_context),
intent: std::marker::PhantomData,
})
}
}
impl<T: ActionIntent + ?Sized> Action for OverridableContextAction<T> {
type Intent = T;
crate::action_accessors!();
fn as_action(self: Handle<Self>) -> AnyAction {
AnyAction::of_context::<Self>(self)
}
fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
ContextAction::is_enabled(self, app, intent, None)
}
fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
ContextAction::invoke(self, app, intent, None)
}
fn make_overridable_action(
self: Handle<Self>,
app: &mut App,
context: BuildContext,
) -> ActionRef {
let default_action = self.overridable_data(app).default_action.clone();
OverridableContextAction::<T>::new(app, default_action, context).into_erased()
}
fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
OverridableActionMixin::update_calling_action(self, app, value);
}
fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
OverridableActionMixin::is_action_enabled(self, app)
}
fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
OverridableActionMixin::consumes_key(self, app, intent)
}
}
impl<T: ActionIntent + ?Sized> ContextAction for OverridableContextAction<T> {
fn is_enabled(
self: Handle<Self>,
app: &mut App,
intent: &T,
context: Option<BuildContext>,
) -> bool {
OverridableActionMixin::is_enabled(self, app, intent, context)
}
fn invoke(
self: Handle<Self>,
app: &mut App,
intent: &T,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
OverridableActionMixin::invoke(self, app, intent, context)
}
}
impl<T: ActionIntent + ?Sized> OverridableActionMixin for OverridableContextAction<T> {
fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData {
&app.get(self).overridable
}
fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData {
&mut app.get_mut(self).overridable
}
fn invoke_override(
self: Handle<Self>,
app: &mut App,
override_action: AnyAction,
intent: &T,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
debug_assert!(context.is_some());
debug_assert!(!self.overridable_data(app).debug_assert_mutually_recursive);
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_mutually_recursive = true;
}
let default_action = self.overridable_data(app).default_action.clone();
let invoke_context = context.expect("an overridable context action is invoked with one");
let wrapped_default =
ContextActionToActionAdapter::<T>::new(app, invoke_context, default_action);
override_action.update_calling_action(app, Some(wrapped_default.into_erased()));
let return_value = override_action.invoke(app, intent.as_intent(), context);
override_action.update_calling_action(app, None);
if cfg!(debug_assertions) {
self.overridable_data_mut(app)
.debug_assert_mutually_recursive = false;
}
return_value
}
fn invoke_default_action(
self: Handle<Self>,
app: &mut App,
intent: &T,
_from_action: Option<AnyAction>,
context: Option<BuildContext>,
) -> Option<Rc<dyn Any>> {
let default_action = self.overridable_data(app).default_action.handle();
default_action.invoke(app, intent.as_intent(), context)
}
}
struct ContextActionToActionAdapter<T: ActionIntent + ?Sized> {
action: ActionData,
invoke_context: BuildContext,
wrapped: ActionRef,
intent: std::marker::PhantomData<fn(&T)>,
}
impl<T: ActionIntent + ?Sized> ContextActionToActionAdapter<T> {
fn new(
app: &mut App,
invoke_context: BuildContext,
wrapped: ActionRef,
) -> Ref<ContextActionToActionAdapter<T>> {
app.create(ContextActionToActionAdapter::<T> {
action: ActionData::new(),
invoke_context,
wrapped,
intent: std::marker::PhantomData,
})
}
}
impl<T: ActionIntent + ?Sized> Action for ContextActionToActionAdapter<T> {
type Intent = T;
crate::action_accessors!();
fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
let wrapped = app.get(self).wrapped.handle();
wrapped.update_calling_action(app, value);
}
fn calling_action(self: Handle<Self>, app: &App) -> Option<AnyAction> {
app.get(self).wrapped.calling_action(app)
}
fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
let (wrapped, invoke_context) = {
let this = app.get(self);
(this.wrapped.handle(), this.invoke_context)
};
wrapped.is_enabled(app, intent.as_intent(), Some(invoke_context))
}
fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
app.get(self).wrapped.is_action_enabled(app)
}
fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
let wrapped = app.get(self).wrapped.handle();
wrapped.consumes_key(app, intent.as_intent())
}
fn add_action_listener(self: Handle<Self>, app: &mut App, listener: ActionListenerCallback) {
self.action_data_mut(app)
.listeners
.push(Rc::clone(&listener));
let wrapped = app.get(self).wrapped.handle();
wrapped.add_action_listener(app, listener);
}
fn remove_action_listener(
self: Handle<Self>,
app: &mut App,
listener: &ActionListenerCallback,
) {
let listeners = &mut self.action_data_mut(app).listeners;
if let Some(index) = listeners
.iter()
.position(|registered| Rc::ptr_eq(registered, listener))
{
listeners.remove(index);
}
let wrapped = app.get(self).wrapped.handle();
wrapped.remove_action_listener(app, listener);
}
fn notify_action_listeners(self: Handle<Self>, app: &mut App) {
app.get(self).wrapped.notify_action_listeners(app);
}
fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
let (wrapped, invoke_context) = {
let this = app.get(self);
(this.wrapped.handle(), this.invoke_context)
};
wrapped.invoke(app, intent.as_intent(), Some(invoke_context))
}
}
#[cfg(test)]
mod tests {
use std::cell::{Cell, RefCell};
use waft_embedder::Offset;
use super::*;
use crate::testing::{TestPointer, test_widgets};
use crate::widgets::basic::{Builder, SizedBox};
use crate::widgets::focus_manager::{FocusHighlightStrategy, FocusNodeLeaf};
#[derive(Debug)]
struct CountIntent {
amount: i32,
}
impl Intent for CountIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Debug)]
struct OtherIntent;
impl Intent for OtherIntent {
fn as_any(&self) -> &dyn Any {
self
}
}
struct CountAction {
action: ActionData,
log: Rc<RefCell<Vec<String>>>,
name: &'static str,
enabled: bool,
}
impl CountAction {
fn new(
app: &mut App,
log: &Rc<RefCell<Vec<String>>>,
name: &'static str,
) -> Ref<CountAction> {
app.create(CountAction {
action: ActionData::new(),
log: Rc::clone(log),
name,
enabled: true,
})
}
fn set_enabled(self: Handle<Self>, app: &mut App, enabled: bool) {
app.get_mut(self).enabled = enabled;
self.notify_action_listeners(app);
}
}
impl Action for CountAction {
type Intent = CountIntent;
crate::action_accessors!();
fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
app.get(self).enabled
}
fn invoke(self: Handle<Self>, app: &mut App, intent: &CountIntent) -> Option<Rc<dyn Any>> {
let (log, name) = {
let this = app.get(self);
(Rc::clone(&this.log), this.name)
};
log.borrow_mut().push(format!("{name}:{}", intent.amount));
Some(Rc::new(intent.amount * 2))
}
}
fn map(intent_type: TypeId, action: ActionRef) -> HashMap<TypeId, ActionRef> {
HashMap::from([(intent_type, action)])
}
fn probe(sink: &Rc<Cell<Option<BuildContext>>>) -> WidgetRef {
let sink = Rc::clone(sink);
Builder::new(move |_app, context| {
sink.set(Some(context));
SizedBox::shrink().into_widget()
})
.into_widget()
}
fn as_i32(result: Option<Rc<dyn Any>>) -> Option<i32> {
result.and_then(|value| value.downcast_ref::<i32>().copied())
}
#[test]
fn invoke_reaches_the_nearest_actions_widget_that_maps_the_intent() {
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
let log: Rc<RefCell<Vec<String>>> = Rc::default();
let outer = CountAction::new(&mut app, &log, "outer");
let inner = CountAction::new(&mut app, &log, "inner");
let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
drop(app);
tester.pump_widget(
Actions::new(
map(TypeId::of::<CountIntent>(), outer.erase()),
Actions::new(
map(TypeId::of::<CountIntent>(), inner.erase()),
probe(&captured),
),
)
.into_widget(),
);
let mut app = tester.cell.borrow_mut();
let context = captured.get().expect("the builder ran");
let result = Actions::invoke(&mut app, context, &CountIntent { amount: 2 });
assert_eq!(*log.borrow(), ["inner:2"]);
assert_eq!(as_i32(result), Some(4));
inner.set_enabled(&mut app, false);
log.borrow_mut().clear();
let result = Actions::maybe_invoke(&mut app, context, &CountIntent { amount: 3 });
assert!(log.borrow().is_empty());
assert_eq!(as_i32(result), None);
});
}
#[test]
fn invoke_walks_past_an_actions_widget_that_does_not_map_the_intent() {
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
let log: Rc<RefCell<Vec<String>>> = Rc::default();
let outer = CountAction::new(&mut app, &log, "outer");
let unrelated = DoNothingAction::new(&mut app);
let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
drop(app);
tester.pump_widget(
Actions::new(
map(TypeId::of::<CountIntent>(), outer.erase()),
Actions::new(
map(TypeId::of::<OtherIntent>(), unrelated.erase()),
probe(&captured),
),
)
.into_widget(),
);
let mut app = tester.cell.borrow_mut();
let context = captured.get().expect("the builder ran");
let result = Actions::invoke(&mut app, context, &CountIntent { amount: 5 });
assert_eq!(*log.borrow(), ["outer:5"]);
assert_eq!(as_i32(result), Some(10));
});
}
#[test]
fn maybe_find_returns_the_bound_action_and_handler_only_when_it_is_enabled() {
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
let log: Rc<RefCell<Vec<String>>> = Rc::default();
let action = CountAction::new(&mut app, &log, "action");
let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
drop(app);
tester.pump_widget(
Actions::new(
map(TypeId::of::<CountIntent>(), action.erase()),
probe(&captured),
)
.into_widget(),
);
let mut app = tester.cell.borrow_mut();
let context = captured.get().expect("the builder ran");
assert_eq!(
Actions::maybe_find(&mut app, context, TypeId::of::<CountIntent>()),
Some(Action::as_action(action.handle()))
);
assert_eq!(
Actions::maybe_find(&mut app, context, TypeId::of::<OtherIntent>()),
None
);
let intent: IntentRef = Rc::new(CountIntent { amount: 7 });
let handler = Actions::handler(&mut app, context, Rc::clone(&intent))
.expect("an enabled action has a handler");
handler.call(&mut app);
assert_eq!(*log.borrow(), ["action:7"]);
action.set_enabled(&mut app, false);
assert!(Actions::handler(&mut app, context, intent).is_none());
});
}
#[test]
fn an_overridable_action_prefers_the_override_above_its_lookup_context() {
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
let log: Rc<RefCell<Vec<String>>> = Rc::default();
let override_action = CountAction::new(&mut app, &log, "override");
let default_action = CountAction::new(&mut app, &log, "default");
let outer_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
let inner_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
let outer_sink = Rc::clone(&outer_context);
let inner_sink = Rc::clone(&inner_context);
drop(app);
tester.pump_widget(
Actions::new(
map(TypeId::of::<CountIntent>(), override_action.erase()),
Builder::new(move |_app, context| {
outer_sink.set(Some(context));
probe(&inner_sink)
}),
)
.into_widget(),
);
let mut app = tester.cell.borrow_mut();
let lookup_context = outer_context.get().expect("the builder ran");
let overridable =
AnyAction::overridable(&mut app, default_action.erase(), lookup_context);
let intent = CountIntent { amount: 1 };
overridable.invoke(&mut app, &intent, Some(lookup_context));
assert_eq!(*log.borrow(), ["override:1"]);
});
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
let log: Rc<RefCell<Vec<String>>> = Rc::default();
let default_action = CountAction::new(&mut app, &log, "default");
let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
drop(app);
tester.pump_widget(probe(&captured));
let mut app = tester.cell.borrow_mut();
let lookup_context = captured.get().expect("the builder ran");
let intent = CountIntent { amount: 1 };
let overridable =
AnyAction::overridable(&mut app, default_action.erase(), lookup_context);
overridable.invoke(&mut app, &intent, Some(lookup_context));
assert_eq!(*log.borrow(), ["default:1"]);
});
}
#[test]
fn the_detector_reports_the_focus_highlight() {
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
FocusManager::instance(&mut app)
.set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
let focus_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
let focused: Rc<RefCell<Vec<bool>>> = Rc::default();
let highlight_sink = Rc::clone(&focus_highlights);
let focus_sink = Rc::clone(&focused);
drop(app);
tester.pump_widget(
FocusableActionDetector::new(SizedBox::expand())
.autofocus(true)
.on_show_focus_highlight(move |_app, show| {
highlight_sink.borrow_mut().push(show)
})
.on_focus_change(move |_app, has_focus| focus_sink.borrow_mut().push(has_focus))
.into_widget(),
);
tester.pump();
assert_eq!(*focused.borrow(), [true]);
assert_eq!(*focus_highlights.borrow(), [true]);
});
}
#[test]
fn the_detector_reports_the_hover_highlight() {
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
FocusManager::instance(&mut app)
.set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
let hover_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
let sink = Rc::clone(&hover_highlights);
drop(app);
tester.pump_widget(
FocusableActionDetector::new(SizedBox::expand())
.on_show_hover_highlight(move |_app, show| sink.borrow_mut().push(show))
.into_widget(),
);
tester.pump();
let mut mouse = TestPointer::mouse(1, 0);
tester.move_to(&mut mouse, Offset::new(10.0, 10.0), false);
assert_eq!(*hover_highlights.borrow(), [true]);
tester.move_to(&mut mouse, Offset::new(10_000.0, 10_000.0), false);
assert_eq!(*hover_highlights.borrow(), [true, false]);
});
}
#[test]
fn a_disabled_detector_shows_no_highlight() {
test_widgets(|tester| {
let mut app = tester.cell.borrow_mut();
FocusManager::instance(&mut app)
.set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
let focus_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
let sink = Rc::clone(&focus_highlights);
let node = crate::FocusNode::new(&mut app);
let detector = |enabled: bool, sink: Rc<RefCell<Vec<bool>>>| {
FocusableActionDetector::new(SizedBox::expand())
.enabled(enabled)
.focus_node(node.erase())
.autofocus(true)
.on_show_focus_highlight(move |_app, show| sink.borrow_mut().push(show))
.into_widget()
};
drop(app);
tester.pump_widget(detector(false, Rc::clone(&sink)));
tester.pump();
let mut app = tester.cell.borrow_mut();
node.request_focus(&mut app, None);
app.drain_microtasks();
assert!(!node.has_primary_focus(&app));
assert!(focus_highlights.borrow().is_empty());
drop(app);
tester.pump_widget(detector(true, Rc::clone(&sink)));
tester.pump();
let mut app = tester.cell.borrow_mut();
node.request_focus(&mut app, None);
app.drain_microtasks();
assert!(node.has_primary_focus(&app));
assert_eq!(*focus_highlights.borrow(), [true]);
});
}
}