Merge pull request #16253 from davidmann4/fix/memo-views-16197-followups

Fix the stale cached states the #16197 review found (#16252)
This commit is contained in:
David Mann authored and GitHub committed 2026-11-22 02:02:45 +01:00
commit 085ca2de1c
11 files changed
+151 -9

No files matched your search

+3 -2
View File
@@ -1300,8 +1300,9 @@ pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result<Value> {
}
let mut before = std::mem::replace(&mut *s.tools.brush, b);
// A brush the call built anew holds a new tip source: when the tip is the one it had, it keeps its revision, so the
// views that show the tip replay.
if s.tools.brush.tip == before.tip {
// views that show the tip replay. A stored tip's equality ignores whether its full bitmap is loaded, so a tip that
// loaded only now keeps the new value: swapping the old one back would drop the bitmap (#16252).
if s.tools.brush.tip == before.tip && s.tools.brush.tip.is_loaded() == before.tip.is_loaded() {
std::mem::swap(&mut s.tools.brush.tip, &mut before.tip);
}
// A coalesced gesture (one slider drag) journals as one call: remember the brush it started from.
+21
View File
@@ -561,6 +561,27 @@ fn the_decoded_tip_cache_stays_within_its_budget() {
assert!(matches!(&*t.tools.brush.tip, TipShape::Stored(r) if r.is_loaded()));
}
/// A stored tip the brush holds unloaded (its file failed to load at startup and is back) loads on the next brush
/// edit, and the brush keeps the loaded bitmap instead of the unloaded tip it compares equal to (#16252).
#[test]
fn a_brush_edit_keeps_a_stored_tip_that_loads_only_now() {
let (s, mem) = library(1, 64);
drop(s);
let mut t = Session::new();
t.attach_preset_store(open(Box::new(mem)));
t.execute("tools.setBrush", json!({"preset": "Big 0"})).unwrap();
if let TipShape::Stored(r) = &mut *t.tools.brush.tip {
r.full = None;
}
assert!(matches!(&*t.tools.brush.tip, TipShape::Stored(r) if !r.is_loaded()), "the tip starts unloaded");
t.execute("tools.setBrush", json!({"brush": {"size": 30}})).unwrap();
assert!(matches!(&*t.tools.brush.tip, TipShape::Stored(r) if r.is_loaded()), "the edit keeps the tip it loaded");
// An edit of a brush whose tip is loaded already keeps the tip and its revision.
let revision = t.tools.brush.tip.revision();
t.execute("tools.setBrush", json!({"brush": {"size": 40}})).unwrap();
assert_eq!(t.tools.brush.tip.revision(), revision, "an unchanged loaded tip keeps its revision");
}
#[test]
fn missing_corrupt_or_unknown_tips_fail_when_used_without_panicking() {
let (s, mem) = library(3, 64);
+23 -1
View File
@@ -27,7 +27,7 @@ impl Session {
&self.docs
}
/// Changes whenever a document is opened, closed or renamed.
/// Changes whenever a document is opened, closed, renamed or moved to another position.
pub fn documents_generation(&self) -> u64 {
self.documents_generation
}
@@ -171,6 +171,10 @@ impl Session {
pub fn move_document(&mut self, from: usize, to: usize) -> Option<usize> {
let active = self.active().map(|d| d.doc.id);
let to = move_item(&mut self.docs, from, to)?;
// The Window menu lists the documents by position: a move changes what each entry opens (#16252).
if to != from {
self.documents_generation = self.documents_generation.wrapping_add(1);
}
self.active = active.and_then(|id| self.docs.iter().position(|d| d.doc.id == id));
self.note_active_change();
Some(to)
@@ -316,4 +320,22 @@ mod document_generation_tests {
session.close(0);
assert_eq!(session.documents_generation(), opened.wrapping_add(1));
}
/// A reorder that leaves the active document where it was still moves the generation: the Window menu's
/// entries open other documents now (#16252).
#[test]
fn document_generation_moves_when_documents_are_reordered() {
let mut session = Session::new();
for _ in 0..3 {
session.add_document(Document::new("test", Size::new(2, 2), ColorMode::Rgb, SampleType::U8), None);
}
session.set_active(0);
let before = session.documents_generation();
assert_eq!(session.move_document(1, 2), Some(2));
assert_eq!(session.active_index(), Some(0), "the active document stays first");
assert_eq!(session.documents_generation(), before.wrapping_add(1));
let moved = session.documents_generation();
assert_eq!(session.move_document(1, 1), Some(1));
assert_eq!(session.documents_generation(), moved, "a move to the same place changes nothing");
}
}
+7
View File
@@ -125,6 +125,13 @@ impl TipShape {
TipShape::Stored(r) => Some(r.bitmap()),
}
}
/// Whether the tip paints with its full bitmap: false only for a stored tip whose bitmap isn't loaded.
pub fn is_loaded(&self) -> bool {
match self {
TipShape::Stored(r) => r.is_loaded(),
TipShape::Round | TipShape::Sampled(_) => true,
}
}
/// The tip's real pixel size (a stored tip's, not its preview's); `None` for a computed tip.
pub fn bitmap_size(&self) -> Option<(u32, u32)> {
match self {
@@ -145,3 +145,34 @@ fn the_held_command_states_equal_a_fresh_build_after_each_step() {
held_is_fresh(&mut h, "a pending crop");
assert!(crate::crop_ui::pending(h.state()), "the crop is pending");
}
/// Merge Channels reads every open grayscale document, not only the active one: a change to a background document
/// moves its state in either direction (#16252).
#[test]
fn merge_channels_follows_a_change_to_a_background_document() {
let mut h = harness_of(|s| {
for _ in 0..3 {
s.execute("file.new", json!({"width": 64, "height": 64, "mode": "grayscale"})).unwrap();
}
s.set_active(0);
});
let merge = |h: &mut H| {
h.run_steps(2);
let merge = CommandRef::from(craft::imaging::ui::channels::ChannelsCommands::MergeChannels);
h.state().framework.held_states.states.get(&merge).is_some_and(|state| state.is_enabled())
};
assert!(merge(&mut h), "three grayscale documents of one size can merge");
// A change to a background document, as a job or a script makes through `Session::document_mut`.
let resize = |h: &mut H, side: u32| {
let s = &mut h.state_mut().session;
let Some(id) = s.documents().get(2).map(|st| st.doc.id) else { panic!("three documents are open") };
let Some(st) = s.document_mut(id) else { panic!("the third document is open") };
std::sync::Arc::make_mut(st.doc_mut()).size = photocraft_geom::Size::new(side, side);
};
resize(&mut h, 32);
assert!(!merge(&mut h), "a background document of another size leaves two to merge");
held_is_fresh(&mut h, "resizing a background document");
resize(&mut h, 64);
assert!(merge(&mut h), "and back at the same size, three again");
held_is_fresh(&mut h, "resizing it back");
}
@@ -44,6 +44,9 @@ pub(crate) struct Session {
target: Target,
opened: PatternFillOptions,
preview: Option<Preview>,
/// The swatches' textures. The picker paints them by id and doesn't ask the texture cache again, so the dialog
/// owns them until it closes: a cached texture would be freed once the cache is full (#16252).
_swatch_textures: Vec<egui::TextureHandle>,
}
impl Session {
@@ -72,16 +75,19 @@ fn start(app: &mut PhotocraftApp, idx: usize, document: DocId, target: Target, o
app.pattern_fill.opens += 1;
let serial = app.pattern_fill.opens;
let ctx = app.ctx().clone();
let swatch_textures: Vec<egui::TextureHandle> =
app.session.patterns.items.iter().map(|p| crate::panels::preset_browser::pattern_texture_handle(&ctx, p)).collect();
let swatches: Vec<PatternSwatch> = app
.session
.patterns
.items
.iter()
.map(|p| PatternSwatch::new(p.id.clone(), p.display_name()).with_picture(crate::panels::preset_browser::pattern_texture(&ctx, p)))
.zip(&swatch_textures)
.map(|(p, texture)| PatternSwatch::new(p.id.clone(), p.display_name()).with_picture(texture.id()))
.collect();
let dialog = PatternFillDialog::new(options.clone(), swatches).canvas(CanvasHost::primary(app, idx).canvas_id());
let id = app.framework.dialogs.open(dialog);
app.pattern_fill.session = Some(Session { serial, document, target, opened: options, preview: None });
app.pattern_fill.session = Some(Session { serial, document, target, opened: options, preview: None, _swatch_textures: swatch_textures });
id
}
@@ -327,3 +327,24 @@ fn a_replaced_or_deleted_edit_target_is_not_previewed_or_committed() {
assert_eq!(*app.session.active().unwrap().doc, *deleted);
assert_eq!(steps(&app), count, "a stale OK adds no History step");
}
/// The picker paints its swatches by texture id and doesn't ask the texture cache again, so the dialog owns them:
/// emptying the cache (as it frees textures once it holds more than its capacity) leaves every swatch, and closing
/// the dialog frees them (#16252).
#[test]
fn the_open_dialog_keeps_its_swatch_textures_when_the_texture_cache_lets_go() {
use craft::ui::primitives::textures::TextureCache;
let mut app = app();
let ctx = app.ctx().clone();
let allocated = |ctx: &egui::Context| ctx.tex_manager().read().num_allocated();
TextureCache::clear(&ctx);
let before = allocated(&ctx);
let patterns = app.session.patterns.items.len();
assert!(patterns > 0, "the library has patterns");
crate::menus::invoke(&mut app, &ctx, cmds::CREATE, json!({})).unwrap();
let dialog = app.framework.dialogs.open_dialogs()[0].id;
TextureCache::clear(&ctx);
assert!(allocated(&ctx) >= before + patterns, "the {patterns} swatches outlive the cache");
cancel(&mut app, dialog);
assert_eq!(allocated(&ctx), before, "closing the dialog frees them");
}
+9
View File
@@ -156,6 +156,15 @@ fn the_held_menu_model_equals_a_fresh_build_after_each_step() {
held_is_fresh(&mut h, "closing it");
h.state_mut().session.saved_to("/tmp/Renamed.psd".into());
held_is_fresh(&mut h, "a save that renames the document");
// Three documents, the first active: moving the second after the third keeps the active document where it was,
// and the Window menu's second entry opens the other document now (#16252).
for name in ["Second", "Third"] {
h.state_mut().session.execute("file.new", json!({"width": 200, "height": 100, "name": name})).unwrap();
}
h.state_mut().session.set_active(0);
held_is_fresh(&mut h, "opening two more documents");
assert_eq!(h.state_mut().session.move_document(1, 2), Some(2));
held_is_fresh(&mut h, "reordering the documents behind the active one");
}
#[test]
+20
View File
@@ -44,6 +44,13 @@ struct Documents<'a> {
/// The active document, by its `Tracked` revision, which moves with every change to it: its content, layers,
/// selection, history, mode, mask and view state, which most rules read.
active: Option<&'a Tracked<DocState>>,
/// Every open document's revision in tab order, folded into one value: rules that read other documents than the
/// active one (Merge Channels needs grayscale documents of the active one's size) follow their changes (#16252).
all: u64,
/// The scratch read-error generation: a tile that fails to read shows zeros through `&self`, and the real pixels
/// again once it reads, without moving its document's revision. Rules that read pixels (the align commands read
/// content bounds) follow both (#16252).
scratch: u64,
/// A running job greys the commands that would change its document.
jobs: (bool, Option<u64>),
/// Smart Objects › Edit Contents' parent: whether the active document is a smart object's contents.
@@ -174,6 +181,17 @@ impl<'a> MenuFacts<'a> {
}
}
/// The revisions of `documents` in their order, folded into one value that moves when any of them changes or they
/// are reordered. A fixed size, so the key is the same few bytes however many documents are open.
fn all_revisions(documents: &[Tracked<DocState>]) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::hash::DefaultHasher::new();
for document in documents {
document.revision().hash(&mut hasher);
}
hasher.finish()
}
impl<'a> RuleFacts<'a> {
/// What the rules read in `app`'s current state.
pub(crate) fn of(app: &'a PhotocraftApp) -> RuleFacts<'a> {
@@ -186,6 +204,8 @@ impl<'a> RuleFacts<'a> {
active_generation: s.active_generation(),
active_index: s.active_index(),
active: s.active_tracked(),
all: all_revisions(s.documents()),
scratch: photocraft_raster::spill::read_error_generation(),
jobs: (s.has_jobs(), s.active_job().map(|job| job.id.0)),
smart_child: active.is_some_and(|d| s.smart_links.iter().any(|link| link.child == d.doc.id)),
fade: s.edit_state.fade.as_ref().map(|fade| (fade.doc, fade.revision)),
+4 -1
View File
@@ -744,7 +744,10 @@ impl ThumbSource<LayerThumb<LayerId>> for PhotoThumbs<'_> {
},
_ => 0,
};
Revision::of(&(shown, clip, self.doc.size.width, self.doc.size.height))
// A tile that fails to read shows zeros, and its pixels again once it reads, without moving its surface's
// generation: the scratch read-error generation moves with both (#16252).
let scratch = photocraft_raster::spill::read_error_generation();
Revision::of(&(shown, clip, self.doc.size.width, self.doc.size.height, scratch))
}
fn render(&self, key: &LayerThumb<LayerId>, request: &ThumbRequest) -> ThumbRender {
+4 -3
View File
@@ -307,9 +307,10 @@ fn pattern_key(pattern: &photocraft_doc::Pattern) -> PictureKey {
("pattern", pattern.id.clone(), pattern.surface.generation())
}
/// The cached texture of `pattern`'s swatch.
pub(crate) fn pattern_texture(ctx: &egui::Context, pattern: &photocraft_doc::Pattern) -> egui::TextureId {
TextureCache::texture(ctx, pattern_key(pattern), || pattern_image(pattern))
/// A texture of `pattern`'s swatch that its holder owns: it stays while the handle lives, where a cached texture
/// lasts only while something asks for it every frame.
pub(crate) fn pattern_texture_handle(ctx: &egui::Context, pattern: &photocraft_doc::Pattern) -> egui::TextureHandle {
ctx.load_texture(format!("photocraft/pattern-swatch/{}", pattern.id), pattern_image(pattern), egui::TextureOptions::LINEAR)
}
/// The swatch of `pattern`, keyed by its id and named by its display name.