PhotoCraft: An open-source, photo editor written by scratch in pure Rust
perf(type): refresh type layers without cloning the document (#7092)
Nicolas Falesyc05d827fdea5
diff --git a/crates/engine/src/edit_menu_cmds.rs b/crates/engine/src/edit_menu_cmds.rsindex 11e227360..12cb62a41 100644--- a/crates/engine/src/edit_menu_cmds.rs+++ b/crates/engine/src/edit_menu_cmds.rs@@ -902,13 +902,13 @@ fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {return Ok(json!({"count": 0, "layers": 0}));}s.edit("Replace All Text", |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());for (id, matches) in &plan {if let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) {for (a, b) in matches.iter().rev() {crate::type_cmds::replace_text(t, *a, *b, &replace);}- crate::type_cmds::refresh(&snapshot, t);+ crate::type_cmds::refresh_at(dpi, format, t);}}Ok(())@@ -926,10 +926,10 @@ fn find_replace(s: &mut Session, p: &Value) -> Result<Value> {{crate::type_cmds::check_text_unlocked(&doc, id)?;s.edit("Replace Text", |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) {crate::type_cmds::replace_text(t, a, b, &replace);- crate::type_cmds::refresh(&snapshot, t);+ crate::type_cmds::refresh_at(dpi, format, t);}Ok(())})?;diff --git a/crates/engine/src/type_cmds.rs b/crates/engine/src/type_cmds.rsindex d6b92e840..b31820dec 100644--- a/crates/engine/src/type_cmds.rs+++ b/crates/engine/src/type_cmds.rs@@ -8,7 +8,7 @@use std::sync::Arc;-use photocraft_color::Color;+use photocraft_color::{Color, PixelFormat};use photocraft_doc::text::{AntiAlias, Caps, CharStyle, FontFeature, FontVariation, Kerning, Orientation, ParagraphRun, ParagraphStyle, TextAlign, TextDirection, TextRun, TextShape,};@@ -534,9 +534,15 @@ pub fn replace_text(t: &mut TextLayer, a: usize, b: usize, new: &str) {/// Re-renders the layer's pixels and regenerates its PSD `TySh` data.pub fn refresh(doc: &Document, t: &mut TextLayer) {- let dpi = doc.resolution_dpi;+ refresh_at(doc.resolution_dpi, doc.pixel_format(), t);+}++/// [`refresh`] given only the two things it reads from the document: its resolution and its+/// pixel format. A caller holding the layer mutably reads them first instead of cloning the whole+/// document to pass it, once per keystroke and pointer move while typing (#7092).+pub fn refresh_at(dpi: f32, format: PixelFormat, t: &mut TextLayer) {let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());- let (layout, r) = eng.render(t, dpi, doc.pixel_format());+ let (layout, r) = eng.render(t, dpi, format);t.cache = Some(r.surface);t.psd_raw = Some(Arc::new(photocraft_text::psd::build_tysh(t, dpi, layout.bounds())));}@@ -553,11 +559,12 @@ pub(crate) fn check_text_unlocked(doc: &Document, id: LayerId) -> Result<()> {/// Runs `f` on a type layer as one undo step. `f` may set an explicit layer name (`type.edit`'s/// `name`), which is applied in the same step; otherwise an auto-named layer follows its text.-fn with_text_layer<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut TextLayer, &Document, &mut Option<String>) -> Result<R>) -> Result<R> {+/// `f` gets the document's resolution (dpi).+fn with_text_layer<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut TextLayer, f32, &mut Option<String>) -> Result<R>) -> Result<R> {let id = layer_id(s, p)?;check_text_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?;let (r, damage) = s.edit(label, |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;let auto_named = is_auto_named(l);let LayerContent::Text(t) = &mut l.content else {@@ -565,8 +572,8 @@ fn with_text_layer<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&m};let before = t.cache.as_ref().map(|c| c.tile_bounds());let mut rename = None;- let r = f(t, &snapshot, &mut rename)?;- refresh(&snapshot, t);+ let r = f(t, dpi, &mut rename)?;+ refresh_at(dpi, format, t);// Only this layer's pixels changed: the canvas recomposites their old and new area// instead of the whole document (#124). Unknown old pixels mean a full refresh.let damage = before.zip(t.cache.as_ref().map(|c| c.tile_bounds())).map(|(a, b)| a.union(&b));@@ -629,14 +636,14 @@ pub(crate) fn with_text_targets() -> Result<Vec<LayerId>> {let ids = format_targets(s, p)?;let damage = s.edit(label, |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());let mut damage = Some(photocraft_geom::Rect::EMPTY);for id in &ids {let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) else { return Err(EngineError::NoLayer(*id)) };let before = t.cache.as_ref().map(|c| c.tile_bounds());let range = if p.get("layers").is_none() || p.get("layer").is_some() { range_param(&t.text, p) } else { (0, t.text.len()) };f(t, range)?;- refresh(&snapshot, t);+ refresh_at(dpi, format, t);// An unknown old/new cache retains Session.edit's full-refresh fallback.damage = damage.zip(before).zip(t.cache.as_ref().map(|c| c.tile_bounds())).map(|((all, a), b)| all.union(&a).union(&b));}@@ -856,7 +863,7 @@ pub fn specs() -> Vec<CommandSpec> {}};let label = if kern_pair.is_some() { "Kerning" } else { "Edit Type" };- with_text_layer(s, p, label, |t, doc, rename| {+ with_text_layer(s, p, label, |t, dpi, rename| {if let Some((at, by)) = kern_pair {// Photoshop's Alt+←/→: the pair before the caret becomes manually kerned,// starting from what it shows now (its metrics/optical or manual value).@@ -868,7 +875,7 @@ pub fn specs() -> Vec<CommandSpec> {let b = byte_at(&t.text, at);let now = {let mut eng = photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner());- eng.pair_kerning(t, doc.resolution_dpi, a)+ eng.pair_kerning(t, dpi, a)}.ok_or_else(|| bad("type.edit", "no kerning pair at the caret (line break or line end)"))?;let value = (f64::from(now.round()) + by).clamp(KERN_MIN, KERN_MAX) as f32;@@ -984,16 +991,16 @@ pub fn specs() -> Vec<CommandSpec> {run: |s, p| {let id = layer_id(s, p)?;s.edit("Rasterize Type", |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;let LayerContent::Text(t) = &mut l.content else {return Err(EngineError::Other(format!("layer {} is not a type layer", id.0)));};if t.cache.is_none() {- refresh(&snapshot, t);+ refresh_at(dpi, format, t);}- let surface = t.cache.take().unwrap_or_else(|| photocraft_raster::Surface::new(snapshot.pixel_format()));- let surface = if surface.format() == snapshot.pixel_format() { surface } else { surface.convert(snapshot.pixel_format()) };+ let surface = t.cache.take().unwrap_or_else(|| photocraft_raster::Surface::new(format));+ let surface = if surface.format() == format { surface } else { surface.convert(format) };l.content = LayerContent::Raster(surface);l.psd_blocks.retain(|(k, _)| k != b"TySh");Ok(())diff --git a/crates/engine/src/type_extra_cmds.rs b/crates/engine/src/type_extra_cmds.rsindex efa2d791c..275531501 100644--- a/crates/engine/src/type_extra_cmds.rs+++ b/crates/engine/src/type_extra_cmds.rs@@ -15,7 +15,8 @@ use serde_json::{Value, json};use crate::commands::{CommandSpec, layer_param};use crate::type_cmds::{- check_text_unlocked, format_targets, has_format_target, is_auto_named, layer_name, refresh, replace_text, style_paragraphs, style_range, with_text_targets,+ check_text_unlocked, format_targets, has_format_target, is_auto_named, layer_name, refresh_at, replace_text, style_paragraphs, style_range,+ with_text_targets,};use crate::{EngineError, Result, Session};@@ -68,19 +69,20 @@ fn has_defaults(s: &Session) -> std::result::Result<(), String> {// ---------- helpers -----------/// Edits a type layer as one history step and re-renders it.-fn with_text<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut TextLayer, &Document) -> Result<R>) -> Result<R> {+/// Edits a type layer as one history step and re-renders it. `f` gets the document's resolution+/// (dpi).+fn with_text<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut TextLayer, f32) -> Result<R>) -> Result<R> {let id = layer_param(s, p)?;check_text_unlocked(&s.active().ok_or(EngineError::NoDocument)?.doc, id)?;s.edit(label, |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;let auto_named = is_auto_named(l);let LayerContent::Text(t) = &mut l.content else {return Err(EngineError::Other(format!("layer {} is {} {} layer, not a type layer", id.0, l.content.article(), l.content.kind_name())));};- let r = f(t, &snapshot)?;- refresh(&snapshot, t);+ let r = f(t, dpi)?;+ refresh_at(dpi, format, t);let name = auto_named.then(|| layer_name(&t.text));if let Some(n) = name {l.name = n;@@ -90,7 +92,11 @@ fn with_text<R>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut Tex}fn layout(doc: &Document, t: &TextLayer) -> photocraft_text::TextLayout {- photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).layout(t, doc.resolution_dpi)+ layout_at(doc.resolution_dpi, t)+}++fn layout_at(dpi: f32, t: &TextLayer) -> photocraft_text::TextLayout {+ photocraft_text::shared().lock().unwrap_or_else(|e| e.into_inner()).layout(t, dpi)}/// `m ∘ translate(tx, ty)`.@@ -144,11 +150,11 @@ fn set_orientation(s: &mut Session, p: &Value, o: Orientation) -> Result<Value>// ---------- point ⇄ paragraph ----------fn to_paragraph(s: &mut Session, p: &Value) -> Result<Value> {- let r = with_text(s, p, "Convert to Paragraph Text", |t, doc| {- let l = layout(doc, t);- let size_px = t.char_runs().iter().map(|r| r.style.size_pt).fold(t.size_pt, f32::max) * doc.resolution_dpi / 72.0;+ let r = with_text(s, p, "Convert to Paragraph Text", |t, dpi| {+ let l = layout_at(dpi, t);+ let size_px = t.char_runs().iter().map(|r| r.style.size_pt).fold(t.size_pt, f32::max) * dpi / 72.0;let ps = t.paragraph_runs().first().map(|p| p.style.clone()).unwrap_or_default();- let indents = (ps.start_indent_pt + ps.end_indent_pt).max(0.0) * doc.resolution_dpi / 72.0;+ let indents = (ps.start_indent_pt + ps.end_indent_pt).max(0.0) * dpi / 72.0;if l.vertical {// Line space: u along the columns, v across them (first column centred on v = 0).let [u0, v0, u1, v1] = l.line_bounds().unwrap_or([0.0, -size_px / 2.0, size_px, size_px / 2.0]);@@ -178,7 +184,7 @@ fn to_paragraph(s: &mut Session, p: &Value) -> Result<Value> {probe.shape = TextShape::Box { x, y: y0, width, height };// Box text puts the first baseline at the box top plus the ascender height: measure it and// shift the box so that baseline stays at the point-text anchor (y = 0).- let b0 = layout(doc, &probe).lines.first().map_or(0.0, |ln| ln.baseline);+ let b0 = layout_at(dpi, &probe).lines.first().map_or(0.0, |ln| ln.baseline);let y = y0 - b0;t.shape = TextShape::Box { x: 0.0, y: 0.0, width, height };t.transform = then_translate(&t.transform, f64::from(x), f64::from(y));@@ -188,9 +194,9 @@ fn to_paragraph(s: &mut Session, p: &Value) -> Result<Value> {}fn to_point(s: &mut Session, p: &Value) -> Result<Value> {- let r = with_text(s, p, "Convert to Point Text", |t, doc| {+ let r = with_text(s, p, "Convert to Point Text", |t, dpi| {let TextShape::Box { x, y, width, height } = t.shape else { return Err(EngineError::Other("already point text".into())) };- let l = layout(doc, t);+ let l = layout_at(dpi, t);// Vertical type: columns run along the box height.let (x, width) = if l.vertical { (y, height) } else { (x, width) };let baseline = l.lines.first().map_or(0.0, |ln| ln.baseline);@@ -496,11 +502,11 @@ fn paste_lorem(s: &mut Session, p: &Value) -> Result<Value> {fn update_all(s: &mut Session) -> Result<Value> {let mut n = 0;s.edit("Update All Text Layers", |doc, _| {- let snapshot = doc.clone();- let ids: Vec<LayerId> = snapshot.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());+ let ids: Vec<LayerId> = doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();for id in ids {if let Some(Layer { content: LayerContent::Text(t), .. }) = doc.layer_mut(id) {- refresh(&snapshot, t);+ refresh_at(dpi, format, t);n += 1;}}@@ -582,7 +588,7 @@ fn replace_fonts(s: &mut Session, map: &serde_json::Map<String, Value>, all: boo}let mut n = 0;s.edit("Replace Missing Fonts", |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());for id in &ids {if let Some(Layer { content: LayerContent::Text(t), .. }) = doc.layer_mut(*id) {let mut changed = false;@@ -603,7 +609,7 @@ fn replace_fonts(s: &mut Session, map: &serde_json::Map<String, Value>, all: booat += r.len;}if changed {- refresh(&snapshot, t);+ refresh_at(dpi, format, t);n += 1;}}diff --git a/crates/engine/src/type_spell_cmds.rs b/crates/engine/src/type_spell_cmds.rsindex 12a63a364..915b21229 100644--- a/crates/engine/src/type_spell_cmds.rs+++ b/crates/engine/src/type_spell_cmds.rs@@ -16,7 +16,7 @@ use photocraft_text::spell::Dictionary;use serde_json::{Value, json};use crate::commands::{CommandSpec, layer_param};-use crate::type_cmds::{check_text_unlocked, norm_text, refresh, replace_text};+use crate::type_cmds::{check_text_unlocked, norm_text, refresh_at, replace_text};use crate::{EngineError, Result, Session};fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {@@ -102,10 +102,10 @@ fn change(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(cmd, format!("the text at {start}..{end} is {:?}, not {w:?}", &t[a..b])));}s.edit("Check Spelling", |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) {replace_text(t, a, b, &to);- refresh(&snapshot, t);+ refresh_at(dpi, format, t);}Ok(())})?;@@ -129,13 +129,13 @@ fn change_all(s: &mut Session, p: &Value) -> Result<Value> {let count: usize = plan.iter().map(|(_, h)| h.len()).sum();if count > 0 {s.edit("Check Spelling", |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());for (id, hits) in &plan {if let Some(LayerContent::Text(t)) = doc.layer_mut(*id).map(|l| &mut l.content) {for (a, b) in hits.iter().rev() {replace_text(t, *a, *b, &to);}- refresh(&snapshot, t);+ refresh_at(dpi, format, t);}}Ok(())@@ -215,10 +215,10 @@ fn insert_text(s: &mut Session, p: &Value) -> Result<Value> {let (ba, bb) = (byte_at(t, a), byte_at(t, b));let label = p.get("label").and_then(Value::as_str).unwrap_or("Insert Glyph").to_string();s.edit(&label, |doc, _| {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());if let Some(LayerContent::Text(t)) = doc.layer_mut(id).map(|l| &mut l.content) {replace_text(t, ba, bb, &new);- refresh(&snapshot, t);+ refresh_at(dpi, format, t);}Ok(())})?;diff --git a/crates/engine/src/type_styles_cmds.rs b/crates/engine/src/type_styles_cmds.rsindex 797dfe7f8..5d5ade404 100644--- a/crates/engine/src/type_styles_cmds.rs+++ b/crates/engine/src/type_styles_cmds.rs@@ -17,7 +17,7 @@ use photocraft_doc::{Document, LayerContent, LayerId, TextLayer, TextStyles};use serde_json::{Map, Value, json};use crate::commands::CommandSpec;-use crate::type_cmds::{apply_char_props, apply_para_props, refresh};+use crate::type_cmds::{apply_char_props, apply_para_props, refresh_at};use crate::{EngineError, Result, Session};const FAMILY: &str = photocraft_text::fonts::DEFAULT_FAMILY;@@ -291,7 +291,7 @@ fn commit(s: &mut Session, label: &str, new: TextStyles, target: &[Target], op:fn apply_styles(doc: &mut Document, new: &TextStyles, target: &[Target], op: Op) -> usize {let old = doc.text_styles.clone();doc.text_styles = new.clone();- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());let ids: Vec<LayerId> = doc.walk().into_iter().filter(|(_, _, l)| matches!(l.content, LayerContent::Text(_))).map(|(_, _, l)| l.id).collect();let mut changed = 0;for id in ids {@@ -302,7 +302,7 @@ fn apply_styles(doc: &mut Document, new: &TextStyles, target: &[Target], op: Op)None => restyle(t, &old, new, Some((0, 0)), Op::default()),};if did {- refresh(&snapshot, t);+ refresh_at(dpi, format, t);changed += 1;}}@@ -516,7 +516,7 @@ fn delete(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {} else {doc.text_styles.character.retain(|d| d.id != id);}- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());let ids: Vec<LayerId> = doc.walk().into_iter().map(|(_, _, l)| l.id).collect();for lid in ids {let Some(LayerContent::Text(t)) = doc.layer_mut(lid).map(|l| &mut l.content) else { continue };@@ -537,7 +537,7 @@ fn delete(s: &mut Session, p: &Value, paragraph: bool) -> Result<Value> {}}if hit {- refresh(&snapshot, t);+ refresh_at(dpi, format, t);n += 1;}}diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rsindex f42b74484..bd76d9c8f 100644--- a/crates/engine/src/variables_cmds.rs+++ b/crates/engine/src/variables_cmds.rs@@ -165,7 +165,7 @@ fn apply_to_doc(doc: &mut Document, vars: &Variables, set: &DataSet) -> Result<(}}(VarKind::TextReplacement, VarValue::Text(text)) => {- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());if let Some(l) = doc.layer_mut(def.layer)&& let LayerContent::Text(t) = &mut l.content{@@ -180,7 +180,7 @@ fn apply_to_doc(doc: &mut Document, vars: &Variables, set: &DataSet) -> Result<(t.sync_summary();// The compositor draws a type layer from its cache: clearing it left the// layer blank until some other edit re-rendered it (#990).- crate::type_cmds::refresh(&snapshot, t);+ crate::type_cmds::refresh_at(dpi, format, t);}}(VarKind::PixelReplacement { method, align, clip }, VarValue::Pixels(path)) => {diff --git a/crates/engine/src/warp_cmds.rs b/crates/engine/src/warp_cmds.rsindex 5142b0a94..452d600ec 100644--- a/crates/engine/src/warp_cmds.rs+++ b/crates/engine/src/warp_cmds.rs@@ -321,7 +321,7 @@ fn warp_type_layer(s: &mut Session, cmd: &str, id: LayerId, w: &Warp) -> Result<}s.edit("Warp", |doc, _| {let group = crate::transform_cmds::group_locks(doc, id);- let snapshot = doc.clone();+ let (dpi, format) = (doc.resolution_dpi, doc.pixel_format());let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;let locks = l.locks.union(group);if locks.position || locks.all {@@ -329,7 +329,7 @@ fn warp_type_layer(s: &mut Session, cmd: &str, id: LayerId, w: &Warp) -> Result<}let LayerContent::Text(t) = &mut l.content else { return Err(EngineError::Other("not a type layer".into())) };t.warp = tw.clone();- crate::type_cmds::refresh(&snapshot, t);+ crate::type_cmds::refresh_at(dpi, format, t);Ok(())})?;Ok(json!({"layer": id.0, "changed": true, "warp": tw}))