cache text buf

This commit is contained in:
2025-09-20 12:49:55 -04:00
parent 2d7484a631
commit 949c9df0a0
3 changed files with 44 additions and 9 deletions

View File

@@ -1,9 +1,9 @@
use cosmic_text::{Attrs, Family, FontSystem, Metrics, Shaping}; use cosmic_text::{Attrs, Family, FontSystem, Metrics, Shaping};
use crate::prelude::*; use crate::{prelude::*, util::MutDetect};
pub struct Text { pub struct Text {
pub content: String, pub content: MutDetect<String>,
pub attrs: TextAttrs, pub attrs: TextAttrs,
/// inner alignment of text region (within where its drawn) /// inner alignment of text region (within where its drawn)
pub align: Align, pub align: Align,
@@ -32,7 +32,7 @@ impl Text {
pub fn new(content: impl Into<String>) -> Self { pub fn new(content: impl Into<String>) -> Self {
let attrs = TextAttrs::default(); let attrs = TextAttrs::default();
Self { Self {
content: content.into(), content: content.into().into(),
buf: TextBuffer::new_empty(Metrics::new(attrs.font_size, attrs.line_height)), buf: TextBuffer::new_empty(Metrics::new(attrs.font_size, attrs.line_height)),
attrs, attrs,
align: Align::Center, align: Align::Center,
@@ -49,6 +49,8 @@ impl Text {
font_system, font_system,
Metrics::new(self.attrs.font_size, self.attrs.line_height), Metrics::new(self.attrs.font_size, self.attrs.line_height),
); );
if self.content.changed {
self.content.changed = false;
self.buf.set_text( self.buf.set_text(
font_system, font_system,
&self.content, &self.content,
@@ -57,6 +59,7 @@ impl Text {
); );
} }
} }
}
impl Widget for Text { impl Widget for Text {
fn draw(&mut self, painter: &mut Painter) { fn draw(&mut self, painter: &mut Painter) {

30
src/util/change.rs Normal file
View File

@@ -0,0 +1,30 @@
use std::ops::{Deref, DerefMut};
pub struct MutDetect<T> {
inner: T,
pub changed: bool,
}
impl<T> Deref for MutDetect<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T> DerefMut for MutDetect<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.changed = true;
&mut self.inner
}
}
impl<T> From<T> for MutDetect<T> {
fn from(inner: T) -> Self {
MutDetect {
inner,
changed: true,
}
}
}

View File

@@ -1,9 +1,11 @@
mod borrow; mod borrow;
mod change;
mod id; mod id;
mod math; mod math;
mod refcount; mod refcount;
pub(crate) use borrow::*; pub(crate) use borrow::*;
pub use change::*;
pub(crate) use id::*; pub(crate) use id::*;
pub(crate) use math::*; pub(crate) use math::*;
pub(crate) use refcount::*; pub(crate) use refcount::*;