Wire up global actions

Added an ephemeral root node so that even if there's no window/focused handle we still have something to dispatch to.

Co-authored-by: Antonio <antonio@zed.dev>
This commit is contained in:
Piotr Osiewicz 2023-12-06 16:15:53 +01:00
parent 1f538c5fdd
commit d09dfe01f5
5 changed files with 162 additions and 132 deletions

View file

@ -2803,35 +2803,46 @@ impl Element for EditorElement {
let focus_handle = editor.focus_handle(cx); let focus_handle = editor.focus_handle(cx);
let dispatch_context = self.editor.read(cx).dispatch_context(cx); let dispatch_context = self.editor.read(cx).dispatch_context(cx);
cx.with_key_dispatch(dispatch_context, Some(focus_handle.clone()), |_, cx| { cx.with_key_dispatch(
self.register_actions(cx); Some(dispatch_context),
self.register_key_listeners(cx); Some(focus_handle.clone()),
|_, cx| {
self.register_actions(cx);
self.register_key_listeners(cx);
// We call with_z_index to establish a new stacking context. // We call with_z_index to establish a new stacking context.
cx.with_z_index(0, |cx| { cx.with_z_index(0, |cx| {
cx.with_content_mask(Some(ContentMask { bounds }), |cx| { cx.with_content_mask(Some(ContentMask { bounds }), |cx| {
// Paint mouse listeners at z-index 0 so any elements we paint on top of the editor // Paint mouse listeners at z-index 0 so any elements we paint on top of the editor
// take precedence. // take precedence.
cx.with_z_index(0, |cx| { cx.with_z_index(0, |cx| {
self.paint_mouse_listeners(bounds, gutter_bounds, text_bounds, &layout, cx); self.paint_mouse_listeners(
bounds,
gutter_bounds,
text_bounds,
&layout,
cx,
);
});
let input_handler =
ElementInputHandler::new(bounds, self.editor.clone(), cx);
cx.handle_input(&focus_handle, input_handler);
self.paint_background(gutter_bounds, text_bounds, &layout, cx);
if layout.gutter_size.width > Pixels::ZERO {
self.paint_gutter(gutter_bounds, &mut layout, cx);
}
self.paint_text(text_bounds, &mut layout, cx);
if !layout.blocks.is_empty() {
cx.with_element_id(Some("editor_blocks"), |cx| {
self.paint_blocks(bounds, &mut layout, cx);
})
}
}); });
let input_handler = ElementInputHandler::new(bounds, self.editor.clone(), cx);
cx.handle_input(&focus_handle, input_handler);
self.paint_background(gutter_bounds, text_bounds, &layout, cx);
if layout.gutter_size.width > Pixels::ZERO {
self.paint_gutter(gutter_bounds, &mut layout, cx);
}
self.paint_text(text_bounds, &mut layout, cx);
if !layout.blocks.is_empty() {
cx.with_element_id(Some("editor_blocks"), |cx| {
self.paint_blocks(bounds, &mut layout, cx);
})
}
}); });
}); },
}) )
} }
} }

View file

