[refactor] Make Ui lighter by using a clone-on-write Arc<Style>

This commit is contained in:
Emil Ernerfeldt 2020-10-12 03:22:41 +02:00
parent 4fab4b30a3
commit ad4f87831b
2 changed files with 10 additions and 11 deletions

View file

@ -26,7 +26,7 @@ struct PaintStats {
#[derive(Default)] #[derive(Default)]
pub struct Context { pub struct Context {
/// The default style for new `Ui`:s /// The default style for new `Ui`:s
style: Mutex<Style>, style: Mutex<Arc<Style>>,
paint_options: Mutex<paint::PaintOptions>, paint_options: Mutex<paint::PaintOptions>,
/// None until first call to `begin_frame`. /// None until first call to `begin_frame`.
fonts: Option<Arc<Fonts>>, fonts: Option<Arc<Fonts>>,
@ -123,13 +123,12 @@ impl Context {
*self.font_definitions.lock() = font_definitions; *self.font_definitions.lock() = font_definitions;
} }
// TODO: return MutexGuard pub fn style(&self) -> Arc<Style> {
pub fn style(&self) -> Style {
lock(&self.style, "style").clone() lock(&self.style, "style").clone()
} }
pub fn set_style(&self, style: Style) { pub fn set_style(&self, style: impl Into<Arc<Style>>) {
*lock(&self.style, "style") = style; *lock(&self.style, "style") = style.into();
} }
pub fn pixels_per_point(&self) -> f32 { pub fn pixels_per_point(&self) -> f32 {
@ -605,7 +604,7 @@ impl Context {
impl Context { impl Context {
pub fn style_ui(&self, ui: &mut Ui) { pub fn style_ui(&self, ui: &mut Ui) {
let mut style = self.style(); let mut style: Style = (*self.style()).clone();
style.ui(ui); style.ui(ui);
self.set_style(style); self.set_style(style);
} }

View file

@ -39,7 +39,7 @@ pub struct Ui {
max_rect: Rect, max_rect: Rect,
/// Override default style in this ui /// Override default style in this ui
style: Style, style: Arc<Style>,
layout: Layout, layout: Layout,
@ -92,7 +92,7 @@ impl Ui {
painter: self.painter.clone(), painter: self.painter.clone(),
min_rect, min_rect,
max_rect, max_rect,
style: self.style().clone(), style: self.style.clone(),
layout, layout,
cursor, cursor,
child_count: 0, child_count: 0,
@ -113,11 +113,11 @@ impl Ui {
/// Mutably borrow internal `Style`. /// Mutably borrow internal `Style`.
/// Changes apply to this `Ui` and its subsequent children. /// Changes apply to this `Ui` and its subsequent children.
pub fn style_mut(&mut self) -> &mut Style { pub fn style_mut(&mut self) -> &mut Style {
&mut self.style Arc::make_mut(&mut self.style) // clone-on-write
} }
pub fn set_style(&mut self, style: Style) { pub fn set_style(&mut self, style: impl Into<Arc<Style>>) {
self.style = style self.style = style.into();
} }
pub fn ctx(&self) -> &Arc<Context> { pub fn ctx(&self) -> &Arc<Context> {