Reuse mouse and keyboard listeners when reusing geometry for a view

This commit is contained in:
Antonio Scandurra 2024-01-09 12:37:24 +01:00
parent c9193b586b
commit f55870f378
3 changed files with 131 additions and 66 deletions

View file

@ -1,12 +1,13 @@
use crate::{ use crate::{
arena::ArenaRef, Action, ActionRegistry, DispatchPhase, FocusId, KeyBinding, KeyContext, Action, ActionRegistry, DispatchPhase, EntityId, FocusId, KeyBinding, KeyContext, KeyMatch,
KeyMatch, Keymap, Keystroke, KeystrokeMatcher, WindowContext, Keymap, Keystroke, KeystrokeMatcher, WindowContext,
}; };
use collections::HashMap; use collections::FxHashMap;
use parking_lot::Mutex; use parking_lot::Mutex;
use smallvec::SmallVec; use smallvec::SmallVec;
use std::{ use std::{
any::{Any, TypeId}, any::{Any, TypeId},
mem,
rc::Rc, rc::Rc,
sync::Arc, sync::Arc,
}; };
@ -18,8 +19,9 @@ pub(crate) struct DispatchTree {
node_stack: Vec<DispatchNodeId>, node_stack: Vec<DispatchNodeId>,
pub(crate) context_stack: Vec<KeyContext>, pub(crate) context_stack: Vec<KeyContext>,
nodes: Vec<DispatchNode>, nodes: Vec<DispatchNode>,
focusable_node_ids: HashMap<FocusId, DispatchNodeId>, focusable_node_ids: FxHashMap<FocusId, DispatchNodeId>,
keystroke_matchers: HashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>, view_node_ids: FxHashMap<EntityId, DispatchNodeId>,
keystroke_matchers: FxHashMap<SmallVec<[KeyContext; 4]>, KeystrokeMatcher>,
keymap: Arc<Mutex<Keymap>>, keymap: Arc<Mutex<Keymap>>,
action_registry: Rc<ActionRegistry>, action_registry: Rc<ActionRegistry>,
} }
@ -30,15 +32,16 @@ pub(crate) struct DispatchNode {
pub action_listeners: Vec<DispatchActionListener>, pub action_listeners: Vec<DispatchActionListener>,
pub context: Option<KeyContext>, pub context: Option<KeyContext>,
focus_id: Option<FocusId>, focus_id: Option<FocusId>,
view_id: Option<EntityId>,
parent: Option<DispatchNodeId>, parent: Option<DispatchNodeId>,
} }
type KeyListener = ArenaRef<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>; type KeyListener = Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>;
#[derive(Clone)] #[derive(Clone)]
pub(crate) struct DispatchActionListener { pub(crate) struct DispatchActionListener {
pub(crate) action_type: TypeId, pub(crate) action_type: TypeId,
pub(crate) listener: ArenaRef<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>, pub(crate) listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
} }
impl DispatchTree { impl DispatchTree {
@ -47,8 +50,9 @@ impl DispatchTree {
node_stack: Vec::new(), node_stack: Vec::new(),
context_stack: Vec::new(), context_stack: Vec::new(),
nodes: Vec::new(), nodes: Vec::new(),
focusable_node_ids: HashMap::default(), focusable_node_ids: FxHashMap::default(),
keystroke_matchers: HashMap::default(), view_node_ids: FxHashMap::default(),
keystroke_matchers: FxHashMap::default(),
keymap, keymap,
action_registry, action_registry,
} }
@ -59,6 +63,7 @@ impl DispatchTree {
self.nodes.clear(); self.nodes.clear();
self.context_stack.clear(); self.context_stack.clear();
self.focusable_node_ids.clear(); self.focusable_node_ids.clear();
self.view_node_ids.clear();
self.keystroke_matchers.clear(); self.keystroke_matchers.clear();
} }
@ -83,6 +88,56 @@ impl DispatchTree {
} }
} }
fn move_node(&mut self, source_node: &mut DispatchNode) {
self.push_node(source_node.context.take());
if let Some(focus_id) = source_node.focus_id {
self.make_focusable(focus_id);
}
if let Some(view_id) = source_node.view_id {
self.associate_view(view_id);
}
let target_node = self.active_node();
target_node.key_listeners = mem::take(&mut source_node.key_listeners);
target_node.action_listeners = mem::take(&mut source_node.action_listeners);
}
pub fn graft(&mut self, view_id: EntityId, source: &mut Self) {
let view_source_node_id = source
.view_node_ids
.get(&view_id)
.expect("view should exist in previous dispatch tree");
let view_source_node = &mut source.nodes[view_source_node_id.0];
self.move_node(view_source_node);
let mut source_stack = vec![*view_source_node_id];
for (source_node_id, source_node) in source
.nodes
.iter_mut()
.enumerate()
.skip(view_source_node_id.0 + 1)
{
let source_node_id = DispatchNodeId(source_node_id);
while let Some(source_ancestor) = source_stack.last() {
if source_node.parent != Some(*source_ancestor) {
source_stack.pop();
self.pop_node();
}
}
if source_stack.is_empty() {
break;
} else {
source_stack.push(source_node_id);
self.move_node(source_node);
}
}
while !source_stack.is_empty() {
self.pop_node();
}
}
pub fn clear_pending_keystrokes(&mut self) { pub fn clear_pending_keystrokes(&mut self) {
self.keystroke_matchers.clear(); self.keystroke_matchers.clear();
} }
@ -117,7 +172,7 @@ impl DispatchTree {
pub fn on_action( pub fn on_action(
&mut self, &mut self,
action_type: TypeId, action_type: TypeId,
listener: ArenaRef<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>, listener: Rc<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext)>,
) { ) {
self.active_node() self.active_node()
.action_listeners .action_listeners
@ -133,6 +188,12 @@ impl DispatchTree {
self.focusable_node_ids.insert(focus_id, node_id); self.focusable_node_ids.insert(focus_id, node_id);
} }
pub fn associate_view(&mut self, view_id: EntityId) {
let node_id = self.active_node_id();
self.active_node().view_id = Some(view_id);
self.view_node_ids.insert(view_id, node_id);
}
pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool { pub fn focus_contains(&self, parent: FocusId, child: FocusId) -> bool {
if parent == child { if parent == child {
return true; return true;

View file

@ -285,7 +285,8 @@ impl Element for AnyView {
&& cache_key.text_style == cx.text_style() && cache_key.text_style == cx.text_style()
&& !cx.window.dirty_views.contains(&self.entity_id()) && !cx.window.dirty_views.contains(&self.entity_id())
{ {
println!("could reuse geometry for view {}", self.entity_id()); cx.reuse_geometry();
return;
} }
} }

View file

@ -1,8 +1,8 @@
use crate::{ use crate::{
px, size, transparent_black, Action, AnyDrag, AnyView, AppContext, Arena, ArenaBox, ArenaRef, px, size, transparent_black, Action, AnyDrag, AnyView, AppContext, Arena, AsyncWindowContext,
AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle, DevicePixels,
DevicePixels, DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
Entity, EntityId, EventEmitter, FileDropEvent, Flatten, FontId, GlobalElementId, GlyphId, Hsla, EntityId, EventEmitter, FileDropEvent, Flatten, FontId, GlobalElementId, GlyphId, Hsla,
ImageData, InputEvent, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeystrokeEvent, LayoutId, ImageData, InputEvent, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeystrokeEvent, LayoutId,
Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseMoveEvent, MouseUpEvent, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseMoveEvent, MouseUpEvent,
Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point,
@ -95,7 +95,7 @@ impl DispatchPhase {
} }
type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>; type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
type AnyMouseListener = ArenaBox<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>; type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>; type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
struct FocusEvent { struct FocusEvent {
@ -257,7 +257,6 @@ pub struct Window {
pub(crate) rendered_frame: Frame, pub(crate) rendered_frame: Frame,
pub(crate) next_frame: Frame, pub(crate) next_frame: Frame,
pub(crate) dirty_views: FxHashSet<EntityId>, pub(crate) dirty_views: FxHashSet<EntityId>,
frame_arena: Arena,
pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>, pub(crate) focus_handles: Arc<RwLock<SlotMap<FocusId, AtomicUsize>>>,
focus_listeners: SubscriberSet<(), AnyWindowFocusListener>, focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
blur_listeners: SubscriberSet<(), AnyObserver>, blur_listeners: SubscriberSet<(), AnyObserver>,
@ -288,7 +287,7 @@ pub(crate) struct ElementStateBox {
pub(crate) struct Frame { pub(crate) struct Frame {
focus: Option<FocusId>, focus: Option<FocusId>,
pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>, pub(crate) element_states: FxHashMap<GlobalElementId, ElementStateBox>,
mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, AnyMouseListener)>>, mouse_listeners: FxHashMap<TypeId, Vec<(StackingOrder, EntityId, AnyMouseListener)>>,
pub(crate) dispatch_tree: DispatchTree, pub(crate) dispatch_tree: DispatchTree,
pub(crate) scene_builder: SceneBuilder, pub(crate) scene_builder: SceneBuilder,
pub(crate) depth_map: Vec<(StackingOrder, Bounds<Pixels>)>, pub(crate) depth_map: Vec<(StackingOrder, Bounds<Pixels>)>,
@ -298,6 +297,7 @@ pub(crate) struct Frame {
element_offset_stack: Vec<Point<Pixels>>, element_offset_stack: Vec<Point<Pixels>>,
pub(crate) view_parents: FxHashMap<EntityId, EntityId>, pub(crate) view_parents: FxHashMap<EntityId, EntityId>,
pub(crate) view_stack: Vec<EntityId>, pub(crate) view_stack: Vec<EntityId>,
pub(crate) reused_views: FxHashSet<EntityId>,
} }
impl Frame { impl Frame {
@ -315,6 +315,7 @@ impl Frame {
element_offset_stack: Vec::new(), element_offset_stack: Vec::new(),
view_parents: FxHashMap::default(), view_parents: FxHashMap::default(),
view_stack: Vec::new(), view_stack: Vec::new(),
reused_views: FxHashSet::default(),
} }
} }
@ -326,6 +327,7 @@ impl Frame {
self.next_stacking_order_id = 0; self.next_stacking_order_id = 0;
self.view_parents.clear(); self.view_parents.clear();
debug_assert!(self.view_stack.is_empty()); debug_assert!(self.view_stack.is_empty());
self.reused_views.clear();
} }
fn focus_path(&self) -> SmallVec<[FocusId; 8]> { fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
@ -412,7 +414,6 @@ impl Window {
rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())), rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())), next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
dirty_views: FxHashSet::default(), dirty_views: FxHashSet::default(),
frame_arena: Arena::new(1024 * 1024),
focus_handles: Arc::new(RwLock::new(SlotMap::with_key())), focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
focus_listeners: SubscriberSet::new(), focus_listeners: SubscriberSet::new(),
blur_listeners: SubscriberSet::new(), blur_listeners: SubscriberSet::new(),
@ -886,21 +887,21 @@ impl<'a> WindowContext<'a> {
mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static, mut handler: impl FnMut(&Event, DispatchPhase, &mut WindowContext) + 'static,
) { ) {
let order = self.window.next_frame.z_index_stack.clone(); let order = self.window.next_frame.z_index_stack.clone();
let handler = self let view_id = *self.window.next_frame.view_stack.last().unwrap();
.window
.frame_arena
.alloc(|| {
move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
handler(event.downcast_ref().unwrap(), phase, cx)
}
})
.map(|handler| handler as _);
self.window self.window
.next_frame .next_frame
.mouse_listeners .mouse_listeners
.entry(TypeId::of::<Event>()) .entry(TypeId::of::<Event>())
.or_default() .or_default()
.push((order, handler)) .push((
order,
view_id,
Box::new(
move |event: &dyn Any, phase: DispatchPhase, cx: &mut WindowContext<'_>| {
handler(event.downcast_ref().unwrap(), phase, cx)
},
),
))
} }
/// Register a key event listener on the window for the next frame. The type of event /// Register a key event listener on the window for the next frame. The type of event
@ -913,21 +914,13 @@ impl<'a> WindowContext<'a> {
&mut self, &mut self,
listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static, listener: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
) { ) {
let listener = self self.window.next_frame.dispatch_tree.on_key_event(Rc::new(
.window
.frame_arena
.alloc(|| {
move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| { move |event: &dyn Any, phase, cx: &mut WindowContext<'_>| {
if let Some(event) = event.downcast_ref::<Event>() { if let Some(event) = event.downcast_ref::<Event>() {
listener(event, phase, cx) listener(event, phase, cx)
} }
} },
}) ));
.map(|handler| handler as _);
self.window
.next_frame
.dispatch_tree
.on_key_event(ArenaRef::from(listener));
} }
/// Register an action listener on the window for the next frame. The type of action /// Register an action listener on the window for the next frame. The type of action
@ -941,15 +934,10 @@ impl<'a> WindowContext<'a> {
action_type: TypeId, action_type: TypeId,
listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static, listener: impl Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static,
) { ) {
let listener = self
.window
.frame_arena
.alloc(|| listener)
.map(|handler| handler as _);
self.window self.window
.next_frame .next_frame
.dispatch_tree .dispatch_tree
.on_action(action_type, ArenaRef::from(listener)); .on_action(action_type, Rc::new(listener));
} }
pub fn is_action_available(&self, action: &dyn Action) -> bool { pub fn is_action_available(&self, action: &dyn Action) -> bool {
@ -1327,6 +1315,16 @@ impl<'a> WindowContext<'a> {
); );
} }
pub(crate) fn reuse_geometry(&mut self) {
let window = &mut self.window;
let view_id = *window.next_frame.view_stack.last().unwrap();
assert!(window.next_frame.reused_views.insert(view_id));
window
.next_frame
.dispatch_tree
.graft(view_id, &mut window.rendered_frame.dispatch_tree)
}
/// Draw pixels to the display for this window based on the contents of its scene. /// Draw pixels to the display for this window based on the contents of its scene.
pub(crate) fn draw(&mut self) -> Scene { pub(crate) fn draw(&mut self) -> Scene {
println!("====================="); println!("=====================");
@ -1342,26 +1340,18 @@ impl<'a> WindowContext<'a> {
self.window.platform_window.clear_input_handler(); self.window.platform_window.clear_input_handler();
self.window.layout_engine.as_mut().unwrap().clear(); self.window.layout_engine.as_mut().unwrap().clear();
self.window.next_frame.clear(); self.window.next_frame.clear();
self.window.frame_arena.clear();
let root_view = self.window.root_view.take().unwrap(); let root_view = self.window.root_view.take().unwrap();
self.with_z_index(0, |cx| { self.with_z_index(0, |cx| {
cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| { cx.with_key_dispatch(Some(KeyContext::default()), None, |_, cx| {
for (action_type, action_listeners) in &cx.app.global_action_listeners { for (action_type, action_listeners) in &cx.app.global_action_listeners {
for action_listener in action_listeners.iter().cloned() { for action_listener in action_listeners.iter().cloned() {
let listener = cx cx.window.next_frame.dispatch_tree.on_action(
.window *action_type,
.frame_arena Rc::new(move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
.alloc(|| {
move |action: &dyn Any, phase, cx: &mut WindowContext<'_>| {
action_listener(action, phase, cx) action_listener(action, phase, cx)
} }),
}) )
.map(|listener| listener as _);
cx.window
.next_frame
.dispatch_tree
.on_action(*action_type, ArenaRef::from(listener))
} }
} }
@ -1395,6 +1385,19 @@ impl<'a> WindowContext<'a> {
); );
self.window.next_frame.focus = self.window.focus; self.window.next_frame.focus = self.window.focus;
self.window.root_view = Some(root_view); self.window.root_view = Some(root_view);
for (type_id, listeners) in &mut self.window.rendered_frame.mouse_listeners {
let next_listeners = self
.window
.next_frame
.mouse_listeners
.entry(*type_id)
.or_default();
for (order, view_id, listener) in listeners.drain(..) {
if self.window.next_frame.reused_views.contains(&view_id) {
next_listeners.push((order, view_id, listener));
}
}
}
let previous_focus_path = self.window.rendered_frame.focus_path(); let previous_focus_path = self.window.rendered_frame.focus_path();
mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame); mem::swap(&mut self.window.rendered_frame, &mut self.window.next_frame);
@ -1540,11 +1543,11 @@ impl<'a> WindowContext<'a> {
.remove(&event.type_id()) .remove(&event.type_id())
{ {
// Because handlers may add other handlers, we sort every time. // Because handlers may add other handlers, we sort every time.
handlers.sort_by(|(a, _), (b, _)| a.cmp(b)); handlers.sort_by(|(a, _, _), (b, _, _)| a.cmp(b));
// Capture phase, events bubble from back to front. Handlers for this phase are used for // Capture phase, events bubble from back to front. Handlers for this phase are used for
// special purposes, such as detecting events outside of a given Bounds. // special purposes, such as detecting events outside of a given Bounds.
for (_, handler) in &mut handlers { for (_, _, handler) in &mut handlers {
handler(event, DispatchPhase::Capture, self); handler(event, DispatchPhase::Capture, self);
if !self.app.propagate_event { if !self.app.propagate_event {
break; break;
@ -1553,7 +1556,7 @@ impl<'a> WindowContext<'a> {
// Bubble phase, where most normal handlers do their work. // Bubble phase, where most normal handlers do their work.
if self.app.propagate_event { if self.app.propagate_event {
for (_, handler) in handlers.iter_mut().rev() { for (_, _, handler) in handlers.iter_mut().rev() {
handler(event, DispatchPhase::Bubble, self); handler(event, DispatchPhase::Bubble, self);
if !self.app.propagate_event { if !self.app.propagate_event {
break; break;