@ -201,7 +201,7 @@ pub struct AppContext {
pub(crate) windows: SlotMap<WindowId, Option<Window>>, pub(crate) windows: SlotMap<WindowId, Option<Window>>,
pub(crate) keymap: Arc<Mutex<Keymap>>, pub(crate) keymap: Arc<Mutex<Keymap>>,
pub(crate) global_action_listeners: pub(crate) global_action_listeners:
HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self)>>>, HashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
pending_effects: VecDeque<Effect>, pending_effects: VecDeque<Effect>,
pub(crate) pending_notifications: HashSet<EntityId>, pub(crate) pending_notifications: HashSet<EntityId>,
pub(crate) pending_global_notifications: HashSet<TypeId>, pub(crate) pending_global_notifications: HashSet<TypeId>,
@ -962,9 +962,9 @@ impl AppContext {
self.global_action_listeners self.global_action_listeners
.entry(TypeId::of::<A>()) .entry(TypeId::of::<A>())
.or_default() .or_default()
.push(Box::new(move |action, phase, cx| { .push(Rc::new(move |action, phase, cx| {
if phase == DispatchPhase::Bubble { if phase == DispatchPhase::Bubble {
let action = action.as_any().downcast_ref().unwrap(); let action = action.downcast_ref().unwrap();
listener(action, cx) listener(action, cx)
} }
})); }));

View file

@ -55,7 +55,7 @@ pub trait InteractiveElement: Sized + Element {
E: Debug, E: Debug,
{ {
if let Some(key_context) = key_context.try_into().log_err() { if let Some(key_context) = key_context.try_into().log_err() {
self.interactivity().key_context = key_context; self.interactivity().key_context = Some(key_context);
} }
self self
} }
@ -722,7 +722,7 @@ impl DivState {
pub struct Interactivity { pub struct Interactivity {
pub element_id: Option<ElementId>, pub element_id: Option<ElementId>,
pub key_context: KeyContext, pub key_context: Option<KeyContext>,
pub focusable: bool, pub focusable: bool,
pub tracked_focus_handle: Option<FocusHandle>, pub tracked_focus_handle: Option<FocusHandle>,
pub scroll_handle: Option<ScrollHandle>, pub scroll_handle: Option<ScrollHandle>,
@ -1238,7 +1238,7 @@ impl Default for Interactivity {
fn default() -> Self { fn default() -> Self {
Self { Self {
element_id: None, element_id: None,
key_context: KeyContext::default(), key_context: None,
focusable: false, focusable: false,
tracked_focus_handle: None, tracked_focus_handle: None,
scroll_handle: None, scroll_handle: None,

View file

@ -61,7 +61,7 @@ impl DispatchTree {
self.keystroke_matchers.clear(); self.keystroke_matchers.clear();
} }
pub fn push_node(&mut self, context: KeyContext) { pub fn push_node(&mut self, context: Option<KeyContext>) {
let parent = self.node_stack.last().copied(); let parent = self.node_stack.last().copied();
let node_id = DispatchNodeId(self.nodes.len()); let node_id = DispatchNodeId(self.nodes.len());
self.nodes.push(DispatchNode { self.nodes.push(DispatchNode {
@ -69,7 +69,7 @@ impl DispatchTree {
..Default::default() ..Default::default()
}); });
self.node_stack.push(node_id); self.node_stack.push(node_id);
if !context.is_empty() { if let Some(context) = context {
self.active_node().context = context.clone(); self.active_node().context = context.clone();
self.context_stack.push(context); self.context_stack.push(context);
} }
@ -148,16 +148,14 @@ impl DispatchTree {
false false
} }
pub fn available_actions(&self, target: FocusId) -> Vec<Box<dyn Action>> { pub fn available_actions(&self, target: DispatchNodeId) -> Vec<Box<dyn Action>> {
let mut actions = Vec::new(); let mut actions = Vec::new();
if let Some(node) = self.focusable_node_ids.get(&target) { for node_id in self.dispatch_path(target) {
for node_id in self.dispatch_path(*node) { let node = &self.nodes[node_id.0];
let node = &self.nodes[node_id.0]; for DispatchActionListener { action_type, .. } in &node.action_listeners {
for DispatchActionListener { action_type, .. } in &node.action_listeners { // Intentionally silence these errors without logging.
// Intentionally silence these errors without logging. // If an action cannot be built by default, it's not available.
// If an action cannot be built by default, it's not available. actions.extend(self.action_registry.build_action_type(action_type).ok());
actions.extend(self.action_registry.build_action_type(action_type).ok());
}
} }
} }
actions actions
@ -236,6 +234,11 @@ impl DispatchTree {
self.focusable_node_ids.get(&target).copied() self.focusable_node_ids.get(&target).copied()
} }
pub fn root_node_id(&self) -> DispatchNodeId {
debug_assert!(!self.nodes.is_empty());
DispatchNodeId(0)
}
fn active_node_id(&self) -> DispatchNodeId { fn active_node_id(&self) -> DispatchNodeId {
*self.node_stack.last().unwrap() *self.node_stack.last().unwrap()
} }

View file

@ -453,19 +453,21 @@ impl<'a> WindowContext<'a> {
} }
pub fn dispatch_action(&mut self, action: Box<dyn Action>) { pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
if let Some(focus_handle) = self.focused() { let focus_handle = self.focused();
self.defer(move |cx| {
if let Some(node_id) = cx self.defer(move |cx| {
.window let node_id = focus_handle
.current_frame .and_then(|handle| {
.dispatch_tree cx.window
.focusable_node_id(focus_handle.id) .current_frame
{ .dispatch_tree
cx.propagate_event = true; .focusable_node_id(handle.id)
cx.dispatch_action_on_node(node_id, action); })
} .unwrap_or_else(|| cx.window.current_frame.dispatch_tree.root_node_id());
})
} cx.propagate_event = true;
cx.dispatch_action_on_node(node_id, action);
})
} }
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
@ -1154,8 +1156,19 @@ impl<'a> WindowContext<'a> {
self.start_frame(); self.start_frame();
self.with_z_index(0, |cx| { self.with_z_index(0, |cx| {
let available_space = cx.window.viewport_size.map(Into::into); cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
root_view.draw(Point::zero(), available_space, cx); for (action_type, action_listeners) in &cx.app.global_action_listeners {
for action_listener in action_listeners.iter().cloned() {
cx.window.current_frame.dispatch_tree.on_action(
*action_type,
Rc::new(move |action, phase, cx| action_listener(action, phase, cx)),
)
}
}
let available_space = cx.window.viewport_size.map(Into::into);
root_view.draw(Point::zero(), available_space, cx);
})
}); });
if let Some(active_drag) = self.app.active_drag.take() { if let Some(active_drag) = self.app.active_drag.take() {
@ -1338,75 +1351,79 @@ impl<'a> WindowContext<'a> {
} }
fn dispatch_key_event(&mut self, event: &dyn Any) { fn dispatch_key_event(&mut self, event: &dyn Any) {
if let Some(node_id) = self.window.focus.and_then(|focus_id| { let node_id = self
self.window .window
.current_frame .focus
.dispatch_tree .and_then(|focus_id| {
.focusable_node_id(focus_id) self.window
}) { .current_frame
let dispatch_path = self .dispatch_tree
.window .focusable_node_id(focus_id)
.current_frame })
.dispatch_tree .unwrap_or_else(|| self.window.current_frame.dispatch_tree.root_node_id());
.dispatch_path(node_id);
let mut actions: Vec<Box<dyn Action>> = Vec::new(); let dispatch_path = self
.window
.current_frame
.dispatch_tree
.dispatch_path(node_id);
// Capture phase let mut actions: Vec<Box<dyn Action>> = Vec::new();
let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
self.propagate_event = true;
for node_id in &dispatch_path { // Capture phase
let node = self.window.current_frame.dispatch_tree.node(*node_id); let mut context_stack: SmallVec<[KeyContext; 16]> = SmallVec::new();
self.propagate_event = true;
if !node.context.is_empty() { for node_id in &dispatch_path {
context_stack.push(node.context.clone()); let node = self.window.current_frame.dispatch_tree.node(*node_id);
}
for key_listener in node.key_listeners.clone() { if !node.context.is_empty() {
key_listener(event, DispatchPhase::Capture, self); context_stack.push(node.context.clone());
if !self.propagate_event {
return;
}
}
} }
// Bubble phase for key_listener in node.key_listeners.clone() {
for node_id in dispatch_path.iter().rev() { key_listener(event, DispatchPhase::Capture, self);
// Handle low level key events
let node = self.window.current_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Bubble, self);
if !self.propagate_event {
return;
}
}
// Match keystrokes
let node = self.window.current_frame.dispatch_tree.node(*node_id);
if !node.context.is_empty() {
if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
if let Some(found) = self
.window
.current_frame
.dispatch_tree
.dispatch_key(&key_down_event.keystroke, &context_stack)
{
actions.push(found.boxed_clone())
}
}
context_stack.pop();
}
}
for action in actions {
self.dispatch_action_on_node(node_id, action);
if !self.propagate_event { if !self.propagate_event {
return; return;
} }
} }
} }
// Bubble phase
for node_id in dispatch_path.iter().rev() {
// Handle low level key events
let node = self.window.current_frame.dispatch_tree.node(*node_id);
for key_listener in node.key_listeners.clone() {
key_listener(event, DispatchPhase::Bubble, self);
if !self.propagate_event {
return;
}
}
// Match keystrokes
let node = self.window.current_frame.dispatch_tree.node(*node_id);
if !node.context.is_empty() {
if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
if let Some(found) = self
.window
.current_frame
.dispatch_tree
.dispatch_key(&key_down_event.keystroke, &context_stack)
{
actions.push(found.boxed_clone())
}
}
context_stack.pop();
}
}
for action in actions {
self.dispatch_action_on_node(node_id, action);
if !self.propagate_event {
return;
}
}
} }
fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) { fn dispatch_action_on_node(&mut self, node_id: DispatchNodeId, action: Box<dyn Action>) {
@ -1490,22 +1507,21 @@ impl<'a> WindowContext<'a> {
} }
pub fn available_actions(&self) -> Vec<Box<dyn Action>> { pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
if let Some(focus_id) = self.window.focus { let node_id = self
let mut actions = self .window
.window .focus
.current_frame .and_then(|focus_id| {
.dispatch_tree self.window
.available_actions(focus_id); .current_frame
actions.extend( .dispatch_tree
self.app .focusable_node_id(focus_id)
.global_action_listeners })
.keys() .unwrap_or_else(|| self.window.current_frame.dispatch_tree.root_node_id());
.filter_map(|type_id| self.app.actions.build_action_type(type_id).ok()),
); self.window
actions .current_frame
} else { .dispatch_tree
Vec::new() .available_actions(node_id)
}
} }
pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> { pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
@ -1561,7 +1577,7 @@ impl<'a> WindowContext<'a> {
//========== ELEMENT RELATED FUNCTIONS =========== //========== ELEMENT RELATED FUNCTIONS ===========
pub fn with_key_dispatch<R>( pub fn with_key_dispatch<R>(
&mut self, &mut self,
context: KeyContext, context: Option<KeyContext>,
focus_handle: Option<FocusHandle>, focus_handle: Option<FocusHandle>,
f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R, f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
) -> R { ) -> R {