1use std::any::{Any, TypeId};
9use std::collections::{HashMap, HashSet};
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12
13use waft_foundation::{
14 App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, HandleId, Listener,
15 OptionRetained, Ref, Retained, ValueChanged, describe_identity,
16};
17use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
18use waft_services::{MouseCursor, MouseCursorRef};
19
20use crate::framework::{
21 BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
22 WidgetRef,
23};
24use crate::view::View;
25use crate::widgets::basic::MouseRegion;
26use crate::widgets::focus_manager::{
27 FocusHighlightMode, FocusManager, FocusNodeRef, HighlightModeListener, KeyEventResult,
28 primary_focus,
29};
30use crate::widgets::focus_scope::Focus;
31use crate::widgets::media_query::{MediaQuery, NavigationMode};
32use crate::widgets::shortcuts::{ShortcutMap, Shortcuts};
33
34fn get_parent(app: &App, context: BuildContext) -> Option<BuildContext> {
46 let mut parent = None;
47 context.visit_ancestor_elements(app, &mut |ancestor| {
48 parent = Some(ancestor);
49 false
50 });
51 parent
52}
53
54pub trait Intent: Debug + 'static {
70 fn as_any(&self) -> &dyn Any;
73
74 fn intent_type(&self) -> TypeId {
76 self.as_any().type_id()
77 }
78
79 fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
82 let _ = properties;
83 }
84
85 fn to_string_short(&self) -> String {
87 describe_identity(
88 waft_foundation::bare_type_name(std::any::type_name::<Self>()),
89 self as *const Self as *const () as usize as u64,
90 )
91 }
92
93 fn diagnostics_node(&self, name: Option<String>) -> waft_foundation::DiagnosticableNode {
95 let mut builder = DiagnosticPropertiesBuilder::new();
96 self.debug_fill_properties(&mut builder);
97 waft_foundation::DiagnosticableNode::from_parts(name, self.to_string_short(), builder)
98 }
99
100 fn diagnostic_string(&self) -> String {
102 use waft_foundation::{DiagnosticLevel, DiagnosticsNode, DiagnosticsTreeStyle};
103 self.diagnostics_node(None)
104 .with_style(DiagnosticsTreeStyle::SingleLine)
105 .to_string_with(None, DiagnosticLevel::Info)
106 }
107}
108
109pub type IntentRef = Rc<dyn Intent>;
111
112pub const DO_NOTHING: DoNothingIntent = DoNothingIntent::new();
121
122pub trait ActionIntent: 'static {
127 fn cast_intent(intent: &dyn Intent) -> Option<&Self>;
129
130 fn as_intent(&self) -> &dyn Intent;
132}
133
134impl<T: Intent> ActionIntent for T {
135 fn cast_intent(intent: &dyn Intent) -> Option<&T> {
136 intent.as_any().downcast_ref::<T>()
137 }
138
139 fn as_intent(&self) -> &dyn Intent {
140 self
141 }
142}
143
144impl ActionIntent for dyn Intent {
145 fn cast_intent(intent: &dyn Intent) -> Option<&dyn Intent> {
146 Some(intent)
147 }
148
149 fn as_intent(&self) -> &dyn Intent {
150 self
151 }
152}
153
154pub type ActionListenerCallback = Rc<dyn Fn(&mut App, AnyAction)>;
161
162pub struct ActionData {
165 listeners: Vec<ActionListenerCallback>,
166 current_calling_action: Option<ActionRef>,
167}
168
169impl ActionData {
170 pub fn new() -> ActionData {
172 ActionData {
173 listeners: Vec::new(),
174 current_calling_action: None,
175 }
176 }
177}
178
179impl Default for ActionData {
180 fn default() -> ActionData {
181 ActionData::new()
182 }
183}
184
185#[macro_export]
187macro_rules! action_accessors {
188 () => {
189 fn action_data(
190 self: ::waft_foundation::Handle<Self>,
191 app: &::waft_foundation::App,
192 ) -> &$crate::ActionData {
193 &app.get(self).action
194 }
195
196 fn action_data_mut(
197 self: ::waft_foundation::Handle<Self>,
198 app: &mut ::waft_foundation::App,
199 ) -> &mut $crate::ActionData {
200 &mut app.get_mut(self).action
201 }
202 };
203}
204
205#[macro_export]
209macro_rules! context_action_overrides {
210 () => {
211 fn as_action(self: ::waft_foundation::Handle<Self>) -> $crate::AnyAction {
212 $crate::AnyAction::of_context::<Self>(self)
213 }
214
215 fn is_enabled(
216 self: ::waft_foundation::Handle<Self>,
217 app: &mut ::waft_foundation::App,
218 intent: &Self::Intent,
219 ) -> bool {
220 $crate::ContextAction::is_enabled(self, app, intent, None)
221 }
222
223 fn invoke(
224 self: ::waft_foundation::Handle<Self>,
225 app: &mut ::waft_foundation::App,
226 intent: &Self::Intent,
227 ) -> Option<::std::rc::Rc<dyn ::std::any::Any>> {
228 $crate::ContextAction::invoke(self, app, intent, None)
229 }
230
231 fn make_overridable_action(
232 self: ::waft_foundation::Handle<Self>,
233 app: &mut ::waft_foundation::App,
234 context: $crate::BuildContext,
235 ) -> $crate::ActionRef {
236 let default_action: $crate::ActionRef = self.keep(app).into_erased();
237 $crate::OverridableContextAction::<Self::Intent>::new(app, default_action, context)
238 .into_erased()
239 }
240 };
241}
242
243pub trait Action: Sized + 'static {
274 type Intent: ActionIntent + ?Sized;
278
279 fn action_data(self: Handle<Self>, app: &App) -> &ActionData;
282
283 fn action_data_mut(self: Handle<Self>, app: &mut App) -> &mut ActionData;
285
286 fn debug_fill_properties(
289 self: Handle<Self>,
290 app: &App,
291 properties: &mut DiagnosticPropertiesBuilder,
292 ) {
293 let _ = (self, app, properties);
294 }
295
296 fn as_action(self: Handle<Self>) -> AnyAction {
303 AnyAction::of::<Self>(self)
304 }
305
306 fn intent_type() -> TypeId {
308 TypeId::of::<Self::Intent>()
309 }
310
311 fn calling_action(self: Handle<Self>, app: &App) -> Option<AnyAction> {
331 self.action_data(app).current_calling_action.handle()
332 }
333
334 fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
337 self.action_data_mut(app).current_calling_action = value;
338 }
339
340 fn is_enabled(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
347 let _ = intent;
348 self.is_action_enabled(app)
349 }
350
351 fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
363 let _ = app;
364 true
365 }
366
367 fn consumes_key(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
379 let _ = (app, intent);
380 true
381 }
382
383 fn to_key_event_result(
393 self: Handle<Self>,
394 app: &mut App,
395 intent: &Self::Intent,
396 invoke_result: Option<&Rc<dyn Any>>,
397 ) -> KeyEventResult {
398 let _ = invoke_result;
399 if self.consumes_key(app, intent) {
400 KeyEventResult::Handled
401 } else {
402 KeyEventResult::SkipRemainingHandlers
403 }
404 }
405
406 fn invoke(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> Option<Rc<dyn Any>>;
422
423 fn add_action_listener(self: Handle<Self>, app: &mut App, listener: ActionListenerCallback) {
431 self.action_data_mut(app).listeners.push(listener);
432 }
433
434 fn remove_action_listener(
439 self: Handle<Self>,
440 app: &mut App,
441 listener: &ActionListenerCallback,
442 ) {
443 let listeners = &mut self.action_data_mut(app).listeners;
444 if let Some(index) = listeners
445 .iter()
446 .position(|registered| Rc::ptr_eq(registered, listener))
447 {
448 listeners.remove(index);
449 }
450 }
451
452 fn notify_action_listeners(self: Handle<Self>, app: &mut App) {
459 if self.action_data(app).listeners.is_empty() {
460 return;
461 }
462 let local_listeners = self.action_data(app).listeners.clone();
465 let this = self.as_action();
466 for listener in local_listeners {
467 let still_registered = self
468 .action_data(app)
469 .listeners
470 .iter()
471 .any(|registered| Rc::ptr_eq(registered, &listener));
472 if still_registered {
473 listener(app, this);
474 }
475 }
476 }
477
478 fn make_overridable_action(
481 self: Handle<Self>,
482 app: &mut App,
483 context: BuildContext,
484 ) -> ActionRef {
485 let default_action: ActionRef = self.keep(app).into_erased();
486 OverridableAction::<Self::Intent>::new(app, default_action, context).into_erased()
487 }
488}
489
490pub trait ContextAction: Action {
499 fn is_enabled(
507 self: Handle<Self>,
508 app: &mut App,
509 intent: &Self::Intent,
510 context: Option<BuildContext>,
511 ) -> bool {
512 let _ = (intent, context);
513 Action::is_action_enabled(self, app)
514 }
515
516 fn invoke(
529 self: Handle<Self>,
530 app: &mut App,
531 intent: &Self::Intent,
532 context: Option<BuildContext>,
533 ) -> Option<Rc<dyn Any>>;
534}
535
536type ToKeyEventResultFn =
538 fn(&mut App, HandleId, &dyn Intent, Option<&Rc<dyn Any>>) -> KeyEventResult;
539
540type InvokeFn = fn(&mut App, HandleId, &dyn Intent, Option<BuildContext>) -> Option<Rc<dyn Any>>;
542
543struct ActionVTable {
546 type_name: fn() -> &'static str,
547 intent_type: fn() -> TypeId,
548 calling_action: fn(&App, HandleId) -> Option<AnyAction>,
549 update_calling_action: fn(&mut App, HandleId, Option<ActionRef>),
550 is_enabled: fn(&mut App, HandleId, &dyn Intent, Option<BuildContext>) -> bool,
551 is_action_enabled: fn(&mut App, HandleId) -> bool,
552 consumes_key: fn(&mut App, HandleId, &dyn Intent) -> bool,
553 to_key_event_result: ToKeyEventResultFn,
554 invoke: InvokeFn,
555 add_action_listener: fn(&mut App, HandleId, ActionListenerCallback),
556 remove_action_listener: fn(&mut App, HandleId, &ActionListenerCallback),
557 notify_action_listeners: fn(&mut App, HandleId),
558 make_overridable_action: fn(&mut App, HandleId, BuildContext) -> ActionRef,
559 debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
560}
561
562fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
564 Handle::from_id(id)
565}
566
567fn cast_intent<L: Action>(intent: &dyn Intent) -> &L::Intent {
569 <L::Intent as ActionIntent>::cast_intent(intent).unwrap_or_else(|| {
570 panic!(
571 "An Intent of type {:?} cannot be handled by {}: the Intent must be of a subtype \
572 of {}.",
573 intent,
574 std::any::type_name::<L>(),
575 std::any::type_name::<L::Intent>()
576 )
577 })
578}
579
580impl ActionVTable {
581 const fn of<L: Action>() -> ActionVTable {
584 ActionVTable {
585 type_name: std::any::type_name::<L>,
586 intent_type: L::intent_type,
587 calling_action: |app, id| L::calling_action(resolve(id), app),
588 update_calling_action: |app, id, value| {
589 L::update_calling_action(resolve(id), app, value)
590 },
591 is_enabled: |app, id, intent, _context| {
592 L::is_enabled(resolve(id), app, cast_intent::<L>(intent))
593 },
594 is_action_enabled: |app, id| L::is_action_enabled(resolve(id), app),
595 consumes_key: |app, id, intent| {
596 L::consumes_key(resolve(id), app, cast_intent::<L>(intent))
597 },
598 to_key_event_result: |app, id, intent, invoke_result| {
599 L::to_key_event_result(resolve(id), app, cast_intent::<L>(intent), invoke_result)
600 },
601 invoke: |app, id, intent, _context| {
602 L::invoke(resolve(id), app, cast_intent::<L>(intent))
603 },
604 add_action_listener: |app, id, listener| {
605 L::add_action_listener(resolve(id), app, listener)
606 },
607 remove_action_listener: |app, id, listener| {
608 L::remove_action_listener(resolve(id), app, listener)
609 },
610 notify_action_listeners: |app, id| L::notify_action_listeners(resolve(id), app),
611 make_overridable_action: |app, id, context| {
612 L::make_overridable_action(resolve(id), app, context)
613 },
614 debug_fill_properties: |app, id, properties| {
615 L::debug_fill_properties(resolve(id), app, properties)
616 },
617 }
618 }
619
620 const fn of_context<L: ContextAction>() -> ActionVTable {
623 ActionVTable {
624 is_enabled: |app, id, intent, context| {
625 ContextAction::is_enabled(resolve::<L>(id), app, cast_intent::<L>(intent), context)
626 },
627 invoke: |app, id, intent, context| {
628 ContextAction::invoke(resolve::<L>(id), app, cast_intent::<L>(intent), context)
629 },
630 ..ActionVTable::of::<L>()
631 }
632 }
633}
634
635#[derive(Clone, Copy)]
644pub struct AnyAction {
645 id: HandleId,
646 vtable: &'static ActionVTable,
647}
648
649pub type ActionRef = Retained<AnyAction>;
651
652waft_foundation::erased_handle!(AnyAction: Action => Action::as_action);
653
654impl fmt::Debug for AnyAction {
655 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656 write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
657 }
658}
659
660impl AnyAction {
661 pub fn to_string_short(self) -> String {
663 describe_identity(
664 waft_foundation::bare_type_name((self.vtable.type_name)()),
665 self.id.identity_hash(),
666 )
667 }
668
669 pub fn debug_fill_properties(self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
671 (self.vtable.debug_fill_properties)(app, self.id, properties);
672 }
673
674 pub fn of<L: Action>(action: Handle<L>) -> AnyAction {
676 AnyAction {
677 id: action.id(),
678 vtable: const { &ActionVTable::of::<L>() },
679 }
680 }
681
682 pub fn of_context<L: ContextAction>(action: Handle<L>) -> AnyAction {
685 AnyAction {
686 id: action.id(),
687 vtable: const { &ActionVTable::of_context::<L>() },
688 }
689 }
690
691 pub fn overridable(
714 app: &mut App,
715 default_action: ActionRef,
716 context: BuildContext,
717 ) -> ActionRef {
718 default_action.make_overridable_action(app, context)
719 }
720
721 pub fn id(self) -> HandleId {
723 self.id
724 }
725
726 pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
728 app.handle::<T>(self.id)
729 }
730
731 pub fn intent_type(self) -> TypeId {
733 (self.vtable.intent_type)()
734 }
735
736 pub fn calling_action(self, app: &App) -> Option<AnyAction> {
738 (self.vtable.calling_action)(app, self.id)
739 }
740
741 pub fn update_calling_action(self, app: &mut App, value: Option<ActionRef>) {
743 (self.vtable.update_calling_action)(app, self.id, value);
744 }
745
746 pub fn is_enabled(
749 self,
750 app: &mut App,
751 intent: &dyn Intent,
752 context: Option<BuildContext>,
753 ) -> bool {
754 (self.vtable.is_enabled)(app, self.id, intent, context)
755 }
756
757 pub fn is_action_enabled(self, app: &mut App) -> bool {
759 (self.vtable.is_action_enabled)(app, self.id)
760 }
761
762 pub fn consumes_key(self, app: &mut App, intent: &dyn Intent) -> bool {
764 (self.vtable.consumes_key)(app, self.id, intent)
765 }
766
767 pub fn to_key_event_result(
769 self,
770 app: &mut App,
771 intent: &dyn Intent,
772 invoke_result: Option<&Rc<dyn Any>>,
773 ) -> KeyEventResult {
774 (self.vtable.to_key_event_result)(app, self.id, intent, invoke_result)
775 }
776
777 pub fn invoke(
780 self,
781 app: &mut App,
782 intent: &dyn Intent,
783 context: Option<BuildContext>,
784 ) -> Option<Rc<dyn Any>> {
785 (self.vtable.invoke)(app, self.id, intent, context)
786 }
787
788 pub fn add_action_listener(self, app: &mut App, listener: ActionListenerCallback) {
790 (self.vtable.add_action_listener)(app, self.id, listener);
791 }
792
793 pub fn remove_action_listener(self, app: &mut App, listener: &ActionListenerCallback) {
795 (self.vtable.remove_action_listener)(app, self.id, listener);
796 }
797
798 pub fn notify_action_listeners(self, app: &mut App) {
800 (self.vtable.notify_action_listeners)(app, self.id);
801 }
802
803 fn make_overridable_action(self, app: &mut App, context: BuildContext) -> ActionRef {
805 (self.vtable.make_overridable_action)(app, self.id, context)
806 }
807}
808
809pub struct ActionListener {
825 pub key: Option<KeyRef>,
827
828 pub listener: ActionListenerCallback,
830
831 pub action: ActionRef,
833
834 pub child: WidgetRef,
836}
837
838impl ActionListener {
839 #[cfg_attr(debug_assertions, track_caller)]
841 pub fn new<K>(
842 listener: ActionListenerCallback,
843 action: ActionRef,
844 child: impl IntoWidget<K>,
845 ) -> ActionListener {
846 ActionListener {
847 key: None,
848 listener,
849 action,
850 child: child.into_widget(),
851 }
852 }
853
854 pub fn key(mut self, key: KeyRef) -> ActionListener {
856 self.key = Some(key);
857 self
858 }
859}
860
861impl fmt::Debug for ActionListener {
862 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
863 f.debug_struct("ActionListener")
864 .field("action", &self.action)
865 .finish_non_exhaustive()
866 }
867}
868
869impl StatefulWidget for ActionListener {
870 type State = ActionListenerState;
871
872 fn key(&self) -> Option<&KeyRef> {
873 self.key.as_ref()
874 }
875
876 fn create_state(&self) -> ActionListenerState {
877 ActionListenerState {
878 state: StateData::new(),
879 }
880 }
881}
882
883pub struct ActionListenerState {
885 state: StateData<ActionListener>,
886}
887
888impl State for ActionListenerState {
889 type Widget = ActionListener;
890 crate::state_accessors!();
891
892 fn init_state(self: Handle<Self>, app: &mut App) {
893 let widget = self.widget(app);
894 let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
895 action.add_action_listener(app, listener);
896 }
897
898 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ActionListener) {
899 let widget = self.widget(app);
900 let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
901 if old_widget.action == action && Rc::ptr_eq(&old_widget.listener, &listener) {
902 return;
903 }
904 let (old_action, old_listener) =
905 (old_widget.action.handle(), Rc::clone(&old_widget.listener));
906 old_action.remove_action_listener(app, &old_listener);
907 action.add_action_listener(app, listener);
908 }
909
910 fn dispose(self: Handle<Self>, app: &mut App) {
911 let widget = self.widget(app);
912 let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
913 action.remove_action_listener(app, &listener);
914 }
915
916 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
917 self.widget(app).child.clone()
918 }
919}
920
921pub type OnInvokeCallback<T> = Rc<dyn Fn(&mut App, &T) -> Option<Rc<dyn Any>>>;
930
931pub struct CallbackAction<T: Intent> {
943 action: ActionData,
944
945 on_invoke: OnInvokeCallback<T>,
949}
950
951impl<T: Intent> CallbackAction<T> {
952 pub fn new(app: &mut App, on_invoke: OnInvokeCallback<T>) -> Ref<CallbackAction<T>> {
956 app.create(CallbackAction {
957 action: ActionData::new(),
958 on_invoke,
959 })
960 }
961}
962
963impl<T: Intent> Action for CallbackAction<T> {
964 type Intent = T;
965 crate::action_accessors!();
966
967 fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
968 let on_invoke = Rc::clone(&app.get(self).on_invoke);
969 on_invoke(app, intent)
970 }
971}
972
973pub type ActionDispatcherRef = Rc<dyn ActionDispatcher>;
978
979pub trait ActionDispatcher: Debug {
995 fn to_string_short(&self) -> String {
998 describe_identity(
999 waft_foundation::bare_type_name(std::any::type_name::<Self>()),
1000 self as *const Self as *const () as usize as u64,
1001 )
1002 }
1003
1004 fn invoke_action(
1019 &self,
1020 app: &mut App,
1021 action: AnyAction,
1022 intent: &dyn Intent,
1023 context: Option<BuildContext>,
1024 ) -> Option<Rc<dyn Any>> {
1025 let target = context.or_else(|| primary_focus(app).and_then(|node| node.context(app)));
1026 debug_assert!(
1027 action.is_enabled(app, intent, target),
1028 "Action must be enabled when calling invokeAction"
1029 );
1030 action.invoke(app, intent, target)
1031 }
1032
1033 fn invoke_action_if_enabled(
1048 &self,
1049 app: &mut App,
1050 action: AnyAction,
1051 intent: &dyn Intent,
1052 context: Option<BuildContext>,
1053 ) -> (bool, Option<Rc<dyn Any>>) {
1054 let target = context.or_else(|| primary_focus(app).and_then(|node| node.context(app)));
1055 if action.is_enabled(app, intent, target) {
1056 return (true, action.invoke(app, intent, target));
1057 }
1058 (false, None)
1059 }
1060}
1061
1062#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
1065pub struct PlainActionDispatcher;
1066
1067impl PlainActionDispatcher {
1068 pub fn new() -> PlainActionDispatcher {
1070 PlainActionDispatcher
1071 }
1072}
1073
1074impl ActionDispatcher for PlainActionDispatcher {
1075 fn to_string_short(&self) -> String {
1078 describe_identity(
1079 "ActionDispatcher",
1080 self as *const Self as *const () as usize as u64,
1081 )
1082 }
1083}
1084
1085pub struct Actions {
1102 pub key: Option<KeyRef>,
1104
1105 pub dispatcher: Option<ActionDispatcherRef>,
1114
1115 pub actions: HashMap<TypeId, ActionRef>,
1121
1122 pub child: WidgetRef,
1124}
1125
1126impl Actions {
1127 #[cfg_attr(debug_assertions, track_caller)]
1129 pub fn new<K>(actions: HashMap<TypeId, ActionRef>, child: impl IntoWidget<K>) -> Actions {
1130 Actions {
1131 key: None,
1132 dispatcher: None,
1133 actions,
1134 child: child.into_widget(),
1135 }
1136 }
1137
1138 pub fn key(mut self, key: KeyRef) -> Actions {
1140 self.key = Some(key);
1141 self
1142 }
1143
1144 pub fn dispatcher(mut self, dispatcher: ActionDispatcherRef) -> Actions {
1146 self.dispatcher = Some(dispatcher);
1147 self
1148 }
1149
1150 fn visit_actions_ancestors(
1153 app: &mut App,
1154 context: BuildContext,
1155 visitor: &mut dyn FnMut(&mut App, BuildContext) -> bool,
1156 ) -> bool {
1157 if !context.mounted(app) {
1158 return false;
1159 }
1160 let mut actions_element =
1161 context.get_element_for_inherited_widget_of_exact_type::<ActionsScope>(app);
1162 while let Some(element) = actions_element {
1163 if visitor(app, element) {
1164 break;
1165 }
1166 actions_element = get_parent(app, element).and_then(|parent| {
1170 parent.get_element_for_inherited_widget_of_exact_type::<ActionsScope>(app)
1171 });
1172 }
1173 actions_element.is_some()
1174 }
1175
1176 fn find_dispatcher(app: &mut App, context: BuildContext) -> ActionDispatcherRef {
1179 let mut dispatcher: Option<ActionDispatcherRef> = None;
1180 Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1181 let found = Actions::scope_of(app, element).dispatcher.clone();
1182 match found {
1183 Some(found) => {
1184 dispatcher = Some(found);
1185 true
1186 }
1187 None => false,
1188 }
1189 });
1190 dispatcher.unwrap_or_else(|| Rc::new(PlainActionDispatcher::new()))
1191 }
1192
1193 fn scope_of(app: &App, element: BuildContext) -> &ActionsScope {
1196 crate::framework::downcast_widget::<ActionsScope>(&**element.widget(app))
1197 .expect("the element of an _ActionsScope holds one")
1198 }
1199
1200 pub fn handler(app: &mut App, context: BuildContext, intent: IntentRef) -> Option<Listener> {
1214 let action = Actions::maybe_find(app, context, intent.intent_type())?;
1215 if action.is_enabled(app, &*intent, Some(context)) {
1216 let action = action.keep(app);
1217 return Some(Listener::new(move |app| {
1218 if action.is_enabled(app, &*intent, Some(context)) {
1221 Actions::of(app, context).invoke_action(
1222 app,
1223 action.handle(),
1224 &*intent,
1225 Some(context),
1226 );
1227 }
1228 }));
1229 }
1230 None
1231 }
1232
1233 pub fn find(app: &mut App, context: BuildContext, intent_type: TypeId) -> AnyAction {
1246 Actions::maybe_find(app, context, intent_type).expect(
1247 "Unable to find an action for the given intent type in an Actions widget in the \
1248 given context.\nActions.find() was called on a context that doesn't contain an \
1249 Actions widget with a mapping for the given intent type.",
1250 )
1251 }
1252
1253 pub fn maybe_find(
1265 app: &mut App,
1266 context: BuildContext,
1267 intent_type: TypeId,
1268 ) -> Option<AnyAction> {
1269 let mut action: Option<AnyAction> = None;
1270 Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1271 let result = Actions::get_action_for_intent(app, element, intent_type);
1272 match result {
1273 Some(result) => {
1274 context.depend_on_inherited_element(app, element, None);
1275 action = Some(result);
1276 true
1277 }
1278 None => false,
1279 }
1280 });
1281 action
1282 }
1283
1284 fn maybe_find_without_depending_on(
1286 app: &mut App,
1287 context: BuildContext,
1288 intent_type: TypeId,
1289 ) -> Option<AnyAction> {
1290 let mut action: Option<AnyAction> = None;
1291 Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1292 let result = Actions::get_action_for_intent(app, element, intent_type);
1293 match result {
1294 Some(result) => {
1295 action = Some(result);
1296 true
1297 }
1298 None => false,
1299 }
1300 });
1301 action
1302 }
1303
1304 fn get_action_for_intent(
1306 app: &App,
1307 element: BuildContext,
1308 intent_type: TypeId,
1309 ) -> Option<AnyAction> {
1310 Actions::scope_of(app, element)
1311 .actions
1312 .get(&intent_type)
1313 .map(Retained::handle)
1314 }
1315
1316 pub fn of(app: &mut App, context: BuildContext) -> ActionDispatcherRef {
1322 let marker = context
1323 .depend_on_inherited_widget_of_exact_type::<ActionsScope>(app)
1324 .and_then(|scope| scope.dispatcher.clone());
1325 match marker {
1326 Some(dispatcher) => dispatcher,
1327 None => Actions::find_dispatcher(app, context),
1328 }
1329 }
1330
1331 pub fn invoke(
1341 app: &mut App,
1342 context: BuildContext,
1343 intent: &dyn Intent,
1344 ) -> Option<Rc<dyn Any>> {
1345 let mut return_value: Option<Rc<dyn Any>> = None;
1346 let action_found = Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1347 let result = Actions::get_action_for_intent(app, element, intent.intent_type());
1348 if let Some(result) = result
1349 && result.is_enabled(app, intent, Some(context))
1350 {
1351 return_value = Actions::find_dispatcher(app, element).invoke_action(
1354 app,
1355 result,
1356 intent,
1357 Some(context),
1358 );
1359 }
1360 result.is_some()
1361 });
1362 debug_assert!(
1363 action_found,
1364 "Unable to find an action for an Intent with type {intent:?} in an Actions widget in \
1365 the given context."
1366 );
1367 return_value
1368 }
1369
1370 pub fn maybe_invoke(
1383 app: &mut App,
1384 context: BuildContext,
1385 intent: &dyn Intent,
1386 ) -> Option<Rc<dyn Any>> {
1387 let mut return_value: Option<Rc<dyn Any>> = None;
1388 Actions::visit_actions_ancestors(app, context, &mut |app, element| {
1389 let result = Actions::get_action_for_intent(app, element, intent.intent_type());
1390 if let Some(result) = result
1391 && result.is_enabled(app, intent, Some(context))
1392 {
1393 return_value = Actions::find_dispatcher(app, element).invoke_action(
1394 app,
1395 result,
1396 intent,
1397 Some(context),
1398 );
1399 }
1400 result.is_some()
1401 });
1402 return_value
1403 }
1404}
1405
1406impl fmt::Debug for Actions {
1407 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1408 f.debug_struct("Actions")
1409 .field("dispatcher", &self.dispatcher)
1410 .field("actions", &self.actions)
1411 .finish_non_exhaustive()
1412 }
1413}
1414
1415impl StatefulWidget for Actions {
1416 type State = ActionsState;
1417
1418 fn key(&self) -> Option<&KeyRef> {
1419 self.key.as_ref()
1420 }
1421
1422 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1423 properties.add(DiagnosticsProperty::<String>::new(
1424 "dispatcher",
1425 self.dispatcher
1426 .as_ref()
1427 .map(|dispatcher| dispatcher.to_string_short()),
1428 ));
1429 let mut entries: Vec<(String, String)> = self
1430 .actions
1431 .iter()
1432 .map(|(intent_type, action)| (format!("{intent_type:?}"), action.to_string_short()))
1433 .collect();
1434 entries.sort();
1435 let actions = entries
1436 .into_iter()
1437 .map(|(intent_type, action)| format!("{intent_type}: {action}"))
1438 .collect::<Vec<_>>()
1439 .join(", ");
1440 properties.add(DiagnosticsProperty::<String>::new(
1441 "actions",
1442 Some(format!("{{{actions}}}")),
1443 ));
1444 }
1445
1446 fn create_state(&self) -> ActionsState {
1447 ActionsState {
1448 state: StateData::new(),
1449 listened_actions: HashSet::new(),
1450 action_changed: None,
1451 rebuild_key: 0,
1452 }
1453 }
1454}
1455
1456pub struct ActionsState {
1458 state: StateData<Actions>,
1459 listened_actions: HashSet<ActionRef>,
1461 action_changed: Option<ActionListenerCallback>,
1463 rebuild_key: u64,
1466}
1467
1468impl ActionsState {
1469 fn handle_action_changed(self: Handle<Self>, app: &mut App) {
1470 self.set_state(app, |state| state.rebuild_key += 1);
1472 }
1473
1474 fn update_action_listeners(self: Handle<Self>, app: &mut App) {
1475 let widget_actions: HashSet<ActionRef> =
1476 self.widget(app).actions.values().cloned().collect();
1477 let listened = app.get(self).listened_actions.clone();
1478 let removed_actions: Vec<AnyAction> = listened
1479 .difference(&widget_actions)
1480 .map(Retained::handle)
1481 .collect();
1482 let added_actions: Vec<AnyAction> = widget_actions
1483 .difference(&listened)
1484 .map(Retained::handle)
1485 .collect();
1486
1487 let handler = self.action_changed(app);
1488 for action in removed_actions {
1489 action.remove_action_listener(app, &handler);
1490 }
1491 for action in added_actions {
1492 action.add_action_listener(app, Rc::clone(&handler));
1493 }
1494 app.get_mut(self).listened_actions = widget_actions;
1495 }
1496
1497 fn action_changed(self: Handle<Self>, app: &mut App) -> ActionListenerCallback {
1500 if let Some(handler) = app.get(self).action_changed.clone() {
1501 return handler;
1502 }
1503 let handler: ActionListenerCallback =
1504 Rc::new(move |app: &mut App, _action: AnyAction| self.handle_action_changed(app));
1505 app.get_mut(self).action_changed = Some(Rc::clone(&handler));
1506 handler
1507 }
1508}
1509
1510impl State for ActionsState {
1511 type Widget = Actions;
1512 crate::state_accessors!();
1513
1514 fn init_state(self: Handle<Self>, app: &mut App) {
1515 self.update_action_listeners(app);
1516 }
1517
1518 fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &Actions) {
1519 self.update_action_listeners(app);
1520 }
1521
1522 fn dispose(self: Handle<Self>, app: &mut App) {
1523 let handler = self.action_changed(app);
1524 for action in std::mem::take(&mut app.get_mut(self).listened_actions) {
1525 action.remove_action_listener(app, &handler);
1526 }
1527 }
1528
1529 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1530 let rebuild_key = app.get(self).rebuild_key;
1531 let widget = self.widget(app);
1532 ActionsScope {
1533 dispatcher: widget.dispatcher.clone(),
1534 actions: widget.actions.clone(),
1535 rebuild_key,
1536 child: widget.child.clone(),
1537 }
1538 .into_widget()
1539 }
1540}
1541
1542#[derive(Debug)]
1545struct ActionsScope {
1546 dispatcher: Option<ActionDispatcherRef>,
1547 actions: HashMap<TypeId, ActionRef>,
1548 rebuild_key: u64,
1549 child: WidgetRef,
1550}
1551
1552impl InheritedWidget for ActionsScope {
1553 fn child(&self) -> &WidgetRef {
1554 &self.child
1555 }
1556
1557 fn update_should_notify(&self, old_widget: &ActionsScope) -> bool {
1558 self.rebuild_key != old_widget.rebuild_key
1559 || !same_dispatcher(&old_widget.dispatcher, &self.dispatcher)
1560 || old_widget.actions != self.actions
1561 }
1562}
1563
1564fn same_dispatcher(a: &Option<ActionDispatcherRef>, b: &Option<ActionDispatcherRef>) -> bool {
1566 match (a, b) {
1567 (None, None) => true,
1568 (Some(a), Some(b)) => Rc::ptr_eq(a, b),
1569 _ => false,
1570 }
1571}
1572
1573pub struct FocusableActionDetector {
1589 pub key: Option<KeyRef>,
1591
1592 pub enabled: bool,
1600
1601 pub focus_node: Option<FocusNodeRef>,
1603
1604 pub autofocus: bool,
1607
1608 pub descendants_are_focusable: bool,
1610
1611 pub descendants_are_traversable: bool,
1613
1614 pub actions: Option<HashMap<TypeId, ActionRef>>,
1617
1618 pub shortcuts: Option<ShortcutMap>,
1622
1623 pub on_show_focus_highlight: Option<ValueChanged<bool>>,
1627
1628 pub on_show_hover_highlight: Option<ValueChanged<bool>>,
1632
1633 pub on_focus_change: Option<ValueChanged<bool>>,
1637
1638 pub mouse_cursor: MouseCursorRef,
1643
1644 pub include_focus_semantics: bool,
1648
1649 pub child: WidgetRef,
1651}
1652
1653impl FocusableActionDetector {
1654 #[cfg_attr(debug_assertions, track_caller)]
1656 pub fn new<K>(child: impl IntoWidget<K>) -> FocusableActionDetector {
1657 FocusableActionDetector {
1658 key: None,
1659 enabled: true,
1660 focus_node: None,
1661 autofocus: false,
1662 descendants_are_focusable: true,
1663 descendants_are_traversable: true,
1664 actions: None,
1665 shortcuts: None,
1666 on_show_focus_highlight: None,
1667 on_show_hover_highlight: None,
1668 on_focus_change: None,
1669 mouse_cursor: <dyn MouseCursor>::defer(),
1670 include_focus_semantics: true,
1671 child: child.into_widget(),
1672 }
1673 }
1674
1675 pub fn key(mut self, key: KeyRef) -> FocusableActionDetector {
1677 self.key = Some(key);
1678 self
1679 }
1680
1681 pub fn enabled(mut self, enabled: bool) -> FocusableActionDetector {
1683 self.enabled = enabled;
1684 self
1685 }
1686
1687 pub fn focus_node(mut self, focus_node: FocusNodeRef) -> FocusableActionDetector {
1689 self.focus_node = Some(focus_node);
1690 self
1691 }
1692
1693 pub fn autofocus(mut self, autofocus: bool) -> FocusableActionDetector {
1695 self.autofocus = autofocus;
1696 self
1697 }
1698
1699 pub fn descendants_are_focusable(
1701 mut self,
1702 descendants_are_focusable: bool,
1703 ) -> FocusableActionDetector {
1704 self.descendants_are_focusable = descendants_are_focusable;
1705 self
1706 }
1707
1708 pub fn descendants_are_traversable(
1710 mut self,
1711 descendants_are_traversable: bool,
1712 ) -> FocusableActionDetector {
1713 self.descendants_are_traversable = descendants_are_traversable;
1714 self
1715 }
1716
1717 pub fn actions(mut self, actions: HashMap<TypeId, ActionRef>) -> FocusableActionDetector {
1719 self.actions = Some(actions);
1720 self
1721 }
1722
1723 pub fn shortcuts(mut self, shortcuts: ShortcutMap) -> FocusableActionDetector {
1725 self.shortcuts = Some(shortcuts);
1726 self
1727 }
1728
1729 pub fn on_show_focus_highlight(
1731 mut self,
1732 on_show_focus_highlight: impl Fn(&mut App, bool) + 'static,
1733 ) -> FocusableActionDetector {
1734 self.on_show_focus_highlight = Some(Rc::new(on_show_focus_highlight));
1735 self
1736 }
1737
1738 pub fn on_show_hover_highlight(
1740 mut self,
1741 on_show_hover_highlight: impl Fn(&mut App, bool) + 'static,
1742 ) -> FocusableActionDetector {
1743 self.on_show_hover_highlight = Some(Rc::new(on_show_hover_highlight));
1744 self
1745 }
1746
1747 pub fn on_focus_change(
1749 mut self,
1750 on_focus_change: impl Fn(&mut App, bool) + 'static,
1751 ) -> FocusableActionDetector {
1752 self.on_focus_change = Some(Rc::new(on_focus_change));
1753 self
1754 }
1755
1756 pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> FocusableActionDetector {
1758 self.mouse_cursor = mouse_cursor;
1759 self
1760 }
1761
1762 pub fn include_focus_semantics(
1764 mut self,
1765 include_focus_semantics: bool,
1766 ) -> FocusableActionDetector {
1767 self.include_focus_semantics = include_focus_semantics;
1768 self
1769 }
1770}
1771
1772impl fmt::Debug for FocusableActionDetector {
1773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1774 f.debug_struct("FocusableActionDetector")
1775 .field("enabled", &self.enabled)
1776 .field("focusNode", &self.focus_node)
1777 .finish_non_exhaustive()
1778 }
1779}
1780
1781impl StatefulWidget for FocusableActionDetector {
1782 type State = FocusableActionDetectorState;
1783
1784 fn key(&self) -> Option<&KeyRef> {
1785 self.key.as_ref()
1786 }
1787
1788 fn create_state(&self) -> FocusableActionDetectorState {
1789 FocusableActionDetectorState {
1790 state: StateData::new(),
1791 can_show_highlight: false,
1792 hovering: false,
1793 focused: false,
1794 highlight_mode_listener: None,
1795 mouse_region_key: GlobalKey::new(),
1798 }
1799 }
1800}
1801
1802pub struct FocusableActionDetectorState {
1804 state: StateData<FocusableActionDetector>,
1805 can_show_highlight: bool,
1806 hovering: bool,
1807 focused: bool,
1808 highlight_mode_listener: Option<HighlightModeListener>,
1809 mouse_region_key: GlobalKey,
1810}
1811
1812type HighlightTask<'a> = &'a dyn Fn(Handle<FocusableActionDetectorState>, &mut App);
1815
1816#[derive(Clone, Copy)]
1818struct HighlightState {
1819 hover: bool,
1820 focus: bool,
1821}
1822
1823impl FocusableActionDetectorState {
1824 fn update_highlight_mode(self: Handle<Self>, app: &mut App, _mode: FocusHighlightMode) {
1825 self.may_trigger_callback(
1826 app,
1827 None,
1828 Some(&|this, app| {
1829 let mode = FocusManager::instance(app).highlight_mode(app);
1830 app.get_mut(this).can_show_highlight = match mode {
1831 FocusHighlightMode::Touch => false,
1832 FocusHighlightMode::Traditional => true,
1833 };
1834 }),
1835 );
1836 }
1837
1838 fn handle_focus_highlight_mode_change(
1845 self: Handle<Self>,
1846 app: &mut App,
1847 mode: FocusHighlightMode,
1848 ) {
1849 if !self.mounted(app) {
1850 return;
1851 }
1852 self.update_highlight_mode(app, mode);
1853 }
1854
1855 fn handle_mouse_enter(self: Handle<Self>, app: &mut App) {
1856 if !app.get(self).hovering {
1857 self.may_trigger_callback(
1858 app,
1859 None,
1860 Some(&|this, app| {
1861 app.get_mut(this).hovering = true;
1862 }),
1863 );
1864 }
1865 }
1866
1867 fn handle_mouse_exit(self: Handle<Self>, app: &mut App) {
1868 if app.get(self).hovering {
1869 self.may_trigger_callback(
1870 app,
1871 None,
1872 Some(&|this, app| {
1873 app.get_mut(this).hovering = false;
1874 }),
1875 );
1876 }
1877 }
1878
1879 fn handle_focus_change(self: Handle<Self>, app: &mut App, focused: bool) {
1880 if app.get(self).focused != focused {
1881 self.may_trigger_callback(
1882 app,
1883 None,
1884 Some(&|this, app| {
1885 app.get_mut(this).focused = focused;
1886 }),
1887 );
1888 if let Some(on_focus_change) = self.widget(app).on_focus_change.clone() {
1889 let focused = app.get(self).focused;
1890 on_focus_change(app, focused);
1891 }
1892 }
1893 }
1894
1895 fn should_show_hover_highlight(self: Handle<Self>, app: &App, target_enabled: bool) -> bool {
1896 app.get(self).hovering && target_enabled && app.get(self).can_show_highlight
1897 }
1898
1899 fn can_request_focus(self: Handle<Self>, app: &mut App, target_enabled: bool) -> bool {
1900 let context = self.context(app);
1901 match MediaQuery::maybe_navigation_mode_of(app, context) {
1902 None | Some(NavigationMode::Traditional) => target_enabled,
1903 Some(NavigationMode::Directional) => true,
1904 }
1905 }
1906
1907 fn should_show_focus_highlight(
1908 self: Handle<Self>,
1909 app: &mut App,
1910 target_enabled: bool,
1911 ) -> bool {
1912 app.get(self).focused
1913 && app.get(self).can_show_highlight
1914 && self.can_request_focus(app, target_enabled)
1915 }
1916
1917 fn highlight_state(self: Handle<Self>, app: &mut App, target_enabled: bool) -> HighlightState {
1918 HighlightState {
1919 hover: self.should_show_hover_highlight(app, target_enabled),
1920 focus: self.should_show_focus_highlight(app, target_enabled),
1921 }
1922 }
1923
1924 fn may_trigger_callback(
1931 self: Handle<Self>,
1932 app: &mut App,
1933 old_enabled: Option<bool>,
1934 task: Option<HighlightTask<'_>>,
1935 ) {
1936 debug_assert!(
1937 SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks
1938 );
1939 let old_enabled = old_enabled.unwrap_or_else(|| self.widget(app).enabled);
1940 let did = self.highlight_state(app, old_enabled);
1941 if let Some(task) = task {
1942 task(self, app);
1943 }
1944 let enabled = self.widget(app).enabled;
1945 let do_show = self.highlight_state(app, enabled);
1946 if did.focus != do_show.focus
1947 && let Some(callback) = self.widget(app).on_show_focus_highlight.clone()
1948 {
1949 callback(app, do_show.focus);
1950 }
1951 if did.hover != do_show.hover
1952 && let Some(callback) = self.widget(app).on_show_hover_highlight.clone()
1953 {
1954 callback(app, do_show.hover);
1955 }
1956 }
1957}
1958
1959impl State for FocusableActionDetectorState {
1960 type Widget = FocusableActionDetector;
1961 crate::state_accessors!();
1962
1963 fn init_state(self: Handle<Self>, app: &mut App) {
1964 SchedulerBinding::add_post_frame_callback(
1965 app,
1966 FrameCallback::new(move |app, _duration| {
1967 if !self.mounted(app) {
1970 return;
1971 }
1972 let mode = FocusManager::instance(app).highlight_mode(app);
1973 self.update_highlight_mode(app, mode);
1974 }),
1975 View::maybe_id_of(app, self.context(app)),
1976 );
1977 let listener: HighlightModeListener =
1978 Rc::new(move |app: &mut App, mode| self.handle_focus_highlight_mode_change(app, mode));
1979 app.get_mut(self).highlight_mode_listener = Some(Rc::clone(&listener));
1980 FocusManager::instance(app).add_highlight_mode_listener(app, listener);
1981 }
1982
1983 fn dispose(self: Handle<Self>, app: &mut App) {
1984 if let Some(listener) = app.get_mut(self).highlight_mode_listener.take() {
1985 FocusManager::instance(app).remove_highlight_mode_listener(app, &listener);
1986 }
1987 }
1988
1989 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FocusableActionDetector) {
1990 if self.widget(app).enabled != old_widget.enabled {
1991 let old_enabled = old_widget.enabled;
1992 SchedulerBinding::add_post_frame_callback(
1993 app,
1994 FrameCallback::new(move |app, _duration| {
1995 self.may_trigger_callback(app, Some(old_enabled), None);
1996 }),
1997 View::maybe_id_of(app, self.context(app)),
1998 );
1999 }
2000 }
2001
2002 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
2003 let can_request_focus = {
2004 let enabled = self.widget(app).enabled;
2005 self.can_request_focus(app, enabled)
2006 };
2007 let widget = self.widget(app);
2008 let (
2009 focus_node,
2010 autofocus,
2011 descendants_are_focusable,
2012 descendants_are_traversable,
2013 include_focus_semantics,
2014 mouse_cursor,
2015 child,
2016 enabled,
2017 ) = (
2018 widget.focus_node.clone(),
2019 widget.autofocus,
2020 widget.descendants_are_focusable,
2021 widget.descendants_are_traversable,
2022 widget.include_focus_semantics,
2023 Rc::clone(&widget.mouse_cursor),
2024 widget.child.clone(),
2025 widget.enabled,
2026 );
2027 let mouse_region_key = app.get(self).mouse_region_key.clone();
2028
2029 let mut focus = Focus::new(child)
2030 .autofocus(autofocus)
2031 .descendants_are_focusable(descendants_are_focusable)
2032 .descendants_are_traversable(descendants_are_traversable)
2033 .can_request_focus(can_request_focus)
2034 .on_focus_change(move |app, focused| self.handle_focus_change(app, focused))
2035 .include_semantics(include_focus_semantics);
2036 if let Some(focus_node) = focus_node {
2037 focus = focus.focus_node(focus_node);
2038 }
2039
2040 let mut child: WidgetRef = MouseRegion::new()
2041 .key(mouse_region_key.into())
2042 .on_enter(Rc::new(move |app, _event| self.handle_mouse_enter(app)))
2043 .on_exit(Rc::new(move |app, _event| self.handle_mouse_exit(app)))
2044 .cursor(mouse_cursor)
2045 .child(focus)
2046 .into_widget();
2047
2048 let actions = self.widget(app).actions.clone();
2049 if let Some(actions) = actions.filter(|actions| enabled && !actions.is_empty()) {
2050 child = Actions::new(actions, child).into_widget();
2051 }
2052 let shortcuts = self.widget(app).shortcuts.clone();
2053 if let Some(shortcuts) = shortcuts.filter(|shortcuts| enabled && !shortcuts.is_empty()) {
2054 child = Shortcuts::new(shortcuts, child).into_widget();
2055 }
2056 child
2057 }
2058}
2059
2060pub struct VoidCallbackIntent {
2066 pub callback: Listener,
2069}
2070
2071impl VoidCallbackIntent {
2072 pub fn new(callback: Listener) -> VoidCallbackIntent {
2074 VoidCallbackIntent { callback }
2075 }
2076}
2077
2078impl fmt::Debug for VoidCallbackIntent {
2079 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2080 f.debug_struct("VoidCallbackIntent").finish()
2081 }
2082}
2083
2084impl Intent for VoidCallbackIntent {
2085 fn as_any(&self) -> &dyn Any {
2086 self
2087 }
2088}
2089
2090pub struct VoidCallbackAction {
2099 action: ActionData,
2100}
2101
2102impl VoidCallbackAction {
2103 pub fn new(app: &mut App) -> Ref<VoidCallbackAction> {
2105 app.create(VoidCallbackAction {
2106 action: ActionData::new(),
2107 })
2108 }
2109}
2110
2111impl Action for VoidCallbackAction {
2112 type Intent = VoidCallbackIntent;
2113 crate::action_accessors!();
2114
2115 fn invoke(
2116 self: Handle<Self>,
2117 app: &mut App,
2118 intent: &VoidCallbackIntent,
2119 ) -> Option<Rc<dyn Any>> {
2120 intent.callback.call(app);
2121 None
2122 }
2123}
2124
2125#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2136pub struct DoNothingIntent;
2137
2138impl DoNothingIntent {
2139 pub const fn new() -> DoNothingIntent {
2141 DoNothingIntent
2142 }
2143}
2144
2145impl Intent for DoNothingIntent {
2146 fn as_any(&self) -> &dyn Any {
2147 self
2148 }
2149}
2150
2151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2166pub struct DoNothingAndStopPropagationIntent;
2167
2168impl DoNothingAndStopPropagationIntent {
2169 pub const fn new() -> DoNothingAndStopPropagationIntent {
2171 DoNothingAndStopPropagationIntent
2172 }
2173}
2174
2175impl Intent for DoNothingAndStopPropagationIntent {
2176 fn as_any(&self) -> &dyn Any {
2177 self
2178 }
2179}
2180
2181pub struct DoNothingAction {
2202 action: ActionData,
2203 consumes_key: bool,
2204}
2205
2206impl DoNothingAction {
2207 pub fn new(app: &mut App) -> Ref<DoNothingAction> {
2211 app.create(DoNothingAction {
2212 action: ActionData::new(),
2213 consumes_key: true,
2214 })
2215 }
2216
2217 pub fn set_consumes_key(self: Handle<Self>, app: &mut App, consumes_key: bool) {
2219 app.get_mut(self).consumes_key = consumes_key;
2220 }
2221}
2222
2223impl Action for DoNothingAction {
2224 type Intent = dyn Intent;
2225 crate::action_accessors!();
2226
2227 fn consumes_key(self: Handle<Self>, app: &mut App, _intent: &dyn Intent) -> bool {
2228 app.get(self).consumes_key
2229 }
2230
2231 fn invoke(self: Handle<Self>, _app: &mut App, _intent: &dyn Intent) -> Option<Rc<dyn Any>> {
2232 None
2233 }
2234}
2235
2236#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2242pub struct ActivateIntent;
2243
2244impl ActivateIntent {
2245 pub const fn new() -> ActivateIntent {
2247 ActivateIntent
2248 }
2249}
2250
2251impl Intent for ActivateIntent {
2252 fn as_any(&self) -> &dyn Any {
2253 self
2254 }
2255}
2256
2257#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2263pub struct ButtonActivateIntent;
2264
2265impl ButtonActivateIntent {
2266 pub const fn new() -> ButtonActivateIntent {
2268 ButtonActivateIntent
2269 }
2270}
2271
2272impl Intent for ButtonActivateIntent {
2273 fn as_any(&self) -> &dyn Any {
2274 self
2275 }
2276}
2277
2278pub trait ActivateAction: Action<Intent = ActivateIntent> {}
2284
2285#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2287pub struct SelectIntent;
2288
2289impl SelectIntent {
2290 pub const fn new() -> SelectIntent {
2292 SelectIntent
2293 }
2294}
2295
2296impl Intent for SelectIntent {
2297 fn as_any(&self) -> &dyn Any {
2298 self
2299 }
2300}
2301
2302pub trait SelectAction: Action<Intent = SelectIntent> {}
2307
2308#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
2312pub struct DismissIntent;
2313
2314impl DismissIntent {
2315 pub const fn new() -> DismissIntent {
2317 DismissIntent
2318 }
2319}
2320
2321impl Intent for DismissIntent {
2322 fn as_any(&self) -> &dyn Any {
2323 self
2324 }
2325}
2326
2327pub trait DismissAction: Action<Intent = DismissIntent> {}
2331
2332#[derive(Debug)]
2337pub struct PrioritizedIntents {
2338 pub ordered_intents: Vec<IntentRef>,
2342}
2343
2344impl PrioritizedIntents {
2345 pub fn new(ordered_intents: Vec<IntentRef>) -> PrioritizedIntents {
2348 PrioritizedIntents { ordered_intents }
2349 }
2350}
2351
2352impl Intent for PrioritizedIntents {
2353 fn as_any(&self) -> &dyn Any {
2354 self
2355 }
2356}
2357
2358pub struct PrioritizedAction {
2366 action: ActionData,
2367 selected_action: Option<ActionRef>,
2368 selected_intent: Option<IntentRef>,
2369}
2370
2371impl PrioritizedAction {
2372 pub fn new(app: &mut App) -> Ref<PrioritizedAction> {
2374 app.create(PrioritizedAction {
2375 action: ActionData::new(),
2376 selected_action: None,
2377 selected_intent: None,
2378 })
2379 }
2380}
2381
2382impl Action for PrioritizedAction {
2383 type Intent = PrioritizedIntents;
2384 crate::action_accessors!();
2385 crate::context_action_overrides!();
2386}
2387
2388impl ContextAction for PrioritizedAction {
2389 fn is_enabled(
2390 self: Handle<Self>,
2391 app: &mut App,
2392 intent: &PrioritizedIntents,
2393 context: Option<BuildContext>,
2394 ) -> bool {
2395 let Some(focus) = primary_focus(app) else {
2396 return false;
2397 };
2398 let Some(focus_context) = focus.context(app) else {
2399 return false;
2400 };
2401 for candidate_intent in intent.ordered_intents.iter() {
2402 let candidate_action =
2403 Actions::maybe_find(app, focus_context, candidate_intent.intent_type());
2404 if let Some(candidate_action) = candidate_action
2405 && candidate_action.is_enabled(app, &**candidate_intent, context)
2406 {
2407 let candidate_action = candidate_action.keep(app);
2408 let this = app.get_mut(self);
2409 this.selected_action = Some(candidate_action);
2410 this.selected_intent = Some(Rc::clone(candidate_intent));
2411 return true;
2412 }
2413 }
2414 false
2415 }
2416
2417 fn invoke(
2418 self: Handle<Self>,
2419 app: &mut App,
2420 _intent: &PrioritizedIntents,
2421 context: Option<BuildContext>,
2422 ) -> Option<Rc<dyn Any>> {
2423 let selected_action = app
2424 .get(self)
2425 .selected_action
2426 .handle()
2427 .expect("isEnabled selected an action");
2428 let selected_intent = app
2429 .get(self)
2430 .selected_intent
2431 .clone()
2432 .expect("isEnabled selected an intent");
2433 selected_action.invoke(app, &*selected_intent, context);
2434 None
2435 }
2436}
2437
2438struct OverridableActionData {
2444 default_action: ActionRef,
2447 lookup_context: BuildContext,
2449 debug_assert_mutually_recursive: bool,
2452 debug_assert_is_action_enabled_mutually_recursive: bool,
2453 debug_assert_is_enabled_mutually_recursive: bool,
2454 debug_assert_consume_key_mutually_recursive: bool,
2455}
2456
2457impl OverridableActionData {
2458 fn new(default_action: ActionRef, lookup_context: BuildContext) -> OverridableActionData {
2459 OverridableActionData {
2460 default_action,
2461 lookup_context,
2462 debug_assert_mutually_recursive: false,
2463 debug_assert_is_action_enabled_mutually_recursive: false,
2464 debug_assert_is_enabled_mutually_recursive: false,
2465 debug_assert_consume_key_mutually_recursive: false,
2466 }
2467 }
2468}
2469
2470trait OverridableActionMixin: ContextAction {
2472 fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData;
2474
2475 fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData;
2477
2478 fn invoke_default_action(
2480 self: Handle<Self>,
2481 app: &mut App,
2482 intent: &Self::Intent,
2483 from_action: Option<AnyAction>,
2484 context: Option<BuildContext>,
2485 ) -> Option<Rc<dyn Any>>;
2486
2487 fn get_override_action(
2489 self: Handle<Self>,
2490 app: &mut App,
2491 intent_type: TypeId,
2492 declare_dependency: bool,
2493 ) -> Option<AnyAction> {
2494 let lookup_context = self.overridable_data(app).lookup_context;
2495 let override_action = if declare_dependency {
2496 Actions::maybe_find(app, lookup_context, intent_type)
2497 } else {
2498 Actions::maybe_find_without_depending_on(app, lookup_context, intent_type)
2499 };
2500 debug_assert!(override_action != Some(Action::as_action(self)));
2501 override_action
2502 }
2503
2504 fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
2506 self.action_data_mut(app).current_calling_action = value.clone();
2507 let default_action = self.overridable_data(app).default_action.handle();
2508 default_action.update_calling_action(app, value);
2509 }
2510
2511 fn invoke_override(
2513 self: Handle<Self>,
2514 app: &mut App,
2515 override_action: AnyAction,
2516 intent: &Self::Intent,
2517 context: Option<BuildContext>,
2518 ) -> Option<Rc<dyn Any>> {
2519 debug_assert!(!self.overridable_data(app).debug_assert_mutually_recursive);
2520 if cfg!(debug_assertions) {
2521 self.overridable_data_mut(app)
2522 .debug_assert_mutually_recursive = true;
2523 }
2524 let default_action = self.overridable_data(app).default_action.clone();
2525 override_action.update_calling_action(app, Some(default_action));
2526 let return_value = override_action.invoke(app, intent.as_intent(), context);
2527 override_action.update_calling_action(app, None);
2528 if cfg!(debug_assertions) {
2529 self.overridable_data_mut(app)
2530 .debug_assert_mutually_recursive = false;
2531 }
2532 return_value
2533 }
2534
2535 fn invoke(
2537 self: Handle<Self>,
2538 app: &mut App,
2539 intent: &Self::Intent,
2540 context: Option<BuildContext>,
2541 ) -> Option<Rc<dyn Any>> {
2542 let intent_type = intent.as_intent().intent_type();
2543 let override_action = self.get_override_action(app, intent_type, false);
2544 match override_action {
2545 None => {
2546 let calling = self.action_data(app).current_calling_action.handle();
2547 self.invoke_default_action(app, intent, calling, context)
2548 }
2549 Some(override_action) => self.invoke_override(app, override_action, intent, context),
2550 }
2551 }
2552
2553 fn is_override_action_enabled(
2555 self: Handle<Self>,
2556 app: &mut App,
2557 override_action: AnyAction,
2558 ) -> bool {
2559 debug_assert!(
2560 !self
2561 .overridable_data(app)
2562 .debug_assert_is_action_enabled_mutually_recursive
2563 );
2564 if cfg!(debug_assertions) {
2565 self.overridable_data_mut(app)
2566 .debug_assert_is_action_enabled_mutually_recursive = true;
2567 }
2568 let default_action = self.overridable_data(app).default_action.clone();
2569 override_action.update_calling_action(app, Some(default_action));
2570 let is_override_enabled = override_action.is_action_enabled(app);
2571 override_action.update_calling_action(app, None);
2572 if cfg!(debug_assertions) {
2573 self.overridable_data_mut(app)
2574 .debug_assert_is_action_enabled_mutually_recursive = false;
2575 }
2576 is_override_enabled
2577 }
2578
2579 fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
2581 let intent_type = TypeId::of::<Self::Intent>();
2582 let override_action = self.get_override_action(app, intent_type, true);
2583 match override_action {
2584 Some(override_action) => self.is_override_action_enabled(app, override_action),
2585 None => self
2586 .overridable_data(app)
2587 .default_action
2588 .is_action_enabled(app),
2589 }
2590 }
2591
2592 fn is_enabled(
2594 self: Handle<Self>,
2595 app: &mut App,
2596 intent: &Self::Intent,
2597 context: Option<BuildContext>,
2598 ) -> bool {
2599 debug_assert!(
2600 !self
2601 .overridable_data(app)
2602 .debug_assert_is_enabled_mutually_recursive
2603 );
2604 if cfg!(debug_assertions) {
2605 self.overridable_data_mut(app)
2606 .debug_assert_is_enabled_mutually_recursive = true;
2607 }
2608
2609 let erased = intent.as_intent();
2610 let override_action = self.get_override_action(app, erased.intent_type(), false);
2611 let default_action = self.overridable_data(app).default_action.clone();
2612 if let Some(override_action) = override_action {
2613 override_action.update_calling_action(app, Some(default_action.clone()));
2614 }
2615 let return_value = override_action
2616 .unwrap_or(default_action.handle())
2617 .is_enabled(app, intent.as_intent(), context);
2618 if let Some(override_action) = override_action {
2619 override_action.update_calling_action(app, None);
2620 }
2621 if cfg!(debug_assertions) {
2622 self.overridable_data_mut(app)
2623 .debug_assert_is_enabled_mutually_recursive = false;
2624 }
2625 return_value
2626 }
2627
2628 fn consumes_key(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
2630 debug_assert!(
2631 !self
2632 .overridable_data(app)
2633 .debug_assert_consume_key_mutually_recursive
2634 );
2635 if cfg!(debug_assertions) {
2636 self.overridable_data_mut(app)
2637 .debug_assert_consume_key_mutually_recursive = true;
2638 }
2639 let erased = intent.as_intent();
2640 let override_action = self.get_override_action(app, erased.intent_type(), false);
2641 let default_action = self.overridable_data(app).default_action.clone();
2642 if let Some(override_action) = override_action {
2643 override_action.update_calling_action(app, Some(default_action.clone()));
2644 }
2645 let is_enabled = override_action
2646 .unwrap_or(default_action.handle())
2647 .consumes_key(app, intent.as_intent());
2648 if let Some(override_action) = override_action {
2649 override_action.update_calling_action(app, None);
2650 }
2651 if cfg!(debug_assertions) {
2652 self.overridable_data_mut(app)
2653 .debug_assert_consume_key_mutually_recursive = false;
2654 }
2655 is_enabled
2656 }
2657}
2658
2659pub struct OverridableAction<T: ActionIntent + ?Sized> {
2661 action: ActionData,
2662 overridable: OverridableActionData,
2663 intent: std::marker::PhantomData<fn(&T)>,
2664}
2665
2666impl<T: ActionIntent + ?Sized> OverridableAction<T> {
2667 pub fn new(
2670 app: &mut App,
2671 default_action: ActionRef,
2672 lookup_context: BuildContext,
2673 ) -> Ref<OverridableAction<T>> {
2674 app.create(OverridableAction::<T> {
2675 action: ActionData::new(),
2676 overridable: OverridableActionData::new(default_action, lookup_context),
2677 intent: std::marker::PhantomData,
2678 })
2679 }
2680}
2681
2682impl<T: ActionIntent + ?Sized> Action for OverridableAction<T> {
2683 type Intent = T;
2684 crate::action_accessors!();
2685
2686 fn debug_fill_properties(
2687 self: Handle<Self>,
2688 app: &App,
2689 properties: &mut DiagnosticPropertiesBuilder,
2690 ) {
2691 properties.add(DiagnosticsProperty::<String>::new(
2692 "defaultAction",
2693 Some(app.get(self).overridable.default_action.to_string_short()),
2694 ));
2695 }
2696
2697 fn as_action(self: Handle<Self>) -> AnyAction {
2698 AnyAction::of_context::<Self>(self)
2699 }
2700
2701 fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2702 ContextAction::is_enabled(self, app, intent, None)
2703 }
2704
2705 fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
2706 ContextAction::invoke(self, app, intent, None)
2707 }
2708
2709 fn make_overridable_action(
2710 self: Handle<Self>,
2711 app: &mut App,
2712 context: BuildContext,
2713 ) -> ActionRef {
2714 let default_action = self.overridable_data(app).default_action.clone();
2715 OverridableAction::<T>::new(app, default_action, context).into_erased()
2716 }
2717
2718 fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
2719 OverridableActionMixin::update_calling_action(self, app, value);
2720 }
2721
2722 fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
2723 OverridableActionMixin::is_action_enabled(self, app)
2724 }
2725
2726 fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2727 OverridableActionMixin::consumes_key(self, app, intent)
2728 }
2729}
2730
2731impl<T: ActionIntent + ?Sized> ContextAction for OverridableAction<T> {
2732 fn is_enabled(
2733 self: Handle<Self>,
2734 app: &mut App,
2735 intent: &T,
2736 context: Option<BuildContext>,
2737 ) -> bool {
2738 OverridableActionMixin::is_enabled(self, app, intent, context)
2739 }
2740
2741 fn invoke(
2742 self: Handle<Self>,
2743 app: &mut App,
2744 intent: &T,
2745 context: Option<BuildContext>,
2746 ) -> Option<Rc<dyn Any>> {
2747 OverridableActionMixin::invoke(self, app, intent, context)
2748 }
2749}
2750
2751impl<T: ActionIntent + ?Sized> OverridableActionMixin for OverridableAction<T> {
2752 fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData {
2753 &app.get(self).overridable
2754 }
2755
2756 fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData {
2757 &mut app.get_mut(self).overridable
2758 }
2759
2760 fn invoke_default_action(
2761 self: Handle<Self>,
2762 app: &mut App,
2763 intent: &T,
2764 _from_action: Option<AnyAction>,
2765 _context: Option<BuildContext>,
2766 ) -> Option<Rc<dyn Any>> {
2767 let default_action = self.overridable_data(app).default_action.handle();
2768 default_action.invoke(app, intent.as_intent(), None)
2769 }
2770}
2771
2772pub struct OverridableContextAction<T: ActionIntent + ?Sized> {
2774 action: ActionData,
2775 overridable: OverridableActionData,
2776 intent: std::marker::PhantomData<fn(&T)>,
2777}
2778
2779impl<T: ActionIntent + ?Sized> OverridableContextAction<T> {
2780 pub fn new(
2783 app: &mut App,
2784 default_action: ActionRef,
2785 lookup_context: BuildContext,
2786 ) -> Ref<OverridableContextAction<T>> {
2787 app.create(OverridableContextAction::<T> {
2788 action: ActionData::new(),
2789 overridable: OverridableActionData::new(default_action, lookup_context),
2790 intent: std::marker::PhantomData,
2791 })
2792 }
2793}
2794
2795impl<T: ActionIntent + ?Sized> Action for OverridableContextAction<T> {
2796 type Intent = T;
2797 crate::action_accessors!();
2798
2799 fn as_action(self: Handle<Self>) -> AnyAction {
2800 AnyAction::of_context::<Self>(self)
2801 }
2802
2803 fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2804 ContextAction::is_enabled(self, app, intent, None)
2805 }
2806
2807 fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
2808 ContextAction::invoke(self, app, intent, None)
2809 }
2810
2811 fn make_overridable_action(
2812 self: Handle<Self>,
2813 app: &mut App,
2814 context: BuildContext,
2815 ) -> ActionRef {
2816 let default_action = self.overridable_data(app).default_action.clone();
2817 OverridableContextAction::<T>::new(app, default_action, context).into_erased()
2818 }
2819
2820 fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
2821 OverridableActionMixin::update_calling_action(self, app, value);
2822 }
2823
2824 fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
2825 OverridableActionMixin::is_action_enabled(self, app)
2826 }
2827
2828 fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2829 OverridableActionMixin::consumes_key(self, app, intent)
2830 }
2831}
2832
2833impl<T: ActionIntent + ?Sized> ContextAction for OverridableContextAction<T> {
2834 fn is_enabled(
2835 self: Handle<Self>,
2836 app: &mut App,
2837 intent: &T,
2838 context: Option<BuildContext>,
2839 ) -> bool {
2840 OverridableActionMixin::is_enabled(self, app, intent, context)
2841 }
2842
2843 fn invoke(
2844 self: Handle<Self>,
2845 app: &mut App,
2846 intent: &T,
2847 context: Option<BuildContext>,
2848 ) -> Option<Rc<dyn Any>> {
2849 OverridableActionMixin::invoke(self, app, intent, context)
2850 }
2851}
2852
2853impl<T: ActionIntent + ?Sized> OverridableActionMixin for OverridableContextAction<T> {
2854 fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData {
2855 &app.get(self).overridable
2856 }
2857
2858 fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData {
2859 &mut app.get_mut(self).overridable
2860 }
2861
2862 fn invoke_override(
2865 self: Handle<Self>,
2866 app: &mut App,
2867 override_action: AnyAction,
2868 intent: &T,
2869 context: Option<BuildContext>,
2870 ) -> Option<Rc<dyn Any>> {
2871 debug_assert!(context.is_some());
2872 debug_assert!(!self.overridable_data(app).debug_assert_mutually_recursive);
2873 if cfg!(debug_assertions) {
2874 self.overridable_data_mut(app)
2875 .debug_assert_mutually_recursive = true;
2876 }
2877
2878 let default_action = self.overridable_data(app).default_action.clone();
2879 let invoke_context = context.expect("an overridable context action is invoked with one");
2880 let wrapped_default =
2881 ContextActionToActionAdapter::<T>::new(app, invoke_context, default_action);
2882 override_action.update_calling_action(app, Some(wrapped_default.into_erased()));
2883 let return_value = override_action.invoke(app, intent.as_intent(), context);
2884 override_action.update_calling_action(app, None);
2885
2886 if cfg!(debug_assertions) {
2887 self.overridable_data_mut(app)
2888 .debug_assert_mutually_recursive = false;
2889 }
2890 return_value
2891 }
2892
2893 fn invoke_default_action(
2894 self: Handle<Self>,
2895 app: &mut App,
2896 intent: &T,
2897 _from_action: Option<AnyAction>,
2898 context: Option<BuildContext>,
2899 ) -> Option<Rc<dyn Any>> {
2900 let default_action = self.overridable_data(app).default_action.handle();
2901 default_action.invoke(app, intent.as_intent(), context)
2902 }
2903}
2904
2905struct ContextActionToActionAdapter<T: ActionIntent + ?Sized> {
2908 action: ActionData,
2909 invoke_context: BuildContext,
2910 wrapped: ActionRef,
2911 intent: std::marker::PhantomData<fn(&T)>,
2912}
2913
2914impl<T: ActionIntent + ?Sized> ContextActionToActionAdapter<T> {
2915 fn new(
2916 app: &mut App,
2917 invoke_context: BuildContext,
2918 wrapped: ActionRef,
2919 ) -> Ref<ContextActionToActionAdapter<T>> {
2920 app.create(ContextActionToActionAdapter::<T> {
2921 action: ActionData::new(),
2922 invoke_context,
2923 wrapped,
2924 intent: std::marker::PhantomData,
2925 })
2926 }
2927}
2928
2929impl<T: ActionIntent + ?Sized> Action for ContextActionToActionAdapter<T> {
2930 type Intent = T;
2931 crate::action_accessors!();
2932
2933 fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
2934 let wrapped = app.get(self).wrapped.handle();
2935 wrapped.update_calling_action(app, value);
2936 }
2937
2938 fn calling_action(self: Handle<Self>, app: &App) -> Option<AnyAction> {
2939 app.get(self).wrapped.calling_action(app)
2940 }
2941
2942 fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2943 let (wrapped, invoke_context) = {
2944 let this = app.get(self);
2945 (this.wrapped.handle(), this.invoke_context)
2946 };
2947 wrapped.is_enabled(app, intent.as_intent(), Some(invoke_context))
2948 }
2949
2950 fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
2951 app.get(self).wrapped.is_action_enabled(app)
2952 }
2953
2954 fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
2955 let wrapped = app.get(self).wrapped.handle();
2956 wrapped.consumes_key(app, intent.as_intent())
2957 }
2958
2959 fn add_action_listener(self: Handle<Self>, app: &mut App, listener: ActionListenerCallback) {
2960 self.action_data_mut(app)
2961 .listeners
2962 .push(Rc::clone(&listener));
2963 let wrapped = app.get(self).wrapped.handle();
2964 wrapped.add_action_listener(app, listener);
2965 }
2966
2967 fn remove_action_listener(
2968 self: Handle<Self>,
2969 app: &mut App,
2970 listener: &ActionListenerCallback,
2971 ) {
2972 let listeners = &mut self.action_data_mut(app).listeners;
2973 if let Some(index) = listeners
2974 .iter()
2975 .position(|registered| Rc::ptr_eq(registered, listener))
2976 {
2977 listeners.remove(index);
2978 }
2979 let wrapped = app.get(self).wrapped.handle();
2980 wrapped.remove_action_listener(app, listener);
2981 }
2982
2983 fn notify_action_listeners(self: Handle<Self>, app: &mut App) {
2984 app.get(self).wrapped.notify_action_listeners(app);
2985 }
2986
2987 fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
2988 let (wrapped, invoke_context) = {
2989 let this = app.get(self);
2990 (this.wrapped.handle(), this.invoke_context)
2991 };
2992 wrapped.invoke(app, intent.as_intent(), Some(invoke_context))
2993 }
2994}
2995
2996#[cfg(test)]
2997mod tests {
2998 use std::cell::{Cell, RefCell};
2999
3000 use waft_embedder::Offset;
3001
3002 use super::*;
3003 use crate::testing::{TestPointer, test_widgets};
3004 use crate::widgets::basic::{Builder, SizedBox};
3005 use crate::widgets::focus_manager::{FocusHighlightStrategy, FocusNodeLeaf};
3006
3007 #[derive(Debug)]
3008 struct CountIntent {
3009 amount: i32,
3010 }
3011
3012 impl Intent for CountIntent {
3013 fn as_any(&self) -> &dyn Any {
3014 self
3015 }
3016 }
3017
3018 #[derive(Debug)]
3019 struct OtherIntent;
3020
3021 impl Intent for OtherIntent {
3022 fn as_any(&self) -> &dyn Any {
3023 self
3024 }
3025 }
3026
3027 struct CountAction {
3029 action: ActionData,
3030 log: Rc<RefCell<Vec<String>>>,
3031 name: &'static str,
3032 enabled: bool,
3033 }
3034
3035 impl CountAction {
3036 fn new(
3037 app: &mut App,
3038 log: &Rc<RefCell<Vec<String>>>,
3039 name: &'static str,
3040 ) -> Ref<CountAction> {
3041 app.create(CountAction {
3042 action: ActionData::new(),
3043 log: Rc::clone(log),
3044 name,
3045 enabled: true,
3046 })
3047 }
3048
3049 fn set_enabled(self: Handle<Self>, app: &mut App, enabled: bool) {
3050 app.get_mut(self).enabled = enabled;
3051 self.notify_action_listeners(app);
3052 }
3053 }
3054
3055 impl Action for CountAction {
3056 type Intent = CountIntent;
3057 crate::action_accessors!();
3058
3059 fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
3060 app.get(self).enabled
3061 }
3062
3063 fn invoke(self: Handle<Self>, app: &mut App, intent: &CountIntent) -> Option<Rc<dyn Any>> {
3064 let (log, name) = {
3065 let this = app.get(self);
3066 (Rc::clone(&this.log), this.name)
3067 };
3068 log.borrow_mut().push(format!("{name}:{}", intent.amount));
3069 Some(Rc::new(intent.amount * 2))
3070 }
3071 }
3072
3073 fn map(intent_type: TypeId, action: ActionRef) -> HashMap<TypeId, ActionRef> {
3074 HashMap::from([(intent_type, action)])
3075 }
3076
3077 fn probe(sink: &Rc<Cell<Option<BuildContext>>>) -> WidgetRef {
3079 let sink = Rc::clone(sink);
3080 Builder::new(move |_app, context| {
3081 sink.set(Some(context));
3082 SizedBox::shrink().into_widget()
3083 })
3084 .into_widget()
3085 }
3086
3087 fn as_i32(result: Option<Rc<dyn Any>>) -> Option<i32> {
3088 result.and_then(|value| value.downcast_ref::<i32>().copied())
3089 }
3090
3091 #[test]
3092 fn invoke_reaches_the_nearest_actions_widget_that_maps_the_intent() {
3093 test_widgets(|tester| {
3094 let mut app = tester.cell.borrow_mut();
3095 let log: Rc<RefCell<Vec<String>>> = Rc::default();
3096 let outer = CountAction::new(&mut app, &log, "outer");
3097 let inner = CountAction::new(&mut app, &log, "inner");
3098 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3099 drop(app);
3100 tester.pump_widget(
3101 Actions::new(
3102 map(TypeId::of::<CountIntent>(), outer.erase()),
3103 Actions::new(
3104 map(TypeId::of::<CountIntent>(), inner.erase()),
3105 probe(&captured),
3106 ),
3107 )
3108 .into_widget(),
3109 );
3110 let mut app = tester.cell.borrow_mut();
3111 let context = captured.get().expect("the builder ran");
3112
3113 let result = Actions::invoke(&mut app, context, &CountIntent { amount: 2 });
3114 assert_eq!(*log.borrow(), ["inner:2"]);
3115 assert_eq!(as_i32(result), Some(4));
3116
3117 inner.set_enabled(&mut app, false);
3119 log.borrow_mut().clear();
3120 let result = Actions::maybe_invoke(&mut app, context, &CountIntent { amount: 3 });
3121 assert!(log.borrow().is_empty());
3122 assert_eq!(as_i32(result), None);
3123 });
3124 }
3125
3126 #[test]
3127 fn invoke_walks_past_an_actions_widget_that_does_not_map_the_intent() {
3128 test_widgets(|tester| {
3129 let mut app = tester.cell.borrow_mut();
3130 let log: Rc<RefCell<Vec<String>>> = Rc::default();
3131 let outer = CountAction::new(&mut app, &log, "outer");
3132 let unrelated = DoNothingAction::new(&mut app);
3133 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3134 drop(app);
3135 tester.pump_widget(
3136 Actions::new(
3137 map(TypeId::of::<CountIntent>(), outer.erase()),
3138 Actions::new(
3139 map(TypeId::of::<OtherIntent>(), unrelated.erase()),
3140 probe(&captured),
3141 ),
3142 )
3143 .into_widget(),
3144 );
3145 let mut app = tester.cell.borrow_mut();
3146 let context = captured.get().expect("the builder ran");
3147
3148 let result = Actions::invoke(&mut app, context, &CountIntent { amount: 5 });
3149 assert_eq!(*log.borrow(), ["outer:5"]);
3150 assert_eq!(as_i32(result), Some(10));
3151 });
3152 }
3153
3154 #[test]
3155 fn maybe_find_returns_the_bound_action_and_handler_only_when_it_is_enabled() {
3156 test_widgets(|tester| {
3157 let mut app = tester.cell.borrow_mut();
3158 let log: Rc<RefCell<Vec<String>>> = Rc::default();
3159 let action = CountAction::new(&mut app, &log, "action");
3160 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3161 drop(app);
3162 tester.pump_widget(
3163 Actions::new(
3164 map(TypeId::of::<CountIntent>(), action.erase()),
3165 probe(&captured),
3166 )
3167 .into_widget(),
3168 );
3169 let mut app = tester.cell.borrow_mut();
3170 let context = captured.get().expect("the builder ran");
3171
3172 assert_eq!(
3173 Actions::maybe_find(&mut app, context, TypeId::of::<CountIntent>()),
3174 Some(Action::as_action(action.handle()))
3175 );
3176 assert_eq!(
3177 Actions::maybe_find(&mut app, context, TypeId::of::<OtherIntent>()),
3178 None
3179 );
3180
3181 let intent: IntentRef = Rc::new(CountIntent { amount: 7 });
3182 let handler = Actions::handler(&mut app, context, Rc::clone(&intent))
3183 .expect("an enabled action has a handler");
3184 handler.call(&mut app);
3185 assert_eq!(*log.borrow(), ["action:7"]);
3186
3187 action.set_enabled(&mut app, false);
3188 assert!(Actions::handler(&mut app, context, intent).is_none());
3189 });
3190 }
3191
3192 #[test]
3193 fn an_overridable_action_prefers_the_override_above_its_lookup_context() {
3194 test_widgets(|tester| {
3195 let mut app = tester.cell.borrow_mut();
3196 let log: Rc<RefCell<Vec<String>>> = Rc::default();
3197 let override_action = CountAction::new(&mut app, &log, "override");
3198 let default_action = CountAction::new(&mut app, &log, "default");
3199 let outer_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
3200 let inner_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
3201 let outer_sink = Rc::clone(&outer_context);
3202 let inner_sink = Rc::clone(&inner_context);
3203 drop(app);
3204 tester.pump_widget(
3205 Actions::new(
3206 map(TypeId::of::<CountIntent>(), override_action.erase()),
3207 Builder::new(move |_app, context| {
3208 outer_sink.set(Some(context));
3209 probe(&inner_sink)
3210 }),
3211 )
3212 .into_widget(),
3213 );
3214 let mut app = tester.cell.borrow_mut();
3215 let lookup_context = outer_context.get().expect("the builder ran");
3216
3217 let overridable =
3218 AnyAction::overridable(&mut app, default_action.erase(), lookup_context);
3219 let intent = CountIntent { amount: 1 };
3220 overridable.invoke(&mut app, &intent, Some(lookup_context));
3221 assert_eq!(*log.borrow(), ["override:1"]);
3222
3223 });
3225 test_widgets(|tester| {
3226 let mut app = tester.cell.borrow_mut();
3227 let log: Rc<RefCell<Vec<String>>> = Rc::default();
3228 let default_action = CountAction::new(&mut app, &log, "default");
3229 let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
3230 drop(app);
3231 tester.pump_widget(probe(&captured));
3232 let mut app = tester.cell.borrow_mut();
3233 let lookup_context = captured.get().expect("the builder ran");
3234 let intent = CountIntent { amount: 1 };
3235 let overridable =
3236 AnyAction::overridable(&mut app, default_action.erase(), lookup_context);
3237 overridable.invoke(&mut app, &intent, Some(lookup_context));
3238 assert_eq!(*log.borrow(), ["default:1"]);
3239 });
3240 }
3241
3242 #[test]
3243 fn the_detector_reports_the_focus_highlight() {
3244 test_widgets(|tester| {
3245 let mut app = tester.cell.borrow_mut();
3246 FocusManager::instance(&mut app)
3247 .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
3248 let focus_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
3249 let focused: Rc<RefCell<Vec<bool>>> = Rc::default();
3250 let highlight_sink = Rc::clone(&focus_highlights);
3251 let focus_sink = Rc::clone(&focused);
3252 drop(app);
3253 tester.pump_widget(
3254 FocusableActionDetector::new(SizedBox::expand())
3255 .autofocus(true)
3256 .on_show_focus_highlight(move |_app, show| {
3257 highlight_sink.borrow_mut().push(show)
3258 })
3259 .on_focus_change(move |_app, has_focus| focus_sink.borrow_mut().push(has_focus))
3260 .into_widget(),
3261 );
3262 tester.pump();
3264
3265 assert_eq!(*focused.borrow(), [true]);
3266 assert_eq!(*focus_highlights.borrow(), [true]);
3267 });
3268 }
3269
3270 #[test]
3271 fn the_detector_reports_the_hover_highlight() {
3272 test_widgets(|tester| {
3273 let mut app = tester.cell.borrow_mut();
3274 FocusManager::instance(&mut app)
3275 .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
3276 let hover_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
3277 let sink = Rc::clone(&hover_highlights);
3278 drop(app);
3279 tester.pump_widget(
3280 FocusableActionDetector::new(SizedBox::expand())
3281 .on_show_hover_highlight(move |_app, show| sink.borrow_mut().push(show))
3282 .into_widget(),
3283 );
3284 tester.pump();
3285
3286 let mut mouse = TestPointer::mouse(1, 0);
3287 tester.move_to(&mut mouse, Offset::new(10.0, 10.0), false);
3288 assert_eq!(*hover_highlights.borrow(), [true]);
3289
3290 tester.move_to(&mut mouse, Offset::new(10_000.0, 10_000.0), false);
3291 assert_eq!(*hover_highlights.borrow(), [true, false]);
3292 });
3293 }
3294
3295 #[test]
3296 fn a_disabled_detector_shows_no_highlight() {
3297 test_widgets(|tester| {
3298 let mut app = tester.cell.borrow_mut();
3299 FocusManager::instance(&mut app)
3300 .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
3301 let focus_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
3302 let sink = Rc::clone(&focus_highlights);
3303 let node = crate::FocusNode::new(&mut app);
3304 let detector = |enabled: bool, sink: Rc<RefCell<Vec<bool>>>| {
3305 FocusableActionDetector::new(SizedBox::expand())
3306 .enabled(enabled)
3307 .focus_node(node.erase())
3308 .autofocus(true)
3309 .on_show_focus_highlight(move |_app, show| sink.borrow_mut().push(show))
3310 .into_widget()
3311 };
3312 drop(app);
3313 tester.pump_widget(detector(false, Rc::clone(&sink)));
3314 tester.pump();
3315 let mut app = tester.cell.borrow_mut();
3316 node.request_focus(&mut app, None);
3318 app.drain_microtasks();
3319 assert!(!node.has_primary_focus(&app));
3320 assert!(focus_highlights.borrow().is_empty());
3321
3322 drop(app);
3323 tester.pump_widget(detector(true, Rc::clone(&sink)));
3324 tester.pump();
3325 let mut app = tester.cell.borrow_mut();
3326 node.request_focus(&mut app, None);
3327 app.drain_microtasks();
3328 assert!(node.has_primary_focus(&app));
3329 assert_eq!(*focus_highlights.borrow(), [true]);
3330 });
3331 }
3332}
3333
3334#[cfg(test)]
3335mod diagnostics_tests {
3336 use std::collections::HashMap;
3337
3338 use waft_rendering::testing::ignoring_hash_codes;
3339
3340 use super::*;
3341 use crate::Container;
3342 use crate::testing::describe_properties;
3343
3344 #[test]
3346 fn a_default_intent_adds_no_properties() {
3347 let intent = ActivateIntent;
3348 assert_eq!(
3349 describe_properties(|properties| intent.debug_fill_properties(properties)),
3350 Vec::<String>::new()
3351 );
3352 }
3353
3354 #[test]
3356 fn the_default_actions_describe_their_dispatcher_and_empty_map() {
3357 let actions = Actions::new(HashMap::new(), Container::new())
3358 .dispatcher(Rc::new(PlainActionDispatcher::new()));
3359 let cell = waft_foundation::AppCell::new();
3360 let app = cell.borrow();
3361 let description =
3362 describe_properties(|properties| actions.debug_fill_properties(&app, properties));
3363 assert_eq!(description.len(), 2);
3364 assert_eq!(
3365 ignoring_hash_codes(&description.join("\n")),
3366 "dispatcher: ActionDispatcher#00000\nactions: {}"
3367 );
3368 }
3369}