Merge branch 'main' into unborked-git-zed2-diagnostics-view
This commit is contained in:
@@ -54,6 +54,9 @@ pub trait Action: std::fmt::Debug + 'static {
|
||||
where
|
||||
Self: Sized;
|
||||
fn build(value: Option<serde_json::Value>) -> Result<Box<dyn Action>>
|
||||
where
|
||||
Self: Sized;
|
||||
fn is_registered() -> bool
|
||||
where
|
||||
Self: Sized;
|
||||
|
||||
@@ -88,6 +91,14 @@ where
|
||||
Ok(Box::new(action))
|
||||
}
|
||||
|
||||
fn is_registered() -> bool {
|
||||
ACTION_REGISTRY
|
||||
.read()
|
||||
.names_by_type_id
|
||||
.get(&TypeId::of::<A>())
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn partial_eq(&self, action: &dyn Action) -> bool {
|
||||
action
|
||||
.as_any()
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::{
|
||||
div, Action, AnyView, AnyWindowHandle, AppCell, AppContext, AsyncAppContext,
|
||||
BackgroundExecutor, Context, Div, EventEmitter, ForegroundExecutor, InputEvent, KeyDownEvent,
|
||||
Keystroke, Model, ModelContext, Render, Result, Task, TestDispatcher, TestPlatform, View,
|
||||
ViewContext, VisualContext, WindowContext, WindowHandle, WindowOptions,
|
||||
Keystroke, Model, ModelContext, Render, Result, Task, TestDispatcher, TestPlatform, TestWindow,
|
||||
View, ViewContext, VisualContext, WindowContext, WindowHandle, WindowOptions,
|
||||
};
|
||||
use anyhow::{anyhow, bail};
|
||||
use futures::{Stream, StreamExt};
|
||||
@@ -140,7 +140,7 @@ impl TestAppContext {
|
||||
.any_handle
|
||||
}
|
||||
|
||||
pub fn add_window_view<F, V>(&mut self, build_window: F) -> (View<V>, VisualTestContext)
|
||||
pub fn add_window_view<F, V>(&mut self, build_window: F) -> (View<V>, &mut VisualTestContext)
|
||||
where
|
||||
F: FnOnce(&mut ViewContext<V>) -> V,
|
||||
V: Render,
|
||||
@@ -149,7 +149,9 @@ impl TestAppContext {
|
||||
let window = cx.open_window(WindowOptions::default(), |cx| cx.build_view(build_window));
|
||||
drop(cx);
|
||||
let view = window.root_view(self).unwrap();
|
||||
(view, VisualTestContext::from_window(*window.deref(), self))
|
||||
let cx = Box::new(VisualTestContext::from_window(*window.deref(), self));
|
||||
// it might be nice to try and cleanup these at the end of each test.
|
||||
(view, Box::leak(cx))
|
||||
}
|
||||
|
||||
pub fn simulate_new_path_selection(
|
||||
@@ -220,7 +222,35 @@ impl TestAppContext {
|
||||
{
|
||||
window
|
||||
.update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
self.background_executor.run_until_parked()
|
||||
}
|
||||
|
||||
/// simulate_keystrokes takes a space-separated list of keys to type.
|
||||
/// cx.simulate_keystrokes("cmd-shift-p b k s p enter")
|
||||
/// will run backspace on the current editor through the command palette.
|
||||
pub fn simulate_keystrokes(&mut self, window: AnyWindowHandle, keystrokes: &str) {
|
||||
for keystroke in keystrokes
|
||||
.split(" ")
|
||||
.map(Keystroke::parse)
|
||||
.map(Result::unwrap)
|
||||
{
|
||||
self.dispatch_keystroke(window, keystroke.into(), false);
|
||||
}
|
||||
|
||||
self.background_executor.run_until_parked()
|
||||
}
|
||||
|
||||
/// simulate_input takes a string of text to type.
|
||||
/// cx.simulate_input("abc")
|
||||
/// will type abc into your current editor.
|
||||
pub fn simulate_input(&mut self, window: AnyWindowHandle, input: &str) {
|
||||
for keystroke in input.split("").map(Keystroke::parse).map(Result::unwrap) {
|
||||
self.dispatch_keystroke(window, keystroke.into(), false);
|
||||
}
|
||||
|
||||
self.background_executor.run_until_parked()
|
||||
}
|
||||
|
||||
pub fn dispatch_keystroke(
|
||||
@@ -229,15 +259,41 @@ impl TestAppContext {
|
||||
keystroke: Keystroke,
|
||||
is_held: bool,
|
||||
) {
|
||||
let keystroke2 = keystroke.clone();
|
||||
let handled = window
|
||||
.update(self, |_, cx| {
|
||||
cx.dispatch_event(InputEvent::KeyDown(KeyDownEvent { keystroke, is_held }))
|
||||
})
|
||||
.is_ok_and(|handled| handled);
|
||||
|
||||
if !handled {
|
||||
// todo!() simluate input here
|
||||
if handled {
|
||||
return;
|
||||
}
|
||||
|
||||
let input_handler = self.update_test_window(window, |window| window.input_handler.clone());
|
||||
let Some(input_handler) = input_handler else {
|
||||
panic!(
|
||||
"dispatch_keystroke {:?} failed to dispatch action or input",
|
||||
&keystroke2
|
||||
);
|
||||
};
|
||||
let text = keystroke2.ime_key.unwrap_or(keystroke2.key);
|
||||
input_handler.lock().replace_text_in_range(None, &text);
|
||||
}
|
||||
|
||||
pub fn update_test_window<R>(
|
||||
&mut self,
|
||||
window: AnyWindowHandle,
|
||||
f: impl FnOnce(&mut TestWindow) -> R,
|
||||
) -> R {
|
||||
window
|
||||
.update(self, |_, cx| {
|
||||
f(cx.window
|
||||
.platform_window
|
||||
.as_any_mut()
|
||||
.downcast_mut::<TestWindow>()
|
||||
.unwrap())
|
||||
})
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn notifications<T: 'static>(&mut self, entity: &Model<T>) -> impl Stream<Item = ()> {
|
||||
@@ -401,12 +457,24 @@ impl<'a> VisualTestContext<'a> {
|
||||
Self { cx, window }
|
||||
}
|
||||
|
||||
pub fn run_until_parked(&self) {
|
||||
self.cx.background_executor.run_until_parked();
|
||||
}
|
||||
|
||||
pub fn dispatch_action<A>(&mut self, action: A)
|
||||
where
|
||||
A: Action,
|
||||
{
|
||||
self.cx.dispatch_action(self.window, action)
|
||||
}
|
||||
|
||||
pub fn simulate_keystrokes(&mut self, keystrokes: &str) {
|
||||
self.cx.simulate_keystrokes(self.window, keystrokes)
|
||||
}
|
||||
|
||||
pub fn simulate_input(&mut self, input: &str) {
|
||||
self.cx.simulate_input(self.window, input)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Context for VisualTestContext<'a> {
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::{
|
||||
};
|
||||
use derive_more::{Deref, DerefMut};
|
||||
pub(crate) use smallvec::SmallVec;
|
||||
use std::{any::Any, mem};
|
||||
use std::{any::Any, fmt::Debug, mem};
|
||||
|
||||
pub trait Element<V: 'static> {
|
||||
type ElementState: 'static;
|
||||
@@ -33,6 +33,42 @@ pub trait Element<V: 'static> {
|
||||
element_state: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<V>,
|
||||
);
|
||||
|
||||
fn draw<T, R>(
|
||||
self,
|
||||
origin: Point<Pixels>,
|
||||
available_space: Size<T>,
|
||||
view_state: &mut V,
|
||||
cx: &mut ViewContext<V>,
|
||||
f: impl FnOnce(&Self::ElementState, &mut ViewContext<V>) -> R,
|
||||
) -> R
|
||||
where
|
||||
Self: Sized,
|
||||
T: Clone + Default + Debug + Into<AvailableSpace>,
|
||||
{
|
||||
let mut element = RenderedElement {
|
||||
element: self,
|
||||
phase: ElementRenderPhase::Start,
|
||||
};
|
||||
element.draw(origin, available_space.map(Into::into), view_state, cx);
|
||||
if let ElementRenderPhase::Painted { frame_state } = &element.phase {
|
||||
if let Some(frame_state) = frame_state.as_ref() {
|
||||
f(&frame_state, cx)
|
||||
} else {
|
||||
let element_id = element
|
||||
.element
|
||||
.element_id()
|
||||
.expect("we either have some frame_state or some element_id");
|
||||
cx.with_element_state(element_id, |element_state, cx| {
|
||||
let element_state = element_state.unwrap();
|
||||
let result = f(&element_state, cx);
|
||||
(result, element_state)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
unreachable!()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deref, DerefMut, Default, Clone, Debug, Eq, PartialEq, Hash)]
|
||||
@@ -100,7 +136,9 @@ enum ElementRenderPhase<V> {
|
||||
available_space: Size<AvailableSpace>,
|
||||
frame_state: Option<V>,
|
||||
},
|
||||
Painted,
|
||||
Painted {
|
||||
frame_state: Option<V>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Internal struct that wraps an element to store Layout and ElementState after the element is rendered.
|
||||
@@ -162,7 +200,7 @@ where
|
||||
ElementRenderPhase::Start => panic!("must call initialize before layout"),
|
||||
ElementRenderPhase::LayoutRequested { .. }
|
||||
| ElementRenderPhase::LayoutComputed { .. }
|
||||
| ElementRenderPhase::Painted => {
|
||||
| ElementRenderPhase::Painted { .. } => {
|
||||
panic!("element rendered twice")
|
||||
}
|
||||
};
|
||||
@@ -197,7 +235,7 @@ where
|
||||
self.element
|
||||
.paint(bounds, view_state, frame_state.as_mut().unwrap(), cx);
|
||||
}
|
||||
ElementRenderPhase::Painted
|
||||
ElementRenderPhase::Painted { frame_state }
|
||||
}
|
||||
|
||||
_ => panic!("must call layout before paint"),
|
||||
|
||||
@@ -6,15 +6,15 @@ use crate::{
|
||||
SharedString, Size, Style, StyleRefinement, Styled, Task, View, ViewContext, Visibility,
|
||||
};
|
||||
use collections::HashMap;
|
||||
use parking_lot::Mutex;
|
||||
use refineable::Refineable;
|
||||
use smallvec::SmallVec;
|
||||
use std::{
|
||||
any::{Any, TypeId},
|
||||
cell::RefCell,
|
||||
fmt::Debug,
|
||||
marker::PhantomData,
|
||||
mem,
|
||||
sync::Arc,
|
||||
rc::Rc,
|
||||
time::Duration,
|
||||
};
|
||||
use taffy::style::Overflow;
|
||||
@@ -229,6 +229,20 @@ pub trait InteractiveComponent<V: 'static>: Sized + Element<V> {
|
||||
mut self,
|
||||
listener: impl Fn(&mut V, &A, &mut ViewContext<V>) + 'static,
|
||||
) -> Self {
|
||||
// NOTE: this debug assert has the side-effect of working around
|
||||
// a bug where a crate consisting only of action definitions does
|
||||
// not register the actions in debug builds:
|
||||
//
|
||||
// https://github.com/rust-lang/rust/issues/47384
|
||||
// https://github.com/mmastrac/rust-ctor/issues/280
|
||||
//
|
||||
// if we are relying on this side-effect still, removing the debug_assert!
|
||||
// likely breaks the command_palette tests.
|
||||
debug_assert!(
|
||||
A::is_registered(),
|
||||
"{:?} is not registered as an action",
|
||||
A::qualified_name()
|
||||
);
|
||||
self.interactivity().action_listeners.push((
|
||||
TypeId::of::<A>(),
|
||||
Box::new(move |view, action, phase, cx| {
|
||||
@@ -406,7 +420,7 @@ pub trait StatefulInteractiveComponent<V: 'static, E: Element<V>>: InteractiveCo
|
||||
self.interactivity().tooltip_builder.is_none(),
|
||||
"calling tooltip more than once on the same element is not supported"
|
||||
);
|
||||
self.interactivity().tooltip_builder = Some(Arc::new(move |view_state, cx| {
|
||||
self.interactivity().tooltip_builder = Some(Rc::new(move |view_state, cx| {
|
||||
build_tooltip(view_state, cx).into()
|
||||
}));
|
||||
|
||||
@@ -555,7 +569,7 @@ type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
|
||||
|
||||
pub type HoverListener<V> = Box<dyn Fn(&mut V, bool, &mut ViewContext<V>) + 'static>;
|
||||
|
||||
pub type TooltipBuilder<V> = Arc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
|
||||
pub type TooltipBuilder<V> = Rc<dyn Fn(&mut V, &mut ViewContext<V>) -> AnyView + 'static>;
|
||||
|
||||
pub type KeyDownListener<V> =
|
||||
Box<dyn Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + 'static>;
|
||||
@@ -597,7 +611,7 @@ impl<V: 'static> ParentComponent<V> for Div<V> {
|
||||
}
|
||||
|
||||
impl<V: 'static> Element<V> for Div<V> {
|
||||
type ElementState = NodeState;
|
||||
type ElementState = DivState;
|
||||
|
||||
fn element_id(&self) -> Option<ElementId> {
|
||||
self.interactivity.element_id.clone()
|
||||
@@ -617,7 +631,7 @@ impl<V: 'static> Element<V> for Div<V> {
|
||||
child.initialize(view_state, cx);
|
||||
}
|
||||
|
||||
NodeState {
|
||||
DivState {
|
||||
interactive_state,
|
||||
child_layout_ids: SmallVec::new(),
|
||||
}
|
||||
@@ -706,11 +720,17 @@ impl<V: 'static> Component<V> for Div<V> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct NodeState {
|
||||
pub struct DivState {
|
||||
child_layout_ids: SmallVec<[LayoutId; 4]>,
|
||||
interactive_state: InteractiveElementState,
|
||||
}
|
||||
|
||||
impl DivState {
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.interactive_state.pending_mouse_down.borrow().is_some()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Interactivity<V> {
|
||||
pub element_id: Option<ElementId>,
|
||||
pub key_context: KeyContext,
|
||||
@@ -876,7 +896,7 @@ where
|
||||
|
||||
if !click_listeners.is_empty() || drag_listener.is_some() {
|
||||
let pending_mouse_down = element_state.pending_mouse_down.clone();
|
||||
let mouse_down = pending_mouse_down.lock().clone();
|
||||
let mouse_down = pending_mouse_down.borrow().clone();
|
||||
if let Some(mouse_down) = mouse_down {
|
||||
if let Some(drag_listener) = drag_listener {
|
||||
let active_state = element_state.clicked_state.clone();
|
||||
@@ -890,7 +910,7 @@ where
|
||||
&& bounds.contains_point(&event.position)
|
||||
&& (event.position - mouse_down.position).magnitude() > DRAG_THRESHOLD
|
||||
{
|
||||
*active_state.lock() = ElementClickedState::default();
|
||||
*active_state.borrow_mut() = ElementClickedState::default();
|
||||
let cursor_offset = event.position - bounds.origin;
|
||||
let drag = drag_listener(view_state, cursor_offset, cx);
|
||||
cx.active_drag = Some(drag);
|
||||
@@ -910,12 +930,14 @@ where
|
||||
listener(view_state, &mouse_click, cx);
|
||||
}
|
||||
}
|
||||
*pending_mouse_down.lock() = None;
|
||||
*pending_mouse_down.borrow_mut() = None;
|
||||
cx.notify();
|
||||
});
|
||||
} else {
|
||||
cx.on_mouse_event(move |_state, event: &MouseDownEvent, phase, _cx| {
|
||||
cx.on_mouse_event(move |_view_state, event: &MouseDownEvent, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
|
||||
*pending_mouse_down.lock() = Some(event.clone());
|
||||
*pending_mouse_down.borrow_mut() = Some(event.clone());
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -930,8 +952,8 @@ where
|
||||
return;
|
||||
}
|
||||
let is_hovered =
|
||||
bounds.contains_point(&event.position) && has_mouse_down.lock().is_none();
|
||||
let mut was_hovered = was_hovered.lock();
|
||||
bounds.contains_point(&event.position) && has_mouse_down.borrow().is_none();
|
||||
let mut was_hovered = was_hovered.borrow_mut();
|
||||
|
||||
if is_hovered != was_hovered.clone() {
|
||||
*was_hovered = is_hovered;
|
||||
@@ -952,13 +974,13 @@ where
|
||||
}
|
||||
|
||||
let is_hovered =
|
||||
bounds.contains_point(&event.position) && pending_mouse_down.lock().is_none();
|
||||
bounds.contains_point(&event.position) && pending_mouse_down.borrow().is_none();
|
||||
if !is_hovered {
|
||||
active_tooltip.lock().take();
|
||||
active_tooltip.borrow_mut().take();
|
||||
return;
|
||||
}
|
||||
|
||||
if active_tooltip.lock().is_none() {
|
||||
if active_tooltip.borrow().is_none() {
|
||||
let task = cx.spawn({
|
||||
let active_tooltip = active_tooltip.clone();
|
||||
let tooltip_builder = tooltip_builder.clone();
|
||||
@@ -966,7 +988,7 @@ where
|
||||
move |view, mut cx| async move {
|
||||
cx.background_executor().timer(TOOLTIP_DELAY).await;
|
||||
view.update(&mut cx, move |view_state, cx| {
|
||||
active_tooltip.lock().replace(ActiveTooltip {
|
||||
active_tooltip.borrow_mut().replace(ActiveTooltip {
|
||||
waiting: None,
|
||||
tooltip: Some(AnyTooltip {
|
||||
view: tooltip_builder(view_state, cx),
|
||||
@@ -978,14 +1000,14 @@ where
|
||||
.ok();
|
||||
}
|
||||
});
|
||||
active_tooltip.lock().replace(ActiveTooltip {
|
||||
active_tooltip.borrow_mut().replace(ActiveTooltip {
|
||||
waiting: Some(task),
|
||||
tooltip: None,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(active_tooltip) = element_state.active_tooltip.lock().as_ref() {
|
||||
if let Some(active_tooltip) = element_state.active_tooltip.borrow().as_ref() {
|
||||
if active_tooltip.tooltip.is_some() {
|
||||
cx.active_tooltip = active_tooltip.tooltip.clone()
|
||||
}
|
||||
@@ -993,10 +1015,10 @@ where
|
||||
}
|
||||
|
||||
let active_state = element_state.clicked_state.clone();
|
||||
if !active_state.lock().is_clicked() {
|
||||
if !active_state.borrow().is_clicked() {
|
||||
cx.on_mouse_event(move |_, _: &MouseUpEvent, phase, cx| {
|
||||
if phase == DispatchPhase::Capture {
|
||||
*active_state.lock() = ElementClickedState::default();
|
||||
*active_state.borrow_mut() = ElementClickedState::default();
|
||||
cx.notify();
|
||||
}
|
||||
});
|
||||
@@ -1011,7 +1033,7 @@ where
|
||||
.map_or(false, |bounds| bounds.contains_point(&down.position));
|
||||
let element = bounds.contains_point(&down.position);
|
||||
if group || element {
|
||||
*active_state.lock() = ElementClickedState { group, element };
|
||||
*active_state.borrow_mut() = ElementClickedState { group, element };
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
@@ -1022,14 +1044,14 @@ where
|
||||
if overflow.x == Overflow::Scroll || overflow.y == Overflow::Scroll {
|
||||
let scroll_offset = element_state
|
||||
.scroll_offset
|
||||
.get_or_insert_with(Arc::default)
|
||||
.get_or_insert_with(Rc::default)
|
||||
.clone();
|
||||
let line_height = cx.line_height();
|
||||
let scroll_max = (content_size - bounds.size).max(&Size::default());
|
||||
|
||||
cx.on_mouse_event(move |_, event: &ScrollWheelEvent, phase, cx| {
|
||||
if phase == DispatchPhase::Bubble && bounds.contains_point(&event.position) {
|
||||
let mut scroll_offset = scroll_offset.lock();
|
||||
let mut scroll_offset = scroll_offset.borrow_mut();
|
||||
let old_scroll_offset = *scroll_offset;
|
||||
let delta = event.delta.pixel_delta(line_height);
|
||||
|
||||
@@ -1058,7 +1080,7 @@ where
|
||||
let scroll_offset = element_state
|
||||
.scroll_offset
|
||||
.as_ref()
|
||||
.map(|scroll_offset| *scroll_offset.lock());
|
||||
.map(|scroll_offset| *scroll_offset.borrow());
|
||||
|
||||
cx.with_key_dispatch(
|
||||
self.key_context.clone(),
|
||||
@@ -1157,7 +1179,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
let clicked_state = element_state.clicked_state.lock();
|
||||
let clicked_state = element_state.clicked_state.borrow();
|
||||
if clicked_state.group {
|
||||
if let Some(group) = self.group_active_style.as_ref() {
|
||||
style.refine(&group.style)
|
||||
@@ -1211,11 +1233,11 @@ impl<V: 'static> Default for Interactivity<V> {
|
||||
#[derive(Default)]
|
||||
pub struct InteractiveElementState {
|
||||
pub focus_handle: Option<FocusHandle>,
|
||||
pub clicked_state: Arc<Mutex<ElementClickedState>>,
|
||||
pub hover_state: Arc<Mutex<bool>>,
|
||||
pub pending_mouse_down: Arc<Mutex<Option<MouseDownEvent>>>,
|
||||
pub scroll_offset: Option<Arc<Mutex<Point<Pixels>>>>,
|
||||
pub active_tooltip: Arc<Mutex<Option<ActiveTooltip>>>,
|
||||
pub clicked_state: Rc<RefCell<ElementClickedState>>,
|
||||
pub hover_state: Rc<RefCell<bool>>,
|
||||
pub pending_mouse_down: Rc<RefCell<Option<MouseDownEvent>>>,
|
||||
pub scroll_offset: Option<Rc<RefCell<Point<Pixels>>>>,
|
||||
pub active_tooltip: Rc<RefCell<Option<ActiveTooltip>>>,
|
||||
}
|
||||
|
||||
pub struct ActiveTooltip {
|
||||
|
||||
@@ -3,9 +3,8 @@ use crate::{
|
||||
ElementId, InteractiveComponent, InteractiveElementState, Interactivity, LayoutId, Pixels,
|
||||
Point, Size, StyleRefinement, Styled, ViewContext,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use smallvec::SmallVec;
|
||||
use std::{cmp, mem, ops::Range, sync::Arc};
|
||||
use std::{cell::RefCell, cmp, mem, ops::Range, rc::Rc};
|
||||
use taffy::style::Overflow;
|
||||
|
||||
/// uniform_list provides lazy rendering for a set of items that are of uniform height.
|
||||
@@ -61,23 +60,23 @@ pub struct UniformList<V: 'static> {
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct UniformListScrollHandle(Arc<Mutex<Option<ScrollHandleState>>>);
|
||||
pub struct UniformListScrollHandle(Rc<RefCell<Option<ScrollHandleState>>>);
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct ScrollHandleState {
|
||||
item_height: Pixels,
|
||||
list_height: Pixels,
|
||||
scroll_offset: Arc<Mutex<Point<Pixels>>>,
|
||||
scroll_offset: Rc<RefCell<Point<Pixels>>>,
|
||||
}
|
||||
|
||||
impl UniformListScrollHandle {
|
||||
pub fn new() -> Self {
|
||||
Self(Arc::new(Mutex::new(None)))
|
||||
Self(Rc::new(RefCell::new(None)))
|
||||
}
|
||||
|
||||
pub fn scroll_to_item(&self, ix: usize) {
|
||||
if let Some(state) = &*self.0.lock() {
|
||||
let mut scroll_offset = state.scroll_offset.lock();
|
||||
if let Some(state) = &*self.0.borrow() {
|
||||
let mut scroll_offset = state.scroll_offset.borrow_mut();
|
||||
let item_top = state.item_height * ix;
|
||||
let item_bottom = item_top + state.item_height;
|
||||
let scroll_top = -scroll_offset.y;
|
||||
@@ -196,7 +195,7 @@ impl<V: 'static> Element<V> for UniformList<V> {
|
||||
let shared_scroll_offset = element_state
|
||||
.interactive
|
||||
.scroll_offset
|
||||
.get_or_insert_with(Arc::default)
|
||||
.get_or_insert_with(Rc::default)
|
||||
.clone();
|
||||
|
||||
interactivity.paint(
|
||||
@@ -222,7 +221,7 @@ impl<V: 'static> Element<V> for UniformList<V> {
|
||||
.measure_item(view_state, Some(padded_bounds.size.width), cx)
|
||||
.height;
|
||||
if let Some(scroll_handle) = self.scroll_handle.clone() {
|
||||
scroll_handle.0.lock().replace(ScrollHandleState {
|
||||
scroll_handle.0.borrow_mut().replace(ScrollHandleState {
|
||||
item_height,
|
||||
list_height: padded_bounds.size.height,
|
||||
scroll_offset: shared_scroll_offset,
|
||||
|
||||
@@ -337,7 +337,6 @@ mod test {
|
||||
.update(cx, |test_view, cx| cx.focus(&test_view.focus_handle))
|
||||
.unwrap();
|
||||
|
||||
cx.dispatch_keystroke(*window, Keystroke::parse("space").unwrap(), false);
|
||||
cx.dispatch_keystroke(*window, Keystroke::parse("ctrl-g").unwrap(), false);
|
||||
|
||||
window
|
||||
|
||||
@@ -60,7 +60,7 @@ impl DispatchTree {
|
||||
self.keystroke_matchers.clear();
|
||||
}
|
||||
|
||||
pub fn push_node(&mut self, context: KeyContext, old_dispatcher: &mut Self) {
|
||||
pub fn push_node(&mut self, context: KeyContext) {
|
||||
let parent = self.node_stack.last().copied();
|
||||
let node_id = DispatchNodeId(self.nodes.len());
|
||||
self.nodes.push(DispatchNode {
|
||||
@@ -71,12 +71,6 @@ impl DispatchTree {
|
||||
if !context.is_empty() {
|
||||
self.active_node().context = context.clone();
|
||||
self.context_stack.push(context);
|
||||
if let Some((context_stack, matcher)) = old_dispatcher
|
||||
.keystroke_matchers
|
||||
.remove_entry(self.context_stack.as_slice())
|
||||
{
|
||||
self.keystroke_matchers.insert(context_stack, matcher);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,6 +81,33 @@ impl DispatchTree {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_keystroke_matchers(&mut self) {
|
||||
self.keystroke_matchers.clear();
|
||||
}
|
||||
|
||||
/// Preserve keystroke matchers from previous frames to support multi-stroke
|
||||
/// bindings across multiple frames.
|
||||
pub fn preserve_keystroke_matchers(&mut self, old_tree: &mut Self, focus_id: Option<FocusId>) {
|
||||
if let Some(node_id) = focus_id.and_then(|focus_id| self.focusable_node_id(focus_id)) {
|
||||
let dispatch_path = self.dispatch_path(node_id);
|
||||
|
||||
self.context_stack.clear();
|
||||
for node_id in dispatch_path {
|
||||
let node = self.node(node_id);
|
||||
if !node.context.is_empty() {
|
||||
self.context_stack.push(node.context.clone());
|
||||
}
|
||||
|
||||
if let Some((context_stack, matcher)) = old_tree
|
||||
.keystroke_matchers
|
||||
.remove_entry(self.context_stack.as_slice())
|
||||
{
|
||||
self.keystroke_matchers.insert(context_stack, matcher);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on_key_event(&mut self, listener: KeyListener) {
|
||||
self.active_node().key_listeners.push(listener);
|
||||
}
|
||||
|
||||
@@ -184,7 +184,11 @@ pub trait PlatformTextSystem: Send + Sync {
|
||||
fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>>;
|
||||
fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId>;
|
||||
fn glyph_raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>>;
|
||||
fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)>;
|
||||
fn rasterize_glyph(
|
||||
&self,
|
||||
params: &RenderGlyphParams,
|
||||
raster_bounds: Bounds<DevicePixels>,
|
||||
) -> Result<(Size<DevicePixels>, Vec<u8>)>;
|
||||
fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout;
|
||||
fn wrap_line(
|
||||
&self,
|
||||
|
||||
@@ -116,7 +116,9 @@ impl PlatformTextSystem for MacTextSystem {
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(candidates[ix])
|
||||
let font_id = candidates[ix];
|
||||
lock.font_selections.insert(font.clone(), font_id);
|
||||
Ok(font_id)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,8 +147,9 @@ impl PlatformTextSystem for MacTextSystem {
|
||||
fn rasterize_glyph(
|
||||
&self,
|
||||
glyph_id: &RenderGlyphParams,
|
||||
raster_bounds: Bounds<DevicePixels>,
|
||||
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
|
||||
self.0.read().rasterize_glyph(glyph_id)
|
||||
self.0.read().rasterize_glyph(glyph_id, raster_bounds)
|
||||
}
|
||||
|
||||
fn layout_line(&self, text: &str, font_size: Pixels, font_runs: &[FontRun]) -> LineLayout {
|
||||
@@ -247,8 +250,11 @@ impl MacTextSystemState {
|
||||
.into())
|
||||
}
|
||||
|
||||
fn rasterize_glyph(&self, params: &RenderGlyphParams) -> Result<(Size<DevicePixels>, Vec<u8>)> {
|
||||
let glyph_bounds = self.raster_bounds(params)?;
|
||||
fn rasterize_glyph(
|
||||
&self,
|
||||
params: &RenderGlyphParams,
|
||||
glyph_bounds: Bounds<DevicePixels>,
|
||||
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
|
||||
if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {
|
||||
Err(anyhow!("glyph bounds are empty"))
|
||||
} else {
|
||||
@@ -260,6 +266,7 @@ impl MacTextSystemState {
|
||||
if params.subpixel_variant.y > 0 {
|
||||
bitmap_size.height += DevicePixels(1);
|
||||
}
|
||||
let bitmap_size = bitmap_size;
|
||||
|
||||
let mut bytes;
|
||||
let cx;
|
||||
|
||||
@@ -22,7 +22,7 @@ pub struct TestWindow {
|
||||
bounds: WindowBounds,
|
||||
current_scene: Mutex<Option<Scene>>,
|
||||
display: Rc<dyn PlatformDisplay>,
|
||||
input_handler: Option<Box<dyn PlatformInputHandler>>,
|
||||
pub(crate) input_handler: Option<Arc<Mutex<Box<dyn PlatformInputHandler>>>>,
|
||||
handlers: Mutex<Handlers>,
|
||||
platform: Weak<TestPlatform>,
|
||||
sprite_atlas: Arc<dyn PlatformAtlas>,
|
||||
@@ -80,11 +80,11 @@ impl PlatformWindow for TestWindow {
|
||||
}
|
||||
|
||||
fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
|
||||
todo!()
|
||||
self
|
||||
}
|
||||
|
||||
fn set_input_handler(&mut self, input_handler: Box<dyn crate::PlatformInputHandler>) {
|
||||
self.input_handler = Some(input_handler);
|
||||
self.input_handler = Some(Arc::new(Mutex::new(input_handler)));
|
||||
}
|
||||
|
||||
fn prompt(
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use crate::{
|
||||
black, phi, point, rems, AbsoluteLength, BorrowAppContext, BorrowWindow, Bounds, ContentMask,
|
||||
Corners, CornersRefinement, CursorStyle, DefiniteLength, Edges, EdgesRefinement, Font,
|
||||
FontFeatures, FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Result,
|
||||
Rgba, SharedString, Size, SizeRefinement, Styled, TextRun, ViewContext,
|
||||
FontFeatures, FontStyle, FontWeight, Hsla, Length, Pixels, Point, PointRefinement, Rgba,
|
||||
SharedString, Size, SizeRefinement, Styled, TextRun, ViewContext,
|
||||
};
|
||||
use refineable::{Cascade, Refineable};
|
||||
use smallvec::SmallVec;
|
||||
@@ -157,7 +157,7 @@ impl Default for TextStyle {
|
||||
}
|
||||
|
||||
impl TextStyle {
|
||||
pub fn highlight(mut self, style: HighlightStyle) -> Result<Self> {
|
||||
pub fn highlight(mut self, style: HighlightStyle) -> Self {
|
||||
if let Some(weight) = style.font_weight {
|
||||
self.font_weight = weight;
|
||||
}
|
||||
@@ -177,7 +177,7 @@ impl TextStyle {
|
||||
self.underline = Some(underline);
|
||||
}
|
||||
|
||||
Ok(self)
|
||||
self
|
||||
}
|
||||
|
||||
pub fn font(&self) -> Font {
|
||||
|
||||
@@ -39,6 +39,7 @@ pub struct TextSystem {
|
||||
platform_text_system: Arc<dyn PlatformTextSystem>,
|
||||
font_ids_by_font: RwLock<HashMap<Font, FontId>>,
|
||||
font_metrics: RwLock<HashMap<FontId, FontMetrics>>,
|
||||
raster_bounds: RwLock<HashMap<RenderGlyphParams, Bounds<DevicePixels>>>,
|
||||
wrapper_pool: Mutex<HashMap<FontIdWithSize, Vec<LineWrapper>>>,
|
||||
font_runs_pool: Mutex<Vec<Vec<FontRun>>>,
|
||||
}
|
||||
@@ -48,10 +49,11 @@ impl TextSystem {
|
||||
TextSystem {
|
||||
line_layout_cache: Arc::new(LineLayoutCache::new(platform_text_system.clone())),
|
||||
platform_text_system,
|
||||
font_metrics: RwLock::new(HashMap::default()),
|
||||
font_ids_by_font: RwLock::new(HashMap::default()),
|
||||
wrapper_pool: Mutex::new(HashMap::default()),
|
||||
font_runs_pool: Default::default(),
|
||||
font_metrics: RwLock::default(),
|
||||
raster_bounds: RwLock::default(),
|
||||
font_ids_by_font: RwLock::default(),
|
||||
wrapper_pool: Mutex::default(),
|
||||
font_runs_pool: Mutex::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,14 +254,24 @@ impl TextSystem {
|
||||
}
|
||||
|
||||
pub fn raster_bounds(&self, params: &RenderGlyphParams) -> Result<Bounds<DevicePixels>> {
|
||||
self.platform_text_system.glyph_raster_bounds(params)
|
||||
let raster_bounds = self.raster_bounds.upgradable_read();
|
||||
if let Some(bounds) = raster_bounds.get(params) {
|
||||
Ok(bounds.clone())
|
||||
} else {
|
||||
let mut raster_bounds = RwLockUpgradableReadGuard::upgrade(raster_bounds);
|
||||
let bounds = self.platform_text_system.glyph_raster_bounds(params)?;
|
||||
raster_bounds.insert(params.clone(), bounds);
|
||||
Ok(bounds)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rasterize_glyph(
|
||||
&self,
|
||||
glyph_id: &RenderGlyphParams,
|
||||
params: &RenderGlyphParams,
|
||||
) -> Result<(Size<DevicePixels>, Vec<u8>)> {
|
||||
self.platform_text_system.rasterize_glyph(glyph_id)
|
||||
let raster_bounds = self.raster_bounds(params)?;
|
||||
self.platform_text_system
|
||||
.rasterize_glyph(params, raster_bounds)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,16 @@ impl<V: 'static> View<V> {
|
||||
pub fn read<'a>(&self, cx: &'a AppContext) -> &'a V {
|
||||
self.model.read(cx)
|
||||
}
|
||||
|
||||
pub fn render_with<C>(&self, component: C) -> RenderViewWith<C, V>
|
||||
where
|
||||
C: 'static + Component<V>,
|
||||
{
|
||||
RenderViewWith {
|
||||
view: self.clone(),
|
||||
component: Some(component),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Clone for View<V> {
|
||||
@@ -281,6 +291,67 @@ impl<V: Render> From<WeakView<V>> for AnyWeakView {
|
||||
// }
|
||||
// }
|
||||
|
||||
pub struct RenderViewWith<C, V> {
|
||||
view: View<V>,
|
||||
component: Option<C>,
|
||||
}
|
||||
|
||||
impl<C, ParentViewState, ViewState> Component<ParentViewState> for RenderViewWith<C, ViewState>
|
||||
where
|
||||
C: 'static + Component<ViewState>,
|
||||
ParentViewState: 'static,
|
||||
ViewState: 'static,
|
||||
{
|
||||
fn render(self) -> AnyElement<ParentViewState> {
|
||||
AnyElement::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<C, ParentViewState, ViewState> Element<ParentViewState> for RenderViewWith<C, ViewState>
|
||||
where
|
||||
C: 'static + Component<ViewState>,
|
||||
ParentViewState: 'static,
|
||||
ViewState: 'static,
|
||||
{
|
||||
type ElementState = AnyElement<ViewState>;
|
||||
|
||||
fn element_id(&self) -> Option<ElementId> {
|
||||
Some(self.view.entity_id().into())
|
||||
}
|
||||
|
||||
fn initialize(
|
||||
&mut self,
|
||||
_: &mut ParentViewState,
|
||||
_: Option<Self::ElementState>,
|
||||
cx: &mut ViewContext<ParentViewState>,
|
||||
) -> Self::ElementState {
|
||||
self.view.update(cx, |view, cx| {
|
||||
let mut element = self.component.take().unwrap().render();
|
||||
element.initialize(view, cx);
|
||||
element
|
||||
})
|
||||
}
|
||||
|
||||
fn layout(
|
||||
&mut self,
|
||||
_: &mut ParentViewState,
|
||||
element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<ParentViewState>,
|
||||
) -> LayoutId {
|
||||
self.view.update(cx, |view, cx| element.layout(view, cx))
|
||||
}
|
||||
|
||||
fn paint(
|
||||
&mut self,
|
||||
_: Bounds<Pixels>,
|
||||
_: &mut ParentViewState,
|
||||
element: &mut Self::ElementState,
|
||||
cx: &mut ViewContext<ParentViewState>,
|
||||
) {
|
||||
self.view.update(cx, |view, cx| element.paint(view, cx))
|
||||
}
|
||||
}
|
||||
|
||||
mod any_view {
|
||||
use crate::{AnyElement, AnyView, BorrowWindow, LayoutId, Render, WindowContext};
|
||||
use std::any::Any;
|
||||
|
||||
@@ -189,7 +189,7 @@ impl Drop for FocusHandle {
|
||||
pub struct Window {
|
||||
pub(crate) handle: AnyWindowHandle,
|
||||
pub(crate) removed: bool,
|
||||
platform_window: Box<dyn PlatformWindow>,
|
||||
pub(crate) platform_window: Box<dyn PlatformWindow>,
|
||||
display_id: DisplayId,
|
||||
sprite_atlas: Arc<dyn PlatformAtlas>,
|
||||
rem_size: Pixels,
|
||||
@@ -216,7 +216,7 @@ pub struct Window {
|
||||
|
||||
// #[derive(Default)]
|
||||
pub(crate) struct Frame {
|
||||
element_states: HashMap<GlobalElementId, AnyBox>,
|
||||
pub(crate) element_states: HashMap<GlobalElementId, AnyBox>,
|
||||
mouse_listeners: HashMap<TypeId, Vec<(StackingOrder, AnyMouseListener)>>,
|
||||
pub(crate) dispatch_tree: DispatchTree,
|
||||
pub(crate) focus_listeners: Vec<AnyFocusListener>,
|
||||
@@ -393,6 +393,10 @@ 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) {
|
||||
return;
|
||||
}
|
||||
|
||||
let focus_id = handle.id;
|
||||
|
||||
if self.window.last_blur.is_none() {
|
||||
@@ -400,6 +404,10 @@ impl<'a> WindowContext<'a> {
|
||||
}
|
||||
|
||||
self.window.focus = Some(focus_id);
|
||||
self.window
|
||||
.current_frame
|
||||
.dispatch_tree
|
||||
.clear_keystroke_matchers();
|
||||
self.app.push_effect(Effect::FocusChanged {
|
||||
window_handle: self.window.handle,
|
||||
focused: Some(focus_id),
|
||||
@@ -1091,6 +1099,14 @@ impl<'a> WindowContext<'a> {
|
||||
});
|
||||
}
|
||||
|
||||
self.window
|
||||
.current_frame
|
||||
.dispatch_tree
|
||||
.preserve_keystroke_matchers(
|
||||
&mut self.window.previous_frame.dispatch_tree,
|
||||
self.window.focus,
|
||||
);
|
||||
|
||||
self.window.root_view = Some(root_view);
|
||||
let scene = self.window.current_frame.scene_builder.build();
|
||||
|
||||
@@ -2093,7 +2109,7 @@ impl<'a, V: 'static> ViewContext<'a, V> {
|
||||
window
|
||||
.current_frame
|
||||
.dispatch_tree
|
||||
.push_node(context.clone(), &mut window.previous_frame.dispatch_tree);
|
||||
.push_node(context.clone());
|
||||
if let Some(focus_handle) = focus_handle.as_ref() {
|
||||
window
|
||||
.current_frame
|
||||
@@ -2471,7 +2487,7 @@ impl From<SmallVec<[u32; 16]>> for StackingOrder {
|
||||
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
|
||||
pub enum ElementId {
|
||||
View(EntityId),
|
||||
Number(usize),
|
||||
Integer(usize),
|
||||
Name(SharedString),
|
||||
FocusHandle(FocusId),
|
||||
}
|
||||
@@ -2496,13 +2512,13 @@ impl From<EntityId> for ElementId {
|
||||
|
||||
impl From<usize> for ElementId {
|
||||
fn from(id: usize) -> Self {
|
||||
ElementId::Number(id)
|
||||
ElementId::Integer(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i32> for ElementId {
|
||||
fn from(id: i32) -> Self {
|
||||
Self::Number(id as usize)
|
||||
Self::Integer(id as usize)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user