Fix path undo repaint and restore Apply

This commit is contained in:
chasse20 committed 2026-11-10 21:07:57 -05:00
1 parent 2f2ba103be
commit f17e524776
16 files changed
+170 -22

No files matched your search

+21 -14
View File
@@ -166,6 +166,7 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// Set the curve from command parameters, then preview or commit it in the supplied viewport
fn path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "tool.path";
if s.tool.tool != Tool::Path {
@@ -232,6 +233,7 @@ fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathSh
Ok((eid, i, shape))
}
/// Finish any draft and load a stored path's geometry and paint settings for live editing
fn edit_path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "path.edit";
let (eid, index, shape) = path_ref(s, CMD, p)?;
@@ -249,6 +251,7 @@ fn edit_path(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() }))
}
/// Remove one stored curve and repaint its sublayer as an atomic document edit
fn remove_path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "path.remove";
let (eid, index, _) = path_ref(s, CMD, p)?;
@@ -592,27 +595,31 @@ impl Session {
self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path))
}
/// Undo (`back`) or redo the edited path's last point change, false when there is none; with no points left the path is gone
pub(crate) fn step_path(&mut self, back: bool) -> bool {
/// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history
pub(crate) fn step_path(&mut self, back: bool) -> Result<bool> {
if self.tool.tool != Tool::Path {
return false;
return Ok(false);
}
let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) };
// A checkpoint taken by a press that changed nothing isn't a step
while from.last().is_some_and(|s| s.same_curve(&self.tool.path)) {
from.pop();
}
let Some(state) = from.pop() else { return false };
// Skip no-change checkpoints without consuming history until the repaint succeeds
let from = if back { &self.path_steps.0 } else { &self.path_steps.1 };
let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) };
let path = &mut self.tool.path;
let now = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state });
to.push(now);
let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() });
if let Err(error) = self.path_live() {
self.tool.path = previous;
return Err(error);
}
if self.tool.path.points.is_empty() {
self.stop_path_edit();
} else {
let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) };
from.truncate(index);
to.push(previous);
}
true
Ok(true)
}
/// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes
@@ -989,7 +996,7 @@ mod tests {
session.tool.path.points = vec![Vec3::ZERO; MAX_PATH_POINTS];
session.path_checkpoint();
assert!(!session.path_step_pending(true));
assert!(!session.step_path(true));
assert!(!session.step_path(true).unwrap());
for index in 0..crate::session::MAX_HISTORY + 10 {
session.path_checkpoint();
@@ -999,7 +1006,7 @@ mod tests {
assert_eq!(session.path_steps.0.len(), crate::session::MAX_HISTORY);
assert_eq!(session.path_steps.0.iter().map(|state| state.points.len()).sum::<usize>(), crate::session::MAX_HISTORY * MAX_PATH_POINTS);
session.path_checkpoint();
assert!(session.step_path(true), "a no-change checkpoint does not consume an undo");
assert!(session.step_path(true).unwrap(), "a no-change checkpoint does not consume an undo");
assert_eq!(session.tool.path.points[0].x, (crate::session::MAX_HISTORY + 9) as f32);
}
+12 -2
View File
@@ -647,24 +647,32 @@ impl Session {
}
}
/// Whether a point edit, an uncommitted path preview, or a document edit can be undone
pub fn can_undo(&self) -> bool {
!self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true)
}
/// Whether a point edit or document edit can be restored
pub fn can_redo(&self) -> bool {
!self.redo.is_empty() || self.path_step_pending(false)
}
/// Label of the next undo action, giving an active path's point edits and preview priority
pub fn undo_label(&self) -> Option<&str> {
if self.path_draft.is_some() || self.path_step_pending(true) {
return Some(crate::path_tool::NEW_PATH_LABEL);
}
self.undo.last().map(|(l, _)| l.as_str())
}
/// Label of the next redo action, giving an active path's point history priority
pub fn redo_label(&self) -> Option<&str> {
if self.path_step_pending(false) {
return Some(crate::path_tool::NEW_PATH_LABEL);
}
self.redo.last().map(|(l, _)| l.as_str())
}
/// The undone steps, the next one to redo first.
pub fn redo_labels(&self) -> Vec<String> {
self.redo.iter().rev().map(|(l, _)| l.clone()).collect()
@@ -673,13 +681,14 @@ impl Session {
self.undo.iter().map(|(l, _)| l.clone()).collect()
}
/// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order
pub fn undo(&mut self) -> Result<String> {
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
self.cancel_stroke();
self.end_polygon_fill_box();
// While a path is edited, undo steps back through its point changes first
if self.step_path(true) {
if self.step_path(true)? {
return Ok(crate::path_tool::NEW_PATH_LABEL.to_string());
}
@@ -699,12 +708,13 @@ impl Session {
Ok(label)
}
/// Restore a point edit and its pixels before considering document redo
pub fn redo(&mut self) -> Result<String> {
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
self.cancel_stroke();
self.end_polygon_fill_box();
if self.step_path(false) {
if self.step_path(false)? {
return Ok(crate::path_tool::NEW_PATH_LABEL.to_string());
}
+4
View File
@@ -6,11 +6,13 @@ use serde_json::json;
use texturecraft_engine::execute;
use texturecraft_engine::geom::glam::Vec2;
/// Sort a nonempty timing sample in place and report its middle value in milliseconds
fn median_ms(samples: &mut [Duration]) -> f64 {
samples.sort_unstable();
samples[samples.len() / 2].as_secs_f64() * 1_000.0
}
/// Separate repaint cost from dirty-tile and full-set compositing across representative brush sizes
#[test]
#[ignore = "release benchmark: two texture resolutions and brush sizes"]
fn path_preview_timings() {
@@ -62,12 +64,14 @@ fn path_preview_timings() {
}
}
/// Observe resident memory without treating allocator-retained pages as a leak
#[cfg(target_os = "linux")]
fn resident_kib() -> usize {
let status = std::fs::read_to_string("/proc/self/status").unwrap();
status.lines().find_map(|line| line.strip_prefix("VmRSS:").and_then(|rest| rest.split_whitespace().next()).and_then(|n| n.parse().ok())).unwrap()
}
/// Check that repeated canceled previews release tile buffers and leave no document history
#[cfg(target_os = "linux")]
#[test]
#[ignore = "release memory soak: 1,000 edits across 100 canceled previews"]
+84 -6
View File
@@ -517,6 +517,7 @@ fn preview_uses_the_commands_explicit_viewport() {
assert_eq!(preview, path_pixels(&direct));
}
/// Headless history commands must restore geometry and pixels before any frame or subsequent edit
#[test]
fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() {
let mut session = session(wall());
@@ -524,33 +525,110 @@ fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() {
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
let original = session.tool.path.points.clone();
let original_pixels = session.doc.pixels.clone();
let history = session.history_labels().len();
session.insert_path_point(1, Vec3::new(0.5, 0.5, 0.0));
session.path_live().unwrap();
let inserted = session.tool.path.points.clone();
let inserted_pixels = session.doc.pixels.clone();
session.move_path_point(1, Vec3::new(0.5, 0.6, 0.0), true);
session.move_path_point(1, Vec3::new(0.5, 0.7, 0.0), false);
session.path_live().unwrap();
let moved = session.tool.path.points.clone();
let moved_pixels = session.doc.pixels.clone();
session.remove_selected_path_point();
session.path_live().unwrap();
let removed = session.tool.path.points.clone();
let removed_pixels = session.doc.pixels.clone();
for expected in [&moved, &inserted, &original] {
session.undo().unwrap();
session.path_live().unwrap();
for (expected, pixels) in [(&moved, &moved_pixels), (&inserted, &inserted_pixels), (&original, &original_pixels)] {
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(&session.tool.path.points, expected);
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
assert_eq!(session.doc.pixels.layers, pixels.layers);
assert_eq!(session.doc.pixels.masks, pixels.masks);
}
session.select_path_point(0);
assert!(session.can_redo(), "selection must preserve point redo");
for expected in [&inserted, &moved, &removed] {
session.redo().unwrap();
session.path_live().unwrap();
for (expected, pixels) in [(&inserted, &inserted_pixels), (&moved, &moved_pixels), (&removed, &removed_pixels)] {
execute(&mut session, "edit.redo", &Value::Null).unwrap();
assert_eq!(&session.tool.path.points, expected);
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
assert_eq!(session.doc.pixels.layers, pixels.layers);
assert_eq!(session.doc.pixels.masks, pixels.masks);
}
assert_eq!(session.history_labels().len(), history + 1, "all point edits share one document step");
execute(&mut session, "edit.undo", &Value::Null).unwrap();
execute(&mut session, "layer.add.paint", &Value::Null).unwrap();
execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(session.paths(effect).unwrap()[0].points, moved.iter().map(|point| point.to_array()).collect::<Vec<_>>());
assert_eq!(session.doc.pixels.layers, moved_pixels.layers, "a subsequent command keeps the undone path pixels");
}
/// A bad path above the edited one must not consume undo or redo when repainting fails
#[test]
fn point_history_repaint_errors_preserve_the_edit_and_can_be_retried() {
use texturecraft_engine::core::{EffectKind, LayerId};
let mut session = session(wall());
let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap();
let effect = LayerId(report["committed"]["effect"].as_u64().unwrap());
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap();
let paint = session.paths(effect).unwrap()[1].paint.clone();
execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
let original = session.tool.path.points.clone();
session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true);
session.path_live().unwrap();
let moved = session.tool.path.points.clone();
for (command, expected) in [("edit.undo", &original), ("edit.redo", &moved)] {
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") };
paths[1].paint = Value::Null;
let before = session.doc.clone();
let path = session.tool.path.clone();
let history = (session.history_labels(), session.redo_labels());
let error = execute(&mut session, command, &Value::Null).unwrap_err();
assert!(error.to_string().contains("unreadable path settings"), "{error}");
assert_eq!(session.tool.path, path);
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
assert_eq!((session.history_labels(), session.redo_labels()), history);
let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") };
paths[1].paint = paint.clone();
execute(&mut session, command, &Value::Null).unwrap();
assert_eq!(&session.tool.path.points, expected, "the failed step remains available");
assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::<Vec<_>>());
}
}
/// Point history repaints an uncommitted preview without creating document undo steps
#[test]
fn draft_point_history_repaints_immediately_and_undoing_all_points_cancels() {
let mut session = session(wall());
execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap();
let before = session.doc.clone();
let history = session.history_labels();
session.append_path_point(Vec3::new(0.2, 0.5, 0.0), true);
session.path_live().unwrap();
let one_point = session.doc.clone();
session.append_path_point(Vec3::new(0.8, 0.5, 0.0), true);
session.path_live().unwrap();
let two_points = session.doc.clone();
for (command, expected) in [("edit.undo", &one_point), ("edit.redo", &two_points), ("edit.undo", &one_point), ("edit.undo", &before)] {
execute(&mut session, command, &Value::Null).unwrap();
assert_eq!(session.doc.project, expected.project);
assert_eq!(session.doc.pixels.layers, expected.pixels.layers);
assert_eq!(session.history_labels(), history);
}
assert!(session.tool.path.points.is_empty());
assert!(session.tool.path.editing.is_none());
}
#[test]
+1
View File
@@ -84,6 +84,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "مستوى تباين الخواص"),
("Antialiasing", "تنعيم الحواف"),
("Aperture", "فتحة العدسة"),
("Apply", "تطبيق"),
("ArtCraft website...", "موقع ArtCraft الإلكتروني..."),
("Assets", "الأصول"),
("Auto", "تلقائي"),
+1
View File
@@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "Anisotropiestärke"),
("Antialiasing", "Kantenglättung"),
("Aperture", "Blende"),
("Apply", "Anwenden"),
("ArtCraft website...", "ArtCraft-Website..."),
("Assets", "Assets"),
("Auto", "Auto"),
+1
View File
@@ -84,6 +84,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "Nivel de anisotropía"),
("Antialiasing", "Antialiasing"),
("Aperture", "Apertura"),
("Apply", "Aplicar"),
("ArtCraft website...", "Sitio web de ArtCraft..."),
("Assets", "Recursos"),
("Auto", "Auto"),
+1
View File
@@ -90,6 +90,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "Niveau d'anisotropie"),
("Antialiasing", "Anticrénelage"),
("Aperture", "Ouverture"),
("Apply", "Appliquer"),
("ArtCraft website...", "Site web d'ArtCraft..."),
("Assets", "Ressources"),
("Auto", "Auto"),
+1
View File
@@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "Livello anisotropia"),
("Antialiasing", "Antialiasing"),
("Aperture", "Apertura"),
("Apply", "Applica"),
("ArtCraft website...", "Sito web di ArtCraft..."),
("Assets", "Risorse"),
("Auto", "Auto"),
+1
View File
@@ -90,6 +90,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "異方性レベル"),
("Antialiasing", "アンチエイリアス"),
("Aperture", "絞り"),
("Apply", "適用"),
("ArtCraft website...", "ArtCraft ウェブサイト..."),
("Assets", "アセット"),
("Auto", "自動"),
+1
View File
@@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "이방성 레벨"),
("Antialiasing", "안티앨리어싱"),
("Aperture", "조리개"),
("Apply", "적용"),
("ArtCraft website...", "ArtCraft 웹사이트..."),
("Assets", "에셋"),
("Auto", "자동"),
+1
View File
@@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "Nível de anisotropia"),
("Antialiasing", "Antisserrilhamento"),
("Aperture", "Abertura"),
("Apply", "Aplicar"),
("ArtCraft website...", "Site da ArtCraft..."),
("Assets", "Recursos"),
("Auto", "Auto"),
+1
View File
@@ -75,6 +75,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Anisotropy level", "各向异性强度"),
("Antialiasing", "抗锯齿"),
("Aperture", "光圈"),
("Apply", "应用"),
("ArtCraft website...", "ArtCraft 网站..."),
("Assets", "资产"),
("Auto", "自动"),
+1
View File
@@ -17,6 +17,7 @@ pub(crate) struct PathSurfaceCache {
}
impl PathSurfaceCache {
/// Reuse an unchanged curve and retain it for this pass; UV or missing paths have no surface curve
pub(crate) fn get(&mut self, session: &Session, effect: LayerId, index: usize) -> Option<SurfaceCurve> {
let shape = session.paths(effect)?.get(index)?;
let key = (session.mesh_id, effect, index);
+5
View File
@@ -328,6 +328,7 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
let path = &app.session.tool.path;
let (closed, fill) = (path.closed, path.fill);
let selected = path.selected.is_some_and(|i| i < path.points.len());
let has_points = !path.points.is_empty();
if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() {
app.session.set_path_closed(!closed);
}
@@ -340,6 +341,10 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::BACKSPACE, tr("Remove point"), false, button_size)).inner.clicked() {
app.session.remove_selected_path_point();
}
if ui.add_enabled_ui(has_points, |ui| icon_button(ui, ic::CHECK, tr("Apply"), false, button_size)).inner.clicked() {
app.run("tool.path", json!({"commit": true}));
}
}
pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
+34
View File
@@ -2,6 +2,7 @@
use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use texturecraft_engine::core::LayerId;
use texturecraft_engine::execute;
@@ -15,6 +16,7 @@ const A: Pos2 = pos2(600.0, 500.0);
const B: Pos2 = pos2(700.0, 500.0);
const C: Pos2 = pos2(800.0, 500.0);
/// A Path tool session whose texture fills the test pointer coordinates in the 2D view
fn harness() -> AppHarness<'static> {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
@@ -26,6 +28,7 @@ fn harness() -> AppHarness<'static> {
h
}
/// Advance one input frame, optionally changing the primary button's state
fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option<bool>) {
let events = &mut h.input_mut().events;
events.push(Event::PointerMoved(pos));
@@ -35,12 +38,14 @@ fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option<bool>) {
h.step();
}
/// Send a complete pointer click and allow the resulting preview to update
fn click(h: &mut AppHarness<'_>, at: Pos2) {
pointer(h, at, Some(true));
pointer(h, at, Some(false));
h.run_steps(2);
}
/// Move through several frames so the test exercises drag grouping as well as its final position
fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) {
pointer(h, from, Some(true));
for k in 1..=6 {
@@ -50,6 +55,7 @@ fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) {
h.run_steps(2);
}
/// Dispatch an unmodified tool key and settle the resulting UI state
fn key(h: &mut AppHarness<'_>, key: Key) {
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
h.run_steps(2);
@@ -85,6 +91,34 @@ fn placing_points_previews_the_path_and_enter_applies_it_as_one_step() {
assert_eq!(path_sublayers(&h), vec![(eid, 1)]);
}
/// Applying with the pointer commits the preview without leaving the current texture set
#[test]
fn apply_button_commits_the_path_in_the_current_texture_set() {
let mut h = harness();
assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled());
let steps = h.state().session.history_labels().len();
let texture_set = h.state().session.ts();
for at in [A, B, C] {
click(&mut h, at);
}
let paths = path_sublayers(&h);
let preview = h.state().session.doc.pixels.layers.clone();
// Path controls share the horizontally scrolling brush toolbar
h.get_all_by_label("Apply").next().unwrap().scroll_to_me();
h.run_steps(30);
assert!(!h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled());
h.get_all_by_label("Apply").next().unwrap().click();
h.run_steps(2);
assert_eq!(h.state().session.ts(), texture_set);
assert_eq!(h.state().session.history_labels().len(), steps + 1);
assert!(h.state().session.tool.path.points.is_empty());
assert_eq!(path_sublayers(&h), paths);
assert_eq!(h.state().session.doc.pixels.layers, preview);
assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled());
}
#[test]
fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() {
let mut h = harness();