use crate::{
AnyElement, AnyEntity, AnyWeakEntity, App, AvailableSpace, Bounds, ContentMask, Context,
Element, ElementId, Entity, EntityId, GlobalElementId, InspectorElementId, IntoElement,
LayoutId, PaintIndex, Pixels, PrepaintStateIndex, Render, RenderOnce, Size, Style,
StyleRefinement, TextStyle, TransformationMatrix, WeakEntity,
};
use crate::{Empty, Window};
use anyhow::Result;
use collections::FxHashSet;
use refineable::Refineable;
use std::mem;
use std::{
any::{TypeId, type_name},
fmt,
ops::Range,
};
#[derive(Clone, Debug)]
pub struct AnyView {
entity: AnyEntity,
render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
view_type_name: &'static str,
}
impl<V: Render> From<Entity<V>> for AnyView {
fn from(value: Entity<V>) -> Self {
AnyView {
entity: value.into_any(),
render: any_view::render::<V>,
view_type_name: type_name::<V>(),
}
}
}
impl AnyView {
pub fn cached(self, style: StyleRefinement) -> ViewElement<AnyView> {
self.into_element().cached(style)
}
pub fn downgrade(&self) -> AnyWeakView {
AnyWeakView {
entity: self.entity.downgrade(),
render: self.render,
view_type_name: self.view_type_name,
}
}
pub fn downcast<T: 'static>(self) -> Result<Entity<T>, Self> {
match self.entity.downcast() {
Ok(entity) => Ok(entity),
Err(entity) => Err(Self {
entity,
render: self.render,
view_type_name: self.view_type_name,
}),
}
}
pub fn entity_type(&self) -> TypeId {
self.entity.entity_type
}
pub fn entity_id(&self) -> EntityId {
self.entity.entity_id()
}
}
impl PartialEq for AnyView {
fn eq(&self, other: &Self) -> bool {
self.entity == other.entity
}
}
impl Eq for AnyView {}
impl View for AnyView {
fn entity_id(&self) -> Option<EntityId> {
Some(self.entity.entity_id())
}
#[cfg(not(gpui_hot_reload))]
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
(self.render)(&self, window, cx)
}
#[cfg(gpui_hot_reload)]
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
subsecond::HotFn::current(self.render).call((&self, window, cx))
}
}
impl<V: 'static + Render> IntoElement for Entity<V> {
type Element = ViewElement<Entity<V>>;
fn into_element(self) -> Self::Element {
ViewElement::with_type_name(self, type_name::<V>())
}
#[inline(never)]
fn into_any_element(self) -> AnyElement {
self.into_element().into_any()
}
}
impl IntoElement for AnyView {
type Element = ViewElement<AnyView>;
fn into_element(self) -> Self::Element {
let view_type_name = self.view_type_name;
ViewElement::with_type_name(self, view_type_name)
}
}
pub struct AnyWeakView {
entity: AnyWeakEntity,
render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
view_type_name: &'static str,
}
impl AnyWeakView {
pub fn upgrade(&self) -> Option<AnyView> {
let entity = self.entity.upgrade()?;
Some(AnyView {
entity,
render: self.render,
view_type_name: self.view_type_name,
})
}
}
impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
fn from(view: WeakEntity<V>) -> Self {
AnyWeakView {
entity: view.into(),
render: any_view::render::<V>,
view_type_name: type_name::<V>(),
}
}
}
impl PartialEq for AnyWeakView {
fn eq(&self, other: &Self) -> bool {
self.entity == other.entity
}
}
impl std::fmt::Debug for AnyWeakView {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AnyWeakView")
.field("entity_id", &self.entity.entity_id)
.finish_non_exhaustive()
}
}
mod any_view {
use crate::{AnyElement, AnyView, App, IntoElement, Render, Window};
pub(crate) fn render<V: 'static + Render>(
view: &AnyView,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let view = view.clone().downcast::<V>().unwrap();
#[cfg(debug_assertions)]
window
.a11y
.view_type_names
.insert(view.entity_id(), std::any::type_name::<V>());
view.update(cx, |view, cx| view.render(window, cx).into_any_element())
}
}
pub trait View: 'static + Sized {
fn entity_id(&self) -> Option<EntityId>;
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
}
impl<T: RenderOnce> View for T {
fn entity_id(&self) -> Option<EntityId> {
None
}
#[inline]
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
RenderOnce::render(self, window, cx)
}
}
impl<T: Render> View for Entity<T> {
fn entity_id(&self) -> Option<EntityId> {
Some(Entity::entity_id(self))
}
#[inline]
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
self.update(cx, |this, cx| {
Render::render(this, window, cx).into_any_element()
})
}
}
impl<T: Render> Entity<T> {
#[track_caller]
pub fn cached(self, style: StyleRefinement) -> ViewElement<Entity<T>> {
ViewElement::with_type_name(self, type_name::<T>()).cached(style)
}
}
#[doc(hidden)]
pub struct ViewElement<V: View> {
view: Option<V>,
entity_id: Option<EntityId>,
cached_style: Option<StyleRefinement>,
#[cfg(feature = "profiler")]
view_type_name: &'static str,
#[cfg(debug_assertions)]
source: &'static core::panic::Location<'static>,
}
impl<V: View> ViewElement<V> {
#[track_caller]
pub fn new(view: V) -> Self {
Self::with_type_name(view, type_name::<V>())
}
#[track_caller]
#[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
pub(crate) fn with_type_name(view: V, view_type_name: &'static str) -> Self {
let entity_id = view.entity_id();
ViewElement {
entity_id,
cached_style: None,
#[cfg(feature = "profiler")]
view_type_name,
view: Some(view),
#[cfg(debug_assertions)]
source: core::panic::Location::caller(),
}
}
pub(crate) fn cached(mut self, style: StyleRefinement) -> Self {
self.cached_style = Some(style);
self
}
}
struct ViewElementState {
prepaint_range: Range<PrepaintStateIndex>,
paint_range: Range<PaintIndex>,
cache_key: ViewElementCacheKey,
accessed_entities: FxHashSet<EntityId>,
}
struct ViewElementCacheKey {
bounds: Bounds<Pixels>,
content_mask: ContentMask<Pixels>,
text_style: TextStyle,
opacity: f32,
transform: TransformationMatrix,
vn_clip: Option<std::sync::Arc<crate::VnClipNode>>,
}
#[cfg(not(gpui_hot_reload))]
#[inline]
fn render_view<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
view.render(window, cx).into_any_element()
}
#[cfg(gpui_hot_reload)]
fn render_view<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
#[inline(never)]
fn render_view_impl<V: View>(view: V, window: &mut Window, cx: &mut App) -> AnyElement {
view.render(window, cx).into_any_element()
}
subsecond::HotFn::current(render_view_impl::<V>).call((view, window, cx))
}
impl<V: View> Element for ViewElement<V> {
type RequestLayoutState = Option<AnyElement>;
type PrepaintState = Option<AnyElement>;
fn id(&self) -> Option<ElementId> {
self.entity_id.map(ElementId::View)
}
fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
#[cfg(debug_assertions)]
return Some(self.source);
#[cfg(not(debug_assertions))]
return None;
}
fn request_layout(
&mut self,
_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
if let Some(entity_id) = self.entity_id {
#[cfg(feature = "profiler")]
let start = window.window_profiler.begin_view();
let view = &mut self.view;
let layout = request_layout_view(
entity_id,
self.cached_style.as_ref(),
window,
cx,
&mut |window, cx| render_view(view.take().unwrap(), window, cx),
);
#[cfg(feature = "profiler")]
window.window_profiler.end_view(
start,
self.view_type_name,
crate::profiler::ViewPhase::RequestLayout,
);
layout
} else {
request_layout_component(type_name::<V>(), window, cx, &mut |window, cx| {
render_view(self.view.take().unwrap(), window, cx)
})
}
}
fn prepaint(
&mut self,
global_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
bounds: Bounds<Pixels>,
element: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
) -> Option<AnyElement> {
if let Some(entity_id) = self.entity_id {
#[cfg(feature = "profiler")]
let start = window.window_profiler.begin_view();
let prepainted = prepaint_view(
entity_id,
global_id,
bounds,
element,
window,
cx,
&mut |window, cx| render_view(self.view.take().unwrap(), window, cx),
);
#[cfg(feature = "profiler")]
window.window_profiler.end_view(
start,
self.view_type_name,
crate::profiler::ViewPhase::Prepaint,
);
prepainted
} else {
prepaint_component(type_name::<V>(), element, window, cx)
}
}
fn paint(
&mut self,
global_id: Option<&GlobalElementId>,
_inspector_id: Option<&InspectorElementId>,
_bounds: Bounds<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
element: &mut Self::PrepaintState,
window: &mut Window,
cx: &mut App,
) {
if let Some(entity_id) = self.entity_id {
#[cfg(feature = "profiler")]
let start = window.window_profiler.begin_view();
paint_view(
entity_id,
self.cached_style.is_some(),
global_id,
element,
window,
cx,
);
#[cfg(feature = "profiler")]
window.window_profiler.end_view(
start,
self.view_type_name,
crate::profiler::ViewPhase::Paint,
);
} else {
paint_component(std::any::type_name::<V>(), element, window, cx);
}
}
}
pub struct EmptyView;
impl Render for EmptyView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
Empty
}
}
#[inline(never)]
fn request_layout_view(
entity_id: EntityId,
cached_style: Option<&StyleRefinement>,
window: &mut Window,
cx: &mut App,
render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
) -> (LayoutId, Option<AnyElement>) {
window.with_rendered_view(entity_id, |window| {
let caching_disabled = window.is_inspector_picking(cx);
match cached_style {
Some(style) if !caching_disabled => {
let mut root_style = Style::default();
root_style.refine(style);
let layout_id = window.request_layout(root_style, None, cx);
(layout_id, None)
}
_ => {
let mut element = render(window, cx);
let layout_id = element.request_layout(window, cx);
(layout_id, Some(element))
}
}
})
}
#[inline(never)]
fn request_layout_component(
name: &'static str,
window: &mut Window,
cx: &mut App,
render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
) -> (LayoutId, Option<AnyElement>) {
window.with_id(ElementId::from(name), |window| {
let mut element = render(window, cx);
let layout_id = element.request_layout(window, cx);
(layout_id, Some(element))
})
}
#[inline(never)]
fn prepaint_view(
entity_id: EntityId,
global_id: Option<&GlobalElementId>,
bounds: Bounds<Pixels>,
element: &mut Option<AnyElement>,
window: &mut Window,
cx: &mut App,
render: &mut dyn FnMut(&mut Window, &mut App) -> AnyElement,
) -> Option<AnyElement> {
window.set_view_id(entity_id);
window.with_rendered_view(entity_id, |window| {
if let Some(mut element) = element.take() {
element.prepaint(window, cx);
return Some(element);
}
window.with_element_state::<ViewElementState, _>(
global_id.unwrap(),
|element_state, window| {
let content_mask = window.content_mask();
let text_style = window.text_style();
let opacity = window.element_opacity();
let transform = window.element_transform();
let vn_clip = window.vn_clip_stack.clone();
if let Some(mut element_state) = element_state
&& element_state.cache_key.bounds == bounds
&& element_state.cache_key.content_mask == content_mask
&& element_state.cache_key.text_style == text_style
&& element_state.cache_key.opacity.to_bits() == opacity.to_bits()
&& element_state.cache_key.transform == transform
&& crate::VnClipNode::same(&element_state.cache_key.vn_clip, &vn_clip)
&& !window.dirty_views.contains(&entity_id)
&& !window.refreshing
{
let prepaint_start = window.prepaint_index();
window.reuse_prepaint(element_state.prepaint_range.clone());
cx.entities
.extend_accessed(element_state.accessed_entities.iter().copied());
let prepaint_end = window.prepaint_index();
element_state.prepaint_range = prepaint_start..prepaint_end;
return (None, element_state);
}
let refreshing = mem::replace(&mut window.refreshing, true);
let prepaint_start = window.prepaint_index();
let (element, accessed_entities) = cx.detect_accessed_entities(|cx| {
let mut element = render(window, cx);
element.layout_as_root(Size::<AvailableSpace>::from(bounds.size), window, cx);
element.prepaint_at(bounds.origin, window, cx);
element
});
let prepaint_end = window.prepaint_index();
window.refreshing = refreshing;
(
Some(element),
ViewElementState {
accessed_entities,
prepaint_range: prepaint_start..prepaint_end,
paint_range: PaintIndex::default()..PaintIndex::default(),
cache_key: ViewElementCacheKey {
bounds,
content_mask,
text_style,
opacity,
transform,
vn_clip,
},
},
)
},
)
})
}
#[inline(never)]
fn prepaint_component(
name: &'static str,
element: &mut Option<AnyElement>,
window: &mut Window,
cx: &mut App,
) -> Option<AnyElement> {
window.with_id(ElementId::from(name), |window| {
element.as_mut().unwrap().prepaint(window, cx);
});
Some(element.take().unwrap())
}
#[inline(never)]
fn paint_view(
entity_id: EntityId,
cached: bool,
global_id: Option<&GlobalElementId>,
element: &mut Option<AnyElement>,
window: &mut Window,
cx: &mut App,
) {
window.with_rendered_view(entity_id, |window| {
let caching_disabled = window.is_inspector_picking(cx);
if cached && !caching_disabled {
window.with_element_state::<ViewElementState, _>(
global_id.unwrap(),
|element_state, window| {
let mut element_state = element_state.unwrap();
let paint_start = window.paint_index();
let opacity = window.element_opacity();
if let Some(element) = element {
let refreshing = mem::replace(&mut window.refreshing, true);
let ((), accessed_entities) =
cx.detect_accessed_entities(|cx| element.paint(window, cx));
element_state.accessed_entities.extend(accessed_entities);
window.refreshing = refreshing;
element_state.cache_key.opacity = opacity;
} else {
window.reuse_paint(element_state.paint_range.clone());
if element_state.cache_key.opacity.to_bits() != opacity.to_bits() {
window.request_animation_frame();
}
}
let paint_end = window.paint_index();
element_state.paint_range = paint_start..paint_end;
((), element_state)
},
)
} else {
element.as_mut().unwrap().paint(window, cx);
}
});
}
#[inline(never)]
fn paint_component(
name: &'static str,
element: &mut Option<AnyElement>,
window: &mut Window,
cx: &mut App,
) {
window.with_id(ElementId::Name(name.into()), |window| {
element.as_mut().unwrap().paint(window, cx);
});
}
#[cfg(test)]
mod vn_cache_key_tests {
use crate::{
AnyWindowHandle, Context, Entity, Render, StyleRefinement, TestAppContext,
TransformSpec, Window, div, prelude::*, px, size,
};
use std::{cell::Cell, rc::Rc};
struct CaptionRoot {
child: Entity<CaptionChild>,
uncached_drag_parent: bool,
}
struct CaptionChild {
renders: Rc<Cell<u32>>,
own_drag_region: bool,
}
impl Render for CaptionRoot {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div().size_full()
.when(self.uncached_drag_parent, |element| element.window_control_area(crate::WindowControlArea::Drag))
.child(self.child.clone().cached(StyleRefinement::default().w(px(200.)).h(px(40.))))
}
}
impl Render for CaptionChild {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
div().size_full()
.when(self.own_drag_region, |element| element.window_control_area(crate::WindowControlArea::Drag))
.child(div().w(px(50.)).h(px(40.)).window_control_area(crate::WindowControlArea::NoDrag))
}
}
fn caption_frame(handle: AnyWindowHandle, cx: &mut TestAppContext) {
cx.update_window(handle, |root, window, cx| {
root.downcast::<CaptionRoot>().expect("caption root").update(cx, |_, cx| cx.notify());
window.draw(cx).clear(cx);
assert_eq!(window.window_control_area_at(crate::point(px(100.), px(20.))), Some(crate::WindowControlArea::Drag));
assert_eq!(window.window_control_area_at(crate::point(px(25.), px(20.))), Some(crate::WindowControlArea::NoDrag));
}).expect("draw caption");
}
#[gpui::test]
fn cached_caption_replays_drag_and_no_drag_regions(cx: &mut TestAppContext) {
let renders = Rc::new(Cell::new(0));
let counter = renders.clone();
let handle = cx.open_window(size(px(240.), px(100.)), move |_, cx| CaptionRoot {
child: cx.new(|_| CaptionChild { renders: counter, own_drag_region: true }),
uncached_drag_parent: false,
}).into();
caption_frame(handle, cx);
let first = renders.get();
for _ in 0..20 { caption_frame(handle, cx); }
assert_eq!(renders.get(), first, "caption must replay rather than being rebuilt to keep dragging");
}
#[gpui::test]
fn cached_no_drag_cutout_does_not_become_its_uncached_drag_parent(cx: &mut TestAppContext) {
let renders = Rc::new(Cell::new(0));
let counter = renders.clone();
let handle = cx.open_window(size(px(240.), px(100.)), move |_, cx| CaptionRoot {
child: cx.new(|_| CaptionChild { renders: counter, own_drag_region: false }),
uncached_drag_parent: true,
}).into();
caption_frame(handle, cx);
let first = renders.get();
for _ in 0..20 { caption_frame(handle, cx); }
assert_eq!(renders.get(), first);
}
#[gpui::test]
fn caption_hit_test_uses_requested_point_without_a_preceding_move(cx: &mut TestAppContext) {
let handle = cx.open_window(size(px(240.), px(100.)), move |_, cx| CaptionRoot {
child: cx.new(|_| CaptionChild { renders: Rc::new(Cell::new(0)), own_drag_region: true }),
uncached_drag_parent: false,
});
caption_frame(handle.into(), cx);
handle.update(cx, |_, window, cx| {
window.dispatch_event(crate::PlatformInput::MouseMove(crate::MouseMoveEvent {
position: crate::point(px(25.), px(20.)),
pressed_button: None,
modifiers: Default::default(),
}), cx);
assert_eq!(window.window_control_area_at(crate::point(px(100.), px(20.))), Some(crate::WindowControlArea::Drag));
assert_eq!(window.window_control_area_at(crate::point(px(25.), px(20.))), Some(crate::WindowControlArea::NoDrag));
}).expect("hit test without another mouse move");
}
struct Root {
child: Entity<Child>,
opacity: f32,
scale: f32,
}
impl Render for Root {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let mut outer = div().size_full().opacity(self.opacity);
outer.style().vn_transform = Some(TransformSpec {
scale: (self.scale, self.scale),
..TransformSpec::IDENTITY
});
outer.child(
self.child
.clone()
.cached(StyleRefinement::default().size(px(50.))),
)
}
}
struct Child {
renders: Rc<Cell<u32>>,
}
impl Render for Child {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
div().size_full().bg(crate::red())
}
}
fn frame(window: AnyWindowHandle, cx: &mut TestAppContext, opacity: f32, scale: f32) {
cx.update_window(window, |root, window, cx| {
let root = root.downcast::<Root>().expect("test root");
root.update(cx, |root, cx| {
root.opacity = opacity;
root.scale = scale;
cx.notify();
});
window.draw(cx).clear(cx);
})
.expect("draw");
}
#[gpui::test]
fn a_cached_view_renders_again_under_a_new_opacity_or_transform(cx: &mut TestAppContext) {
let renders = Rc::new(Cell::new(0u32));
let counter = renders.clone();
let window = cx.open_window(size(px(200.), px(200.)), move |_, cx| Root {
child: cx.new(|_| Child { renders: counter }),
opacity: 0.1,
scale: 1.0,
});
let window: AnyWindowHandle = window.into();
frame(window, cx, 0.1, 1.0);
let first = renders.get();
assert!(first >= 1, "the first frame renders the child");
frame(window, cx, 0.1, 1.0);
assert_eq!(renders.get(), first, "same opacity and transform: replayed");
frame(window, cx, 0.6, 1.0);
assert_eq!(renders.get(), first + 1, "a new opacity renders");
frame(window, cx, 1.0, 1.0);
assert_eq!(renders.get(), first + 2, "and the next one");
frame(window, cx, 1.0, 1.0);
assert_eq!(renders.get(), first + 2, "the fade over: replayed again");
frame(window, cx, 1.0, 0.95);
assert_eq!(renders.get(), first + 3, "a new transform renders");
frame(window, cx, 1.0, 0.95);
assert_eq!(renders.get(), first + 3, "the same transform replays");
}
}