Provide themes to subtrees via context

Co-Authored-By: Mikayla Maki <mikayla@zed.dev>
This commit is contained in:
Nathan Sobo 2023-08-28 15:13:59 -06:00
parent fd1633ac4b
commit 9371754942
8 changed files with 206 additions and 74 deletions

View file

@ -3619,36 +3619,11 @@ impl<V> BorrowWindowContext for LayoutContext<'_, '_, '_, V> {
pub struct PaintContext<'a, 'b, 'c, V> {
pub view_context: &'c mut ViewContext<'a, 'b, V>,
text_style_stack: Vec<TextStyle>,
}
impl<'a, 'b, 'c, V> PaintContext<'a, 'b, 'c, V> {
pub fn new(view_context: &'c mut ViewContext<'a, 'b, V>) -> Self {
Self {
view_context,
text_style_stack: Vec::new(),
}
}
}
impl<'a, 'b, 'c, V> RenderContext<'a, 'b, V> for PaintContext<'a, 'b, 'c, V> {
fn text_style(&self) -> TextStyle {
self.text_style_stack
.last()
.cloned()
.unwrap_or(TextStyle::default(&self.font_cache))
}
fn push_text_style(&mut self, style: TextStyle) {
self.text_style_stack.push(style);
}
fn pop_text_style(&mut self) {
self.text_style_stack.pop();
}
fn as_view_context(&mut self) -> &mut ViewContext<'a, 'b, V> {
&mut self.view_context
Self { view_context }
}
}

View file

@ -1,5 +1,6 @@
use crate::{
elements::AnyRootElement,
fonts::TextStyle,
geometry::{rect::RectF, Size},
json::ToJson,
keymap_matcher::{Binding, KeymapContext, Keystroke, MatchResult},
@ -30,7 +31,7 @@ use sqlez::{
statement::Statement,
};
use std::{
any::TypeId,
any::{type_name, Any, TypeId},
mem,
ops::{Deref, DerefMut, Range, Sub},
};
@ -53,6 +54,8 @@ pub struct Window {
pub(crate) invalidation: Option<WindowInvalidation>,
pub(crate) platform_window: Box<dyn platform::Window>,
pub(crate) rendered_views: HashMap<usize, Box<dyn AnyRootElement>>,
pub(crate) text_style_stack: Vec<TextStyle>,
pub(crate) theme_stack: Vec<Box<dyn Any>>,
titlebar_height: f32,
appearance: Appearance,
cursor_regions: Vec<CursorRegion>,
@ -100,6 +103,8 @@ impl Window {
clicked_region: None,
titlebar_height,
appearance,
text_style_stack: Vec::new(),
theme_stack: Vec::new(),
};
let mut window_context = WindowContext::mutable(cx, &mut window, handle);
@ -1265,6 +1270,40 @@ impl<'a> WindowContext<'a> {
};
handle
}
pub fn text_style(&self) -> TextStyle {
self.window
.text_style_stack
.last()
.cloned()
.unwrap_or(TextStyle::default(&self.font_cache))
}
pub fn push_text_style(&mut self, style: TextStyle) {
self.window.text_style_stack.push(style);
}
pub fn pop_text_style(&mut self) {
self.window.text_style_stack.pop();
}
pub fn theme<T: 'static>(&self) -> &T {
self.window
.theme_stack
.iter()
.rev()
.find_map(|theme| theme.downcast_ref())
.ok_or_else(|| anyhow!("no theme provided of type {}", type_name::<T>()))
.unwrap()
}
pub fn push_theme<T: 'static>(&mut self, theme: T) {
self.window.theme_stack.push(Box::new(theme));
}
pub fn pop_theme(&mut self) {
self.window.theme_stack.pop();
}
}
#[derive(Default)]