This commit is contained in:
Nathan Sobo 2023-11-10 14:47:45 -07:00
parent 74a0d9316a
commit 7eaba8fabc
20 changed files with 908 additions and 1151 deletions

View file

@ -1,15 +1,14 @@
use crate::{
build_action_from_type, px, size, Action, AnyBox, AnyDrag, AnyView, AppContext,
AsyncWindowContext, AvailableSpace, Bounds, BoxShadow, Context, Corners, CursorStyle,
DevicePixels, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent,
FocusEvent, FontId, GlobalElementId, GlyphId, Hsla, ImageData, InputEvent, IsZero,
KeyBindingContext, KeyListener, KeyMatch, Keystroke, KeystrokeMatcher, LayoutId, Model,
ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent,
MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler,
PlatformWindow, Point, PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams,
RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder, Shadow, SharedString, Size,
Style, SubscriberSet, Subscription, TaffyLayoutEngine, Task, Underline, UnderlineStyle, View,
VisualContext, WeakView, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
px, size, Action, AnyBox, AnyDrag, AnyView, AppContext, AsyncWindowContext, AvailableSpace,
Bounds, BoxShadow, Context, Corners, CursorStyle, DevicePixels, DisplayId, Edges, Effect,
Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId,
Hsla, ImageData, InputEvent, IsZero, KeyContext, KeyDispatcher, LayoutId, Model, ModelContext,
Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path,
Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point,
PolychromeSprite, PromptLevel, Quad, Render, RenderGlyphParams, RenderImageParams,
RenderSvgParams, ScaledPixels, SceneBuilder, Shadow, SharedString, Size, Style, SubscriberSet,
Subscription, TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext,
WeakView, WindowBounds, WindowOptions, SUBPIXEL_VARIANTS,
};
use anyhow::{anyhow, Result};
use collections::HashMap;
@ -60,16 +59,7 @@ pub enum DispatchPhase {
}
type AnyObserver = Box<dyn FnMut(&mut WindowContext) -> bool + 'static>;
type AnyListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
type AnyKeyListener = Box<
dyn Fn(
&dyn Any,
&[&KeyBindingContext],
DispatchPhase,
&mut WindowContext,
) -> Option<Box<dyn Action>>
+ 'static,
>;
type AnyMouseListener = Box<dyn FnMut(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + 'static>;
type AnyWindowFocusListener = Box<dyn FnMut(&FocusEvent, &mut WindowContext) -> bool + 'static>;
@ -97,20 +87,12 @@ impl FocusId {
/// Obtains whether this handle contains the given handle in the most recently rendered frame.
pub(crate) fn contains(&self, other: Self, cx: &WindowContext) -> bool {
let mut ancestor = Some(other);
while let Some(ancestor_id) = ancestor {
if *self == ancestor_id {
return true;
} else {
ancestor = cx
.window
.current_frame
.focus_parents_by_child
.get(&ancestor_id)
.copied();
}
}
false
cx.window
.current_frame
.key_dispatcher
.as_ref()
.unwrap()
.focus_contains(*self, other)
}
}
@ -227,20 +209,31 @@ pub struct Window {
pub(crate) focus: Option<FocusId>,
}
#[derive(Default)]
// #[derive(Default)]
pub(crate) struct Frame {
element_states: HashMap<GlobalElementId, AnyBox>,
key_matchers: HashMap<GlobalElementId, KeystrokeMatcher>,
mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyListener)>>,
mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyMouseListener)>>,
pub(crate) key_dispatcher: Option<KeyDispatcher>,
pub(crate) focus_listeners: Vec<AnyFocusListener>,
pub(crate) key_dispatch_stack: Vec<KeyDispatchStackFrame>,
freeze_key_dispatch_stack: bool,
focus_parents_by_child: HashMap<FocusId, FocusId>,
pub(crate) scene_builder: SceneBuilder,
z_index_stack: StackingOrder,
content_mask_stack: Vec<ContentMask<Pixels>>,
element_offset_stack: Vec<Point<Pixels>>,
focus_stack: Vec<FocusId>,
}
impl Frame {
pub fn new(key_dispatcher: KeyDispatcher) -> Self {
Frame {
element_states: HashMap::default(),
mouse_listeners: HashMap::default(),
key_dispatcher: Some(key_dispatcher),
focus_listeners: Vec::new(),
scene_builder: SceneBuilder::default(),
z_index_stack: StackingOrder::default(),
content_mask_stack: Vec::new(),
element_offset_stack: Vec::new(),
}
}
}
impl Window {
@ -309,8 +302,8 @@ impl Window {
layout_engine: TaffyLayoutEngine::new(),
root_view: None,
element_id_stack: GlobalElementId::default(),
previous_frame: Frame::default(),
current_frame: Frame::default(),
previous_frame: Frame::new(KeyDispatcher::new(cx.keymap.clone())),
current_frame: Frame::new(KeyDispatcher::new(cx.keymap.clone())),
focus_handles: Arc::new(RwLock::new(SlotMap::with_key())),
focus_listeners: SubscriberSet::new(),
default_prevented: true,
@ -328,18 +321,6 @@ impl Window {
}
}
/// When constructing the element tree, we maintain a stack of key dispatch frames until we
/// find the focused element. We interleave key listeners with dispatch contexts so we can use the
/// contexts when matching key events against the keymap. A key listener can be either an action
/// handler or a [KeyDown] / [KeyUp] event listener.
pub(crate) enum KeyDispatchStackFrame {
Listener {
event_type: TypeId,
listener: AnyKeyListener,
},
Context(KeyBindingContext),
}
/// Indicates which region of the window is visible. Content falling outside of this mask will not be
/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
/// to leave room to support more complex shapes in the future.
@ -407,7 +388,9 @@ impl<'a> WindowContext<'a> {
/// Move focus to the element associated with the given `FocusHandle`.
pub fn focus(&mut self, handle: &FocusHandle) {
if self.window.focus == Some(handle.id) {
let focus_id = handle.id;
if self.window.focus == Some(focus_id) {
return;
}
@ -415,13 +398,10 @@ impl<'a> WindowContext<'a> {
self.window.last_blur = Some(self.window.focus);
}
self.window.focus = Some(handle.id);
// self.window.current_frame.key_dispatch_stack.clear()
// self.window.root_view.initialize()
self.window.focus = Some(focus_id);
self.app.push_effect(Effect::FocusChanged {
window_handle: self.window.handle,
focused: Some(handle.id),
focused: Some(focus_id),
});
self.notify();
}
@ -441,11 +421,13 @@ impl<'a> WindowContext<'a> {
}
pub fn dispatch_action(&mut self, action: Box<dyn Action>) {
self.defer(|cx| {
cx.app.propagate_event = true;
let stack = cx.dispatch_stack();
cx.dispatch_action_internal(action, &stack[..])
})
if let Some(focus_handle) = self.focused() {
self.defer(move |cx| {
let dispatcher = cx.window.current_frame.key_dispatcher.take().unwrap();
dispatcher.dispatch_action(focus_handle.id, action, cx);
cx.window.current_frame.key_dispatcher = Some(dispatcher);
})
}
}
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
@ -1079,26 +1061,6 @@ impl<'a> WindowContext<'a> {
self.window.dirty = false;
}
pub(crate) fn dispatch_stack(&mut self) -> Vec<KeyDispatchStackFrame> {
let root_view = self.window.root_view.take().unwrap();
let window = &mut *self.window;
let mut spare_frame = Frame::default();
mem::swap(&mut spare_frame, &mut window.previous_frame);
self.start_frame();
root_view.draw_dispatch_stack(self);
let window = &mut *self.window;
// restore the old values of current and previous frame,
// putting the new frame into spare_frame.
mem::swap(&mut window.current_frame, &mut window.previous_frame);
mem::swap(&mut spare_frame, &mut window.previous_frame);
self.window.root_view = Some(root_view);
spare_frame.key_dispatch_stack
}
/// Rotate the current frame and the previous frame, then clear the current frame.
/// We repopulate all state in the current frame during each paint.
fn start_frame(&mut self) {
@ -1110,12 +1072,9 @@ impl<'a> WindowContext<'a> {
mem::swap(&mut window.previous_frame, &mut window.current_frame);
let frame = &mut window.current_frame;
frame.element_states.clear();
frame.key_matchers.clear();
frame.mouse_listeners.values_mut().for_each(Vec::clear);
frame.focus_listeners.clear();
frame.key_dispatch_stack.clear();
frame.focus_parents_by_child.clear();
frame.freeze_key_dispatch_stack = false;
frame.key_dispatcher.as_mut().map(KeyDispatcher::clear);
}
/// Dispatch a mouse or keyboard event on the window.
@ -1226,99 +1185,16 @@ impl<'a> WindowContext<'a> {
.insert(any_mouse_event.type_id(), handlers);
}
} else if let Some(any_key_event) = event.keyboard_event() {
let key_dispatch_stack = mem::take(&mut self.window.current_frame.key_dispatch_stack);
let key_event_type = any_key_event.type_id();
let mut context_stack = SmallVec::<[&KeyBindingContext; 16]>::new();
for (ix, frame) in key_dispatch_stack.iter().enumerate() {
match frame {
KeyDispatchStackFrame::Listener {
event_type,
listener,
} => {
if key_event_type == *event_type {
if let Some(action) = listener(
any_key_event,
&context_stack,
DispatchPhase::Capture,
self,
) {
self.dispatch_action_internal(action, &key_dispatch_stack[..ix]);
}
if !self.app.propagate_event {
break;
}
}
}
KeyDispatchStackFrame::Context(context) => {
context_stack.push(&context);
}
}
if let Some(focus_id) = self.window.focus {
let mut dispatcher = self.window.current_frame.key_dispatcher.take().unwrap();
dispatcher.dispatch_key(focus_id, any_key_event, self);
self.window.current_frame.key_dispatcher = Some(dispatcher);
}
if self.app.propagate_event {
for (ix, frame) in key_dispatch_stack.iter().enumerate().rev() {
match frame {
KeyDispatchStackFrame::Listener {
event_type,
listener,
} => {
if key_event_type == *event_type {
if let Some(action) = listener(
any_key_event,
&context_stack,
DispatchPhase::Bubble,
self,
) {
self.dispatch_action_internal(
action,
&key_dispatch_stack[..ix],
);
}
if !self.app.propagate_event {
break;
}
}
}
KeyDispatchStackFrame::Context(_) => {
context_stack.pop();
}
}
}
}
drop(context_stack);
self.window.current_frame.key_dispatch_stack = key_dispatch_stack;
}
!self.app.propagate_event
}
/// Attempt to map a keystroke to an action based on the keymap.
pub fn match_keystroke(
&mut self,
element_id: &GlobalElementId,
keystroke: &Keystroke,
context_stack: &[KeyBindingContext],
) -> KeyMatch {
let key_match = self
.window
.current_frame
.key_matchers
.get_mut(element_id)
.unwrap()
.match_keystroke(keystroke, context_stack);
if key_match.is_some() {
for matcher in self.window.current_frame.key_matchers.values_mut() {
matcher.clear_pending();
}
}
key_match
}
/// Register the given handler to be invoked whenever the global of the given type
/// is updated.
pub fn observe_global<G: 'static>(
@ -1345,105 +1221,16 @@ impl<'a> WindowContext<'a> {
self.window.platform_window.prompt(level, msg, answers)
}
pub fn available_actions(&self) -> impl Iterator<Item = Box<dyn Action>> + '_ {
let key_dispatch_stack = &self.window.previous_frame.key_dispatch_stack;
key_dispatch_stack.iter().filter_map(|frame| {
match frame {
// todo!factor out a KeyDispatchStackFrame::Action
KeyDispatchStackFrame::Listener {
event_type,
listener: _,
} => {
match build_action_from_type(event_type) {
Ok(action) => Some(action),
Err(err) => {
dbg!(err);
None
} // we'll hit his if TypeId == KeyDown
}
}
KeyDispatchStackFrame::Context(_) => None,
}
})
}
pub(crate) fn dispatch_action_internal(
&mut self,
action: Box<dyn Action>,
dispatch_stack: &[KeyDispatchStackFrame],
) {
let action_type = action.as_any().type_id();
if let Some(mut global_listeners) = self.app.global_action_listeners.remove(&action_type) {
for listener in &global_listeners {
listener(action.as_ref(), DispatchPhase::Capture, self);
if !self.app.propagate_event {
break;
}
}
global_listeners.extend(
self.global_action_listeners
.remove(&action_type)
.unwrap_or_default(),
);
self.global_action_listeners
.insert(action_type, global_listeners);
}
if self.app.propagate_event {
for stack_frame in dispatch_stack {
if let KeyDispatchStackFrame::Listener {
event_type,
listener,
} = stack_frame
{
if action_type == *event_type {
listener(action.as_any(), &[], DispatchPhase::Capture, self);
if !self.app.propagate_event {
break;
}
}
}
}
}
if self.app.propagate_event {
for stack_frame in dispatch_stack.iter().rev() {
if let KeyDispatchStackFrame::Listener {
event_type,
listener,
} = stack_frame
{
if action_type == *event_type {
self.app.propagate_event = false;
listener(action.as_any(), &[], DispatchPhase::Bubble, self);
if !self.app.propagate_event {
break;
}
}
}
}
}
if self.app.propagate_event {
if let Some(mut global_listeners) =
self.app.global_action_listeners.remove(&action_type)
{
for listener in global_listeners.iter().rev() {
self.app.propagate_event = false;
listener(action.as_ref(), DispatchPhase::Bubble, self);
if !self.app.propagate_event {
break;
}
}
global_listeners.extend(
self.global_action_listeners
.remove(&action_type)
.unwrap_or_default(),
);
self.global_action_listeners
.insert(action_type, global_listeners);
}
pub fn available_actions(&self) -> Vec<Box<dyn Action>> {
if let Some(focus_id) = self.window.focus {
self.window
.current_frame
.key_dispatcher
.as_ref()
.unwrap()
.available_actions(focus_id)
} else {
Vec::new()
}
}
}
@ -1609,22 +1396,9 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
id: impl Into<ElementId>,
f: impl FnOnce(GlobalElementId, &mut Self) -> R,
) -> R {
let keymap = self.app_mut().keymap.clone();
let window = self.window_mut();
window.element_id_stack.push(id.into());
let global_id = window.element_id_stack.clone();
if window.current_frame.key_matchers.get(&global_id).is_none() {
window.current_frame.key_matchers.insert(
global_id.clone(),
window
.previous_frame
.key_matchers
.remove(&global_id)
.unwrap_or_else(|| KeystrokeMatcher::new(keymap)),
);
}
let result = f(global_id, self);
let window: &mut Window = self.borrow_mut();
window.element_id_stack.pop();
@ -2109,94 +1883,25 @@ impl<'a, V: 'static> ViewContext<'a, V> {
}));
}
pub fn with_key_listeners<R>(
pub fn with_key_dispatch<R>(
&mut self,
key_listeners: impl IntoIterator<Item = (TypeId, KeyListener<V>)>,
f: impl FnOnce(&mut Self) -> R,
context: KeyContext,
focus_handle: Option<FocusHandle>,
f: impl FnOnce(Option<FocusHandle>, &mut Self) -> R,
) -> R {
let old_stack_len = self.window.current_frame.key_dispatch_stack.len();
if !self.window.current_frame.freeze_key_dispatch_stack {
for (event_type, listener) in key_listeners {
let handle = self.view().downgrade();
let listener = Box::new(
move |event: &dyn Any,
context_stack: &[&KeyBindingContext],
phase: DispatchPhase,
cx: &mut WindowContext<'_>| {
handle
.update(cx, |view, cx| {
listener(view, event, context_stack, phase, cx)
})
.log_err()
.flatten()
},
);
self.window.current_frame.key_dispatch_stack.push(
KeyDispatchStackFrame::Listener {
event_type,
listener,
},
);
}
let mut old_dispatcher = self.window.previous_frame.key_dispatcher.take().unwrap();
let mut current_dispatcher = self.window.current_frame.key_dispatcher.take().unwrap();
current_dispatcher.push_node(context, &mut old_dispatcher);
if let Some(focus_handle) = focus_handle.as_ref() {
current_dispatcher.make_focusable(focus_handle.id);
}
let result = f(focus_handle, self);
current_dispatcher.pop_node();
let result = f(self);
self.window.previous_frame.key_dispatcher = Some(old_dispatcher);
self.window.current_frame.key_dispatcher = Some(current_dispatcher);
if !self.window.current_frame.freeze_key_dispatch_stack {
self.window
.current_frame
.key_dispatch_stack
.truncate(old_stack_len);
}
result
}
pub fn with_key_dispatch_context<R>(
&mut self,
context: KeyBindingContext,
f: impl FnOnce(&mut Self) -> R,
) -> R {
if context.is_empty() {
return f(self);
}
if !self.window.current_frame.freeze_key_dispatch_stack {
self.window
.current_frame
.key_dispatch_stack
.push(KeyDispatchStackFrame::Context(context));
}
let result = f(self);
if !self.window.previous_frame.freeze_key_dispatch_stack {
self.window.previous_frame.key_dispatch_stack.pop();
}
result
}
pub fn with_focus<R>(
&mut self,
focus_handle: FocusHandle,
f: impl FnOnce(&mut Self) -> R,
) -> R {
if let Some(parent_focus_id) = self.window.current_frame.focus_stack.last().copied() {
self.window
.current_frame
.focus_parents_by_child
.insert(focus_handle.id, parent_focus_id);
}
self.window.current_frame.focus_stack.push(focus_handle.id);
if Some(focus_handle.id) == self.window.focus {
self.window.current_frame.freeze_key_dispatch_stack = true;
}
let result = f(self);
self.window.current_frame.focus_stack.pop();
result
}