use crate::{
AnyElement, AnyEntity, AnyWeakEntity, App, Bounds, ContentMask, Context, Element, ElementId,
Entity, EntityId, GlobalElementId, IntoElement, LayoutId, PaintIndex, Pixels,
PrepaintStateIndex, Render, RenderOnce, Style, StyleRefinement, TextStyle, 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,
}
impl<V: Render> From<Entity<V>> for AnyView {
fn from(value: Entity<V>) -> Self {
AnyView {
entity: value.into_any(),
render: any_view::render::<V>,
}
}
}
impl AnyView {
pub fn cached(self, style: StyleRefinement) -> ViewElement<AnyView> {
ViewElement::new(self).cached(style)
}
pub fn downgrade(&self) -> AnyWeakView {
AnyWeakView {
entity: self.entity.downgrade(),
render: self.render,
}
}
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,
}),
}
}
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())
}
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
(self.render)(&self, window, cx)
}
}
impl<V: 'static + Render> IntoElement for Entity<V> {
type Element = ViewElement<Entity<V>>;
fn into_element(self) -> Self::Element {
ViewElement::new(self)
}
#[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 {
ViewElement::new(self)
}
}
pub struct AnyWeakView {
entity: AnyWeakEntity,
render: fn(&AnyView, &mut Window, &mut App) -> AnyElement,
}
impl AnyWeakView {
pub fn upgrade(&self) -> Option<AnyView> {
let entity = self.entity.upgrade()?;
Some(AnyView {
entity,
render: self.render,
})
}
}
impl<V: 'static + Render> From<WeakEntity<V>> for AnyWeakView {
fn from(view: WeakEntity<V>) -> Self {
AnyWeakView {
entity: view.into(),
render: any_view::render::<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
.core
.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::new(self).cached(style)
}
}
#[doc(hidden)]
pub struct ViewElement<V: View> {
view: Option<V>,
entity_id: Option<EntityId>,
cached_style: Option<StyleRefinement>,
#[cfg(debug_assertions)]
source: &'static core::panic::Location<'static>,
}
impl<V: View> ViewElement<V> {
#[track_caller]
pub fn new(view: V) -> Self {
let entity_id = view.entity_id();
ViewElement {
entity_id,
cached_style: None,
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
}
}
impl<V: View> IntoElement for ViewElement<V> {
type Element = Self;
fn into_element(self) -> Self::Element {
self
}
}
pub(crate) struct ViewElementState {
prepaint_range: Range<PrepaintStateIndex>,
paint_range: Range<PaintIndex>,
cache_key: ViewElementCacheKey,
accessed_entities: FxHashSet<EntityId>,
}
pub(crate) struct ViewElementCacheKey {
bounds: Bounds<Pixels>,
content_mask: ContentMask<Pixels>,
text_style: TextStyle,
}
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>,
window: &mut Window,
cx: &mut App,
) -> (LayoutId, Self::RequestLayoutState) {
if let Some(entity_id) = self.entity_id {
let view = &mut self.view;
request_layout_view(
entity_id,
self.cached_style.as_ref(),
window,
cx,
&mut |window, cx| view.take().unwrap().render(window, cx).into_any_element(),
)
} else {
request_layout_component(type_name::<V>(), window, cx, &mut |window, cx| {
self.view
.take()
.unwrap()
.render(window, cx)
.into_any_element()
})
}
}
fn prepaint(
&mut self,
global_id: Option<&GlobalElementId>,
bounds: Bounds<Pixels>,
element: &mut Self::RequestLayoutState,
window: &mut Window,
cx: &mut App,
) -> Option<AnyElement> {
if let Some(entity_id) = self.entity_id {
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);
}
prepaint_cached_view(entity_id, global_id, bounds, window, cx, |window, cx| {
self.view
.take()
.unwrap()
.render(window, cx)
.into_any_element()
})
})
} else {
prepaint_component(type_name::<V>(), element, window, cx)
}
}
fn paint(
&mut self,
global_id: Option<&GlobalElementId>,
_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 {
paint_view(
entity_id,
self.cached_style.is_some(),
global_id,
element,
window,
cx,
);
} 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
}
}
pub(crate) fn prepaint_cached_view(
entity_id: EntityId,
global_id: Option<&GlobalElementId>,
bounds: Bounds<Pixels>,
window: &mut Window,
cx: &mut App,
build: impl FnOnce(&mut Window, &mut App) -> AnyElement,
) -> Option<AnyElement> {
window.with_element_state::<ViewElementState, _>(global_id.unwrap(), |element_state, window| {
let content_mask = window.content_mask();
let text_style = window.text_style();
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
&& !window.frame_state.dirty_views.contains(&entity_id)
&& !window.core.refreshing
{
let prepaint_start = window.prepaint_index();
window.reuse_prepaint(element_state.prepaint_range.clone());
cx.entities
.extend_accessed(&element_state.accessed_entities);
let prepaint_end = window.prepaint_index();
element_state.prepaint_range = prepaint_start..prepaint_end;
return (None, element_state);
}
let refreshing = mem::replace(&mut window.core.refreshing, true);
let prepaint_start = window.prepaint_index();
let (mut element, accessed_entities) = cx.detect_accessed_entities(|cx| {
let mut element = build(window, cx);
element.layout_as_root(bounds.size.into(), window, cx);
element.prepaint_at(bounds.origin, window, cx);
element
});
let prepaint_end = window.prepaint_index();
window.core.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,
},
},
)
})
}
#[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_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)]
pub(crate) 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();
if let Some(element) = element {
let refreshing = mem::replace(&mut window.core.refreshing, true);
element.paint(window, cx);
window.core.refreshing = refreshing;
} else {
window.reuse_paint(element_state.paint_range.clone());
}
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 tests {
use std::{cell::Cell, rc::Rc};
use crate::{
AnyWindowHandle, AppContext as _, Context, Entity, IntoElement, ParentElement as _, Render,
StyleRefinement, Styled as _, TestAppContext, Window, div, green, px, size,
};
struct CountedView {
renders: Rc<Cell<usize>>,
}
impl Render for CountedView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
self.renders.set(self.renders.get() + 1);
div().w(px(10.)).h(px(10.)).bg(green())
}
}
struct CachedViewHost {
view: Entity<CountedView>,
}
impl Render for CachedViewHost {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
div().size_full().child(
self.view
.clone()
.cached(StyleRefinement::default().size_full()),
)
}
}
fn draw(cx: &mut TestAppContext, window: AnyWindowHandle) -> usize {
cx.update_window(window, |_, window, cx| {
window.draw(cx).clear(cx);
window.frame_state.rendered_frame.scene.quads.len()
})
.unwrap()
}
#[gpui::test]
fn a_cached_view_reuses_its_subtree_until_it_is_notified_or_resized(cx: &mut TestAppContext) {
let renders = Rc::new(Cell::new(0));
let view = cx.new({
let renders = renders.clone();
move |_| CountedView { renders }
});
let window: AnyWindowHandle = cx
.add_window({
let view = view.clone();
move |_, _| CachedViewHost { view }
})
.into();
let first = draw(cx, window);
assert_eq!(renders.get(), 1, "the first frame renders the view");
assert!(first > 0, "the view's content is painted");
let second = draw(cx, window);
assert_eq!(renders.get(), 1, "a clean cached view is not re-rendered");
assert_eq!(
second, first,
"the reused subtree is still painted into the scene"
);
view.update(cx, |_, cx| cx.notify());
draw(cx, window);
assert!(renders.get() > 1, "notifying the view re-renders it");
let renders_before_resize = renders.get();
cx.simulate_window_resize(window, size(px(400.), px(300.)));
draw(cx, window);
assert!(
renders.get() > renders_before_resize,
"resizing the window re-renders the cached view"
);
}
}