Menu model derived from MenuFacts: the facts the rows show, through their revisions or as small plain values; state_hash, had_input and the hash-keyed MenuModel go; the native menus re-sync on the bar's revision and the keymap. PresetState.rev gives way to the Tracked revision, saves that rename a document move documents_generation, and the default proof setup shares the built-in profile

This commit is contained in:
aiongg committed 2026-11-21 14:07:15 +00:00
1 parent 4c78950e68
commit 292cdc6dc5
26 files changed
+381 -253

No files matched your search

+1 -3
View File
@@ -441,9 +441,7 @@ impl Headless {
if ext.as_deref().is_some_and(|e| file_cmds::holds(&doc, e)) {
// Saving by index must not retarget the next automation command.
self.on_doc(Some(i), |this| {
if let Some(st) = this.session.active_mut() {
st.saved_to(target.to_string_lossy().into_owned());
}
this.session.saved_to(target.to_string_lossy().into_owned());
// History Options › Automatically Create New Snapshot When Saving (#2966).
photocraft_engine::history_options_cmds::snapshot_on_save(&mut this.session);
Ok(())
+9 -1
View File
@@ -46,9 +46,12 @@ pub struct ProofSetup {
impl Default for ProofSetup {
fn default() -> Self {
// One shared copy of the built-in profile: every proof-state read of a document without its own setup makes a
// default, and copying the profile each time costs about half a millisecond.
static COATED_CMYK: std::sync::OnceLock<Arc<Profile>> = std::sync::OnceLock::new();
ProofSetup {
name: "working-cmyk".into(),
profile: Arc::new(Builtin::CoatedCmyk.profile().clone()),
profile: Arc::clone(COATED_CMYK.get_or_init(|| Arc::new(Builtin::CoatedCmyk.profile().clone()))),
intent: Intent::RelativeColorimetric,
bpc: true,
simulate_paper: false,
@@ -386,6 +389,11 @@ impl ColorState {
self.proofs.get(&doc).cloned().unwrap_or_else(|| ProofView { gamut_threshold: craft_cms::gamut::DEFAULT_THRESHOLD, ..Default::default() })
}
/// The revision of every document's proofing state: it moves with each change to one.
pub fn proofs_revision(&self) -> craft_tracked::Revision {
self.proofs.revision()
}
/// Borrow the document's proofing state without cloning its profile or allocating defaults.
/// `None` means the unchanged defaults documented by [`Self::proof`].
pub fn proof_ref(&self, doc: DocId) -> Option<&ProofView> {
+7 -4
View File
@@ -121,11 +121,13 @@ fn has_shape(s: &Session) -> std::result::Result<(), String> {
}
impl crate::DocState {
/// Complete a successful document save. File identity is not a history step; callers must
/// finish the write first and must not call this for a copy or export.
pub fn saved_to(&mut self, path: String) {
/// Complete a successful document save ([`crate::Session::saved_to`]); whether the document's name changed.
/// File identity is not a history step; callers must finish the write first and must not call this for a
/// copy or export.
pub(crate) fn saved_to(&mut self, path: String) -> bool {
let name = file_name(&path);
if self.doc.name != name {
let renamed = self.doc.name != name;
if renamed {
Arc::make_mut(self.doc_mut()).name = name;
}
// The file now holds just this document, whatever the one it was opened from held.
@@ -134,6 +136,7 @@ impl crate::DocState {
}
self.path = Some(path);
self.saved_revision = self.revision;
renamed
}
}
@@ -496,7 +496,7 @@ mod tests {
s.execute(CMD, json!({"automaticallyCreateNewSnapshotWhenSaving": true})).unwrap();
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
s.active_mut().unwrap().saved_to("saved.psd".into());
s.saved_to("saved.psd".into());
let states = entries(&s);
let id = snapshot_on_save(&mut s).unwrap();
let st = s.active().unwrap();
@@ -566,7 +566,7 @@ mod tests {
let red = |s: &Session| s.active().unwrap().doc.layer(photocraft_doc::LayerId(id)).unwrap().surface().unwrap().pixel(1, 1)[1] < 0.5;
s.execute(CMD, json!({"makeLayerVisibilityChangesUndoable": false, "automaticallyCreateNewSnapshotWhenSaving": true})).unwrap();
s.execute("edit.fill", json!({"color": "#ff0000"})).unwrap();
s.active_mut().unwrap().saved_to("saved.psd".into());
s.saved_to("saved.psd".into());
let saved = snapshot_on_save(&mut s).unwrap();
// The eye hides the layer: no state.
s.execute("layer.setProps", json!({"layer": id, "visible": false})).unwrap();
+6 -6
View File
@@ -100,21 +100,21 @@ mod tests {
});
std::fs::write(&file, serde_json::to_string(&data).unwrap()).unwrap();
let prefs_rev = s.prefs.rev();
let presets_rev = s.presets.rev;
let presets_rev = s.presets.revision();
let r = s.execute("edit.presets.migratePresets", json!({"path": file.to_string_lossy()})).unwrap();
assert_eq!(r["added"]["gradients"], 1, "only the new group is added");
assert_eq!(s.presets.gradients.len(), before + 1);
assert!(s.presets.gradients.iter().any(|g| g.name == "My Imported Set"));
assert_eq!(s.prefs.rev(), prefs_rev + 1, "migration marks preferences dirty");
assert_eq!(s.presets.rev, presets_rev + 1);
assert_ne!(s.presets.revision(), presets_rev);
// Idempotent: migrating again adds nothing.
let prefs_rev = s.prefs.rev();
let presets_rev = s.presets.rev;
let presets_rev = s.presets.revision();
let saved = s.prefs_to_json();
let r2 = s.execute("edit.presets.migratePresets", json!({"path": file.to_string_lossy()})).unwrap();
assert_eq!(r2["migrated"], 0);
assert_eq!(s.prefs.rev(), prefs_rev, "duplicate groups do not dirty preferences");
assert_eq!(s.presets.rev, presets_rev);
assert_eq!(s.presets.revision(), presets_rev);
assert_eq!(s.prefs_to_json(), saved);
let _ = std::fs::remove_file(file);
}
@@ -138,11 +138,11 @@ mod tests {
}
std::fs::write(&file, serde_json::to_string(&data).unwrap()).unwrap();
let prefs_rev = s.prefs.rev();
let presets_rev = s.presets.rev;
let presets_rev = s.presets.revision();
let r = s.execute("edit.presets.migratePresets", json!({"path": file.to_string_lossy()})).unwrap();
assert_eq!(r["migrated"], 1, "{key}, wrapped={wrapped}");
assert_eq!(s.prefs.rev(), prefs_rev + 1, "{key}, wrapped={wrapped}: preferences must be saved");
assert_eq!(s.presets.rev, presets_rev + 1);
assert_ne!(s.presets.revision(), presets_rev);
let saved = s.prefs_to_json();
let mut restored = Session::new();
restored.load_prefs_json(&saved).unwrap();
+2 -2
View File
@@ -84,11 +84,11 @@ fn using_a_cmyk_swatch_remembers_its_inks() {
fn rename_delete_move_and_groups() {
let mut s = Session::new();
// A group moves to an index, clamped to the list, and the change is saved with the prefs.
let rev = s.presets.rev;
let rev = s.presets.revision();
let r = s.execute("swatches.moveGroup", json!({"group": "Dark", "to": 0})).unwrap();
assert_eq!(r, json!({"group": "Dark", "position": 0}));
assert_eq!(s.presets.swatches[0].name, "Dark");
assert!(s.presets.rev > rev, "a group move is a preset change");
assert_ne!(s.presets.revision(), rev, "a group move is a preset change");
let r = s.execute("swatches.moveGroup", json!({"group": "Dark", "to": 999})).unwrap();
assert_eq!(r["position"], 4);
assert_eq!(s.presets.swatches[4].name, "Dark");
+2 -6
View File
@@ -96,8 +96,6 @@ pub struct PresetState {
/// The user contour library of the Layer Style dialog (`layer.layerStyle.contours.*`).
#[plain_data(assume = "document contours: plain numbers")]
pub contours: Vec<photocraft_doc::Contour>,
/// Bumped on every preset change (UIs key thumbnail caches on it).
pub rev: u64,
}
impl Default for PresetState {
@@ -117,7 +115,6 @@ impl Default for PresetState {
layer_defaults: BTreeMap::new(),
swatches: craft::color_ui::palette::default_swatches(),
contours: Vec::new(),
rev: 0,
}
}
}
@@ -276,13 +273,12 @@ impl Session {
if let Some(c) = p.contours.filter(Value::is_array) {
self.presets.contours = crate::contour_lib_cmds::from_json(&c);
}
self.presets.rev += 1;
}
/// Record a preset change: bumps the panel revision and marks the preferences document dirty
/// Record a preset change: moves the presets' revision and marks the preferences document dirty
/// so the shell persists it.
pub(crate) fn presets_changed(&mut self) {
self.presets.rev += 1;
self.presets.edit(|_| ());
self.prefs.edit(|_| ());
}
}
-1
View File
@@ -74,7 +74,6 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "pattern.presets.select";
let pat = pattern_key(s, p, CMD)?;
s.presets.pattern = Some(pat.id.clone());
s.presets.rev += 1;
let mut out = json!({"pattern": pat.id, "name": pat.display_name()});
if p.get("applyToLayer").and_then(Value::as_bool).unwrap_or(true)
&& let Some(id) = active_pattern_fill(s)
+11 -1
View File
@@ -27,7 +27,7 @@ impl Session {
&self.docs
}
/// Changes whenever a document is opened or closed.
/// Changes whenever a document is opened, closed or renamed.
pub fn documents_generation(&self) -> u64 {
self.documents_generation
}
@@ -44,6 +44,16 @@ impl Session {
self.active.and_then(|i| self.docs.get_mut(i))
}
/// Completes a successful save of the active document: the file becomes its path and names it, and its revision is
/// the saved one. File identity is not a history step; callers finish the write first and don't call this for a
/// copy or export.
pub fn saved_to(&mut self, path: String) {
let renamed = self.active_mut().is_some_and(|st| st.saved_to(path));
if renamed {
self.documents_generation = self.documents_generation.wrapping_add(1);
}
}
/// The open document with this id, active or not.
pub fn document_mut(&mut self, id: photocraft_doc::DocId) -> Option<&mut DocState> {
self.docs.iter_mut().find(|d| d.doc.id == id)
+3 -3
View File
@@ -15,7 +15,7 @@ fn successful_save_identity_is_not_undone_or_redone() {
s.execute("layer.new.layer", json!({})).unwrap();
let original = s.active().unwrap().doc.clone();
let revision = s.active().unwrap().revision;
s.active_mut().unwrap().saved_to("C:\\作品\\My picture.PSD".into());
s.saved_to("C:\\作品\\My picture.PSD".into());
let saved = s.active().unwrap();
assert_eq!(saved.doc.name, "My picture.PSD");
assert_eq!(saved.doc.id, original.id);
@@ -23,11 +23,11 @@ fn successful_save_identity_is_not_undone_or_redone() {
assert!(!saved.is_dirty());
assert_eq!(original.name, "Untitled-1", "the exported snapshot remains immutable");
let snapshot = saved.doc.clone();
s.active_mut().unwrap().saved_to("C:\\作品\\My picture.PSD".into());
s.saved_to("C:\\作品\\My picture.PSD".into());
assert!(Arc::ptr_eq(&s.active().unwrap().doc, &snapshot), "saving the same name does not invalidate snapshots or jobs");
assert!(s.undo());
assert_eq!(s.active().unwrap().doc.name, "My picture.PSD");
s.active_mut().unwrap().saved_to("renamed.psb".into());
s.saved_to("renamed.psb".into());
assert!(s.redo());
assert_eq!(s.active().unwrap().doc.name, "renamed.psb");
assert_eq!(s.active().unwrap().path.as_deref(), Some("renamed.psb"));
+4 -4
View File
@@ -48,12 +48,12 @@ fn csh_import_makes_an_original_shape_available_without_a_document() {
fn csh_failed_import_preserves_existing_presets_and_revision() {
let mut session = Session::new();
let before = session.presets.to_json(&session);
let revision = session.presets.rev;
let revision = session.presets.revision();
let bytes = triangle_csh();
for end in [0, 11, bytes.len() - 1] {
assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes[..end])})).is_err());
assert_eq!(session.presets.to_json(&session), before);
assert_eq!(session.presets.rev, revision);
assert_eq!(session.presets.revision(), revision);
}
assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&bytes), "group": 12})).is_err());
assert_eq!(session.presets.to_json(&session), before);
@@ -70,10 +70,10 @@ fn csh_invalid_second_shape_does_not_partially_import_a_set() {
let mut session = Session::new();
session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&triangle)})).unwrap();
let before = session.presets.to_json(&session);
let revision = session.presets.rev;
let revision = session.presets.revision();
assert!(session.execute("shape.presets.importCsh", json!({"data": photocraft_paint::tile::b64_encode(&set)})).is_err());
assert_eq!(session.presets.to_json(&session), before);
assert_eq!(session.presets.rev, revision);
assert_eq!(session.presets.revision(), revision);
}
#[test]
+5 -5
View File
@@ -676,12 +676,12 @@ impl PhotocraftApp {
// A background save may finish while another document is active (or after its
// document was closed, when there is nothing left to record).
let _ = self.with_document(doc, |app| {
if let Some(st) = app.session.active_mut()
&& arm
{
st.saved_to(path.to_string());
if arm && app.session.active().is_some() {
app.session.saved_to(path.to_string());
// The job locked the document, but record the revision that was written.
st.saved_revision = revision;
if let Some(st) = app.session.active_mut() {
st.saved_revision = revision;
}
app.remember_stamp(doc, path);
// History Options › Automatically Create New Snapshot When Saving (#2966).
photocraft_engine::history_options_cmds::snapshot_on_save(&mut app.session);
+1 -1
View File
@@ -55,7 +55,7 @@ fn engine_methods(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlReq
"jobs.cancel" => jobs_cancel(app, &req.params),
"ui.menu.list" => {
// Report the same enablement the native menu shows, so a listed item is invokable.
let rows = crate::menus::model(app, ctx).rows.clone();
let rows = crate::menus::model(app, ctx).rows().to_vec();
ok(menu_list(app, &rows))
}
"ui.inspect" => ok(inspect(app, ctx)),
+3 -4
View File
@@ -11,6 +11,7 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
mod bar;
pub(crate) mod facts;
pub mod enable_rules;
mod invoke;
mod items;
@@ -296,13 +297,11 @@ mod window_documents_tests {
if crate::i18n::needs_catalogs() {
let mut app = app(1);
let ctx = app.ctx().clone();
if let Some(d) = app.session.active_mut() {
d.saved_to("/tmp/Layers".into());
}
app.session.saved_to("/tmp/Layers".into());
let de = crate::i18n::Lang::from_code("de").unwrap();
let _lang = crate::i18n::language_scope(de);
let shown = model(&mut app, &ctx);
assert_eq!(row(&shown.rows, "window.document.0").map(|r| r.label.as_str()), Some("Layers"));
assert_eq!(row(shown.rows(), "window.document.0").map(|r| r.label.as_str()), Some("Layers"));
}
}
}
+4 -47
View File
@@ -1,7 +1,4 @@
use std::collections::HashMap;
use std::sync::{PoisonError, RwLock};
use craft::menu::{Labeled, MenuBarUi};
use craft::menu::MenuBarUi;
use super::PhotocraftApp;
use super::items;
@@ -29,50 +26,10 @@ pub fn menu_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let (gate, _) = menu_gate(app);
let ctx = ui.ctx().clone();
let model = items::model(app, &ctx);
publish_english(model);
MenuBarUi::new(&model.bar).english(english_name).mnemonics(&TOP_PREFERRED).help_search(true).keyboard(!(gate.modal || gate.recording_shortcut)).show(ui);
MenuBarUi::new(&model.bar).mnemonics(&TOP_PREFERRED).help_search(true).keyboard(!(gate.modal || gate.recording_shortcut)).show(ui);
}
/// The English names of the menu model the bar last drew, by its state: the bar's English hook is a capture-free
/// function, so it reads them here.
struct EnglishNames {
state: u64,
labels: HashMap<(String, String), String>,
titles: HashMap<String, String>,
}
static ENGLISH: RwLock<Option<EnglishNames>> = RwLock::new(None);
/// Keeps [`ENGLISH`] at `model`'s names; copies them only when the model's state changed.
fn publish_english(model: &items::MenuModel) {
let mut names = ENGLISH.write().unwrap_or_else(PoisonError::into_inner);
if names.as_ref().map(|n| n.state) != Some(model.state()) {
let (labels, titles) = model.english_names();
*names = Some(EnglishNames { state: model.state(), labels, titles });
}
}
/// The English name of a command or menu title of the bar's model, for its mnemonics and Help search.
fn english_name(labeled: Labeled<'_>) -> Option<String> {
let names = ENGLISH.read().unwrap_or_else(PoisonError::into_inner);
let names = names.as_ref()?;
match labeled {
Labeled::Command(command) => names.labels.get(&items::command_key(command)).cloned(),
Labeled::Title(title) => names.titles.get(title).cloned(),
_ => None,
}
}
/// The English name of a command or menu title of `model`, for the bar's and the palette's search.
fn english_of(model: &items::MenuModel) -> impl Fn(Labeled<'_>) -> Option<String> + '_ {
move |labeled| match labeled {
Labeled::Command(command) => model.english_label(command),
Labeled::Title(title) => model.english_title(title),
_ => None,
}
}
/// The commands of the menu model's bar as the command palette lists them, with each path and English name. The bar
/// The commands of the menu model's bar as the command palette lists them, with each path and the English names the model carries. The bar
/// is laid out with the options the model was built with, so the palette and the bars agree.
pub(crate) fn help_entries(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec<craft::ui::menu::HelpEntry> {
use craft::menu::{LayoutOptions, Target};
@@ -81,5 +38,5 @@ pub(crate) fn help_entries(app: &mut PhotocraftApp, ctx: &egui::Context) -> Vec<
let label = |s: &'static str| crate::i18n::tr(lang, s).to_string();
let keys = |chord: &craft::keymap::Chord| craft::ui::runtime::commands::holder(ctx, chord);
let options = LayoutOptions::new(crate::native_menu::APP_NAME).label(&label).keys(&keys);
model.bar.help_entries(Target::current(), &options, Some(&english_of(model)))
model.bar.help_entries(Target::current(), &options)
}
+217
View File
@@ -0,0 +1,217 @@
//! What the menu model shows, as the plain values and revisions it is built from: [`super::items::model`] builds the
//! model again only when these change. A rule the rows read is listed here through the signal of the state it reads:
//! a `Tracked` value's or a framework value's revision, an engine marker, or the plain value itself when it is small.
//! Nothing here grows with the documents, presets, recent files or layers, so an idle frame keys the same few bytes
//! whatever the model's size.
use std::sync::Arc;
use craft::ui::contract::{MemoProps, Revision, Tracked};
use photocraft_doc::DocId;
use crate::PhotocraftApp;
/// The facts of one state of the app ([`MenuFacts::of`]).
#[derive(MemoProps)]
pub(crate) struct MenuFacts<'a> {
/// The UI language: labels and titles are translated when the model is built.
language: &'static str,
/// The keymap's overrides and catalog generations: the rows show its chords.
keymap: (u64, u64),
documents: Documents<'a>,
session: SessionFacts,
prefs: PrefFacts<'a>,
ui: UiFacts<'a>,
}
/// The open documents and the active one.
#[derive(MemoProps)]
struct Documents<'a> {
/// Moves when a document opens, closes or is renamed (the Window menu lists them by name).
generation: u64,
active_generation: u64,
active_index: Option<usize>,
/// The active document and its revision, which moves with every change to it: its content, layers, selection,
/// history, mode and mask state, which most rules read.
#[memo_props(hash = "a plain model id")]
active: Option<(DocId, 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.
smart_child: bool,
/// Edit › Fade: the document and revision of the step it fades.
#[memo_props(hash = "a plain model id")]
fade: Option<(DocId, u64)>,
/// The proof setups (View › Proof Colors, Gamut Warning, the simulations).
proofs: Revision,
/// File › Generate › Image Assets and View › Lock Slices.
image_assets: &'a Tracked<Vec<DocId>>,
slices_locked: bool,
}
/// Session state outside the documents that rules read.
#[derive(MemoProps)]
struct SessionFacts {
clipboard: Revision,
style_clipboard: Revision,
/// The path fill and stroke clipboards: Paste Shape Fill and Stroke.
path_clipboards: (bool, bool),
presets: Revision,
no_patterns: bool,
type_defaults: bool,
measurement_log: bool,
mask_targeted: bool,
/// The Actions library: the list, recording and playing (library edits are undone from Edit › Undo).
actions: (u64, Option<(usize, usize)>, u8),
/// Edit › Undo's label when it undoes an Actions library change.
undo_label: Option<&'static str>,
}
/// The preferences the rows show.
#[derive(MemoProps)]
struct PrefFacts<'a> {
language: &'a str,
hidden: &'a Vec<String>,
colors: &'a std::collections::BTreeMap<String, String>,
show_menu_colors: bool,
quick_export: &'static str,
font_preview: &'static str,
generator: bool,
appearance: &'static str,
favorite_themes: &'a Vec<String>,
}
/// The shell's state the rows show.
#[derive(MemoProps)]
struct UiFacts<'a> {
tool: u64,
/// The open Free Transform: its undo steps' and phase's revision, Content-Aware Scale, its layer count and a
/// running commit.
transform: Option<(u64, bool, usize, bool)>,
/// The typed text being edited: Cut and Copy follow its selection, the Type menu its style.
text_edit: Option<&'a crate::state::TextEdit>,
/// The Pen draft's and the Crop tool's own Undo and Redo, and whether a crop is pending.
pen: (Option<bool>, Option<bool>),
crop: (Option<bool>, Option<bool>, bool),
/// Mask targets the rules fill into a command's target, and a multi-channel colour target.
targets: (bool, bool, bool, bool),
/// Symmetry › Transform.
symmetry: bool,
/// The modal state the rows read: open dialogs, the discard prompt, a distort workspace, the shortcut recorder,
/// a brush resize.
modal: (usize, bool, Option<&'static str>, bool, bool),
selected_guide: bool,
extras: crate::state::Extras,
view: &'a crate::view_cmds::ViewOptions,
/// The options, status, menu and contextual task bars.
bars: (bool, bool, bool, bool),
palette: bool,
theme: (&'a str, bool),
#[memo_props(hash = "craft-behavior's document arrangement: a fieldless enum")]
arrangement: Option<craft::behavior::dock::Arrangement>,
/// The Window menu's ticks: which panels are shown ([`window_ticks`]).
ticks: Arc<Vec<bool>>,
recent_files: &'a Tracked<Vec<String>>,
workspaces: &'a Tracked<crate::workspace_ui::Workspaces>,
/// Save and Paste rules ask which services this platform has.
services: (bool, bool),
}
impl<'a> MenuFacts<'a> {
/// The facts of `app`'s current state.
pub(crate) fn of(app: &'a PhotocraftApp) -> MenuFacts<'a> {
let s = &app.session;
let active = s.active();
let prefs = s.prefs();
let ui = &app.ui;
MenuFacts {
language: crate::i18n::current().code(),
keymap: app.framework.keymap_inputs(),
documents: Documents {
generation: s.documents_generation(),
active_generation: s.active_generation(),
active_index: s.active_index(),
active: active.map(|d| (d.doc.id, d.revision)),
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)),
proofs: s.color.proofs_revision(),
image_assets: &s.file_menu.image_assets,
slices_locked: s.file_menu.slices_locked,
},
session: SessionFacts {
clipboard: s.clipboard.revision(),
style_clipboard: s.style_clipboard.revision(),
path_clipboards: (s.path_fill_clipboard.is_some(), s.path_stroke_clipboard.is_some()),
presets: s.presets.revision(),
no_patterns: s.patterns.items.is_empty(),
type_defaults: s.type_defaults.is_some(),
measurement_log: s.analysis.log.is_empty(),
mask_targeted: s.tools.mask_targeted,
actions: (s.actions.list.revision(), s.actions.recording, s.actions.playing),
undo_label: crate::actions::library::edit_undo_label(app),
},
prefs: PrefFacts {
language: &prefs.interface.language,
hidden: &prefs.menus.hidden,
colors: &prefs.menus.colors,
show_menu_colors: prefs.interface.show_menu_colors,
quick_export: prefs.export.quick_export_format.name(),
font_preview: prefs.type_.font_preview.name(),
generator: prefs.plug_ins.generator_enabled,
appearance: prefs.interface.appearance_mode.name(),
favorite_themes: &prefs.interface.favorite_themes,
},
ui: UiFacts {
tool: ui.tool as u64,
transform: ui.transform.as_ref().map(|t| {
(t.session.revision(), t.content_aware.is_some(), t.layers.len(), crate::transform_tool::committing(app).is_some())
}),
text_edit: ui.text_edit.as_ref(),
pen: (crate::vector_ui::pen_history_enabled(app, "edit.undo"), crate::vector_ui::pen_history_enabled(app, "edit.redo")),
crop: (crate::crop_ui::is_enabled(app, "edit.undo"), crate::crop_ui::is_enabled(app, "edit.redo"), crate::crop_ui::pending(app)),
targets: (app.filter_mask_targeted(), app.vector_mask_targeted(), app.layer_mask_targeted(), crate::canvas::multiple_color_target(app)),
symmetry: crate::symmetry_ui::can_transform(app),
modal: (
app.dialog_count(),
app.discard.is_some(),
crate::distort_ui::modal_workspace(app),
crate::prefs_ui::recording(app),
app.brush_resize.active(),
),
selected_guide: crate::guide_select::selected(app).is_some(),
extras: ui.extras,
view: &ui.view,
bars: (ui.panels.options_bar, ui.panels.status_bar, ui.panels.menu_bar, ui.panels.context_task_bar),
palette: ui.palette.open,
theme: (ui.theme.id().as_str(), ui.theme.is_dark()),
arrangement: ui.document_windows.arrangement,
ticks: window_ticks(app),
recent_files: &ui.recent_files,
workspaces: &app.workspaces,
services: (app.services.export.is_some(), app.services.clipboard_get_image.is_some()),
},
}
}
}
/// Panels whose ticks the rows read besides the registry's: the dock, the Tools and Options bars, and panels the
/// analysis and workspace checks name.
const OTHER_PANELS: [&str; 6] = ["dock", "tools", "options", "modifierKeys", crate::analysis::MEASUREMENT_LOG, crate::analysis::NOTES];
/// Which panels the Window menu ticks, derived from the dock: its revision moves with every write (a column resize
/// included), so the ticks are worked out again then, and the menu model only when one of them changed.
fn window_ticks(app: &PhotocraftApp) -> Arc<Vec<bool>> {
let key = (app.ui.docking.revision(), app.ui.flyout.as_deref());
craft::ui::runtime::derived::derived(app.ctx(), egui::Id::new("photocraft-window-ticks"), &key, || {
let registry = crate::panels::registry::PANELS.iter().map(|panel| crate::panel_docking::is_checked(app, panel.id));
let others = OTHER_PANELS.iter().flat_map(|panel| [crate::panel_docking::is_checked(app, panel), crate::panel_docking::is_shown(app, panel)]);
registry.chain(others).collect()
})
}
/// The key the model is derived on, for tests that check a change reaches the menus.
#[cfg(test)]
pub(crate) fn key(app: &PhotocraftApp) -> u128 {
craft::ui::contract::MemoKey::of(&MenuFacts::of(app))
}
+77 -81
View File
@@ -1,16 +1,18 @@
use std::collections::HashMap;
use craft::i18n::Words;
use craft::keymap::{Chord, CommandRef, Mods};
use craft::menu::{
Alternate, Customization, ItemKind, ItemRole, LanguageChoice, LanguageLabels, LanguageMenu, LayoutOptions, MenuBar, MenuRole, Node, Platforms, Row, Target,
ThemeLabels, from_items, layout,
};
use std::sync::Arc;
use craft::ui::contract::Tracked;
use craft::ui::runtime::derived::derived;
use serde_json::json;
use super::invoke::{panel_alias, proof_preset, workspace_id};
use super::state::{checked, is_enabled, reveal_label, translated_menu_label};
use super::facts::MenuFacts;
use super::{DOCUMENT_ITEM, PhotocraftApp, TOP_MENUS, UI_COMMANDS};
/// Is `id` implemented by the engine or the shell (a live menu item)? Shared by the menus and
@@ -46,83 +48,73 @@ const PLACE_AFTER: &[(&str, &str)] = &[
("filter.other.colorToAlpha", "filter.other.offset"),
];
/// The menu rows of one state of the app, built once and kept until that state changes: building
/// them asks every command whether it can run, which on a document with thousands of layers costs
/// far more than a frame.
/// The menu rows of one state of the app, built once and kept until a fact they show changes
/// ([`MenuFacts`]): building them asks every command whether it can run, which on a document with
/// thousands of layers costs far more than a frame.
pub struct MenuModel {
/// [`crate::native_menu::state_hash`] of the state the model was built from.
state: u64,
/// The English label each row was built from, by [`command_key`] (`rows` hold the labels as shown).
english: HashMap<(String, String), String>,
/// The English title of each menu and submenu, by its title as shown.
english_titles: HashMap<String, String>,
/// The rows with labels as shown, after the user's Edit › Menus customization.
pub rows: Vec<Row>,
built: Arc<Built>,
/// The menus laid out for this platform, titles as shown, each translated title and label with its English name.
/// A rebuild that lays out the same menus keeps the held value, so the bar's key stays.
pub bar: Tracked<MenuBar>,
}
impl MenuModel {
/// [`crate::native_menu::state_hash`] of the state this model was built from.
pub(super) fn state(&self) -> u64 {
self.state
}
/// Copies of the English labels and titles, for a lookup that cannot borrow the model.
pub(super) fn english_names(&self) -> (HashMap<(String, String), String>, HashMap<String, String>) {
(self.english.clone(), self.english_titles.clone())
}
/// The English label of the row that runs `command`.
pub(super) fn english_label(&self, command: &CommandRef) -> Option<String> {
self.english.get(&command_key(command)).cloned()
}
/// The English title of a menu or submenu shown as `title`.
pub(super) fn english_title(&self, title: &str) -> Option<String> {
self.english_titles.get(title).cloned()
/// The rows with labels as shown, after the user's Edit › Menus customization; each translated label carries its
/// English name.
pub fn rows(&self) -> &[Row] {
&self.built.rows
}
}
/// The key of a command in the English-name map: its id and its parameters, since one id (`app.theme`) runs many rows.
pub(super) fn command_key(command: &CommandRef) -> (String, String) {
(command.id.clone(), command.params.to_string())
/// One build of the model: the rows and the bar laid out from them.
struct Built {
rows: Vec<Row>,
bar: MenuBar,
}
/// Records the English label of every item under `node`, for the commands the framework lays out itself.
fn collect_english(node: &Node, english: &mut HashMap<(String, String), String>) {
match node {
Node::Item(item) => {
english.insert(command_key(&item.command), item.label.clone());
}
Node::Submenu { children, .. } => children.iter().for_each(|child| collect_english(child, english)),
_ => {}
}
}
/// The model for the app's current state. It is rebuilt when the hash of its inputs changes; a
/// frame with a click or key press folds the frame number in, which covers state the hash does not
/// list. A second pass of that frame sees no input, so it hashes differently and rebuilds once,
/// after the first pass's commands ran.
pub fn model<'a>(app: &'a mut PhotocraftApp, ctx: &egui::Context) -> &'a MenuModel {
let state = crate::native_menu::state_hash(app, had_input(ctx).then_some(app.frame));
match app.menu_model.take() {
Some(held) if held.state == state => app.menu_model.insert(held),
held => {
let mut built = build(app, state);
if let Some(held) = held.filter(|held| held.bar == built.bar) {
built.bar = held.bar;
/// `shown` with the English name of each item and submenu whose label `english`, the same node built in English,
/// words differently.
fn with_english(mut shown: Node, english: &Node) -> Node {
fn name(node: &mut Node, english: &Node) {
match (node, english) {
(Node::Item(item), Node::Item(en)) => {
if item.label != en.label {
item.english = Some(en.label.clone());
}
}
app.menu_model.insert(built)
(Node::Submenu { label, english, children, .. }, Node::Submenu { label: en_label, children: en_children, .. }) => {
if label != en_label {
*english = Some(en_label.clone());
}
children.iter_mut().zip(en_children).for_each(|(child, en)| name(child, en));
}
_ => {}
}
}
name(&mut shown, english);
shown
}
/// Whether this frame had a key press or a button release, which may change state [`crate::native_menu::state_hash`]
/// does not list.
pub(crate) fn had_input(ctx: &egui::Context) -> bool {
craft::ui::runtime::keys::keyed(ctx) || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. })))
/// The id the model is derived under.
pub(crate) fn model_id() -> egui::Id {
egui::Id::new("photocraft-menu-model")
}
/// The model for the app's current state: derived from its [`MenuFacts`], so it is built again only when one of them
/// changed. The held bar is replaced only when the new build lays out different menus.
pub fn model<'a>(app: &'a mut PhotocraftApp, ctx: &egui::Context) -> &'a MenuModel {
let built = {
let app = &*app;
derived(ctx, model_id(), &MenuFacts::of(app), || build(app))
};
let held = app.menu_model.get_or_insert_with(|| MenuModel { bar: Tracked::new(built.bar.clone()), built: Arc::clone(&built) });
if !Arc::ptr_eq(&held.built, &built) {
if *held.bar != built.bar {
*held.bar = built.bar.clone();
}
held.built = built;
}
held
}
/// The row that runs `id`.
@@ -368,23 +360,28 @@ pub(super) fn menu_tint(name: &str) -> Option<egui::Color32> {
})
}
/// Translates the titles of menus and submenus, recording each one's English title.
fn translate_titles(bar: &mut MenuBar, lang: crate::i18n::Lang, english: &mut HashMap<String, String>) {
fn level(nodes: &mut [Node], lang: crate::i18n::Lang, english: &mut HashMap<String, String>) {
/// Translates the titles of menus and submenus, each translated one keeping its English title.
fn translate_titles(bar: &mut MenuBar, lang: crate::i18n::Lang) {
/// `title` as shown in `lang`, and its English name when the two differ.
fn translate(title: &mut String, english: &mut Option<String>, lang: crate::i18n::Lang) {
let shown = crate::i18n::tr(lang, title).to_string();
if shown != *title {
*english = Some(std::mem::replace(title, shown));
}
}
fn level(nodes: &mut [Node], lang: crate::i18n::Lang) {
for node in nodes {
if let Node::Submenu { label, children, .. } = node {
let shown = crate::i18n::tr(lang, label).to_string();
english.insert(shown.clone(), std::mem::replace(label, shown));
level(children, lang, english);
if let Node::Submenu { label, english, children, .. } = node {
translate(label, english, lang);
level(children, lang);
}
}
}
for menu in &mut bar.menus {
if menu.role != MenuRole::App {
let shown = crate::i18n::tr(lang, &menu.title).to_string();
english.insert(shown.clone(), std::mem::replace(&mut menu.title, shown));
translate(&mut menu.title, &mut menu.english, lang);
}
level(&mut menu.children, lang, english);
level(&mut menu.children, lang);
}
}
@@ -396,16 +393,17 @@ fn put_in_window(bar: &mut MenuBar, node: Node) {
menu.children.insert(at, node);
}
fn build(app: &PhotocraftApp, state: u64) -> MenuModel {
fn build(app: &PhotocraftApp) -> Built {
let lang = crate::i18n::current();
let mut rows = menu_rows(app);
let mut english = HashMap::new();
for row in &mut rows {
if row.label == "---" {
continue;
}
english.insert(command_key(&row.command), row.label.clone());
row.label = translated_menu_label(lang, &row.command.id, &row.label);
let shown = translated_menu_label(lang, &row.command.id, &row.label);
if shown != row.label {
row.english = Some(std::mem::replace(&mut row.label, shown));
}
if let Some(tip) = row.tooltip.take() {
row.tooltip = Some(crate::i18n::tr(lang, &tip).to_string());
}
@@ -422,8 +420,7 @@ fn build(app: &PhotocraftApp, state: u64) -> MenuModel {
let i18n = crate::i18n::framework_i18n();
let words = Words::from_i18n(i18n.clone(), i18n.from_code(lang.code()).unwrap_or_else(|| i18n.system_lang()));
let themes = crate::prefs_ui::theme_menu(app);
collect_english(&themes.submenu(&Words::english().set::<ThemeLabels>()), &mut english);
put_in_window(&mut bar, themes.submenu(&words.set::<ThemeLabels>()));
put_in_window(&mut bar, with_english(themes.submenu(&words.set::<ThemeLabels>()), &themes.submenu(&Words::english().set::<ThemeLabels>())));
// Production shows Language only in the macOS app menu.
let pref = &app.session.prefs().interface.language;
let choice = if pref == "auto" { LanguageChoice::Automatic } else { LanguageChoice::Code(pref.clone()) };
@@ -433,7 +430,6 @@ fn build(app: &PhotocraftApp, state: u64) -> MenuModel {
let keys = |chord: &Chord| craft::ui::runtime::commands::holder(app.ctx(), chord);
let options = LayoutOptions::new(crate::native_menu::APP_NAME).label(&label).keys(&keys);
let mut bar = layout(&bar, Target::current(), &options).bar;
let mut english_titles = HashMap::new();
translate_titles(&mut bar, lang, &mut english_titles);
MenuModel { state, english, english_titles, rows, bar: Tracked::new(bar) }
translate_titles(&mut bar, lang);
Built { rows, bar }
}
+6 -62
View File
@@ -4,14 +4,12 @@
//!
//! craft-menu owns the layout, the clash rules, the key equivalents and the driver. This module
//! supplies what is PhotoCraft's: the app name, the translated labels, the shortcuts bound outside
//! the menus, the gate and modal rules ([`crate::menus::menu_gate`]) and the hash of the state the
//! menus show ([`state_hash`]).
//! the menus and the gate and modal rules ([`crate::menus::menu_gate`]). The menus are laid out again
//! only when the model's bar or the keymap changed.
//!
//! A menu click is a fired command ([`poll`] fires it with `FireSource::Menu`); the runtime's
//! drain runs it like any other fired command, so the menu has no command path of its own.
use std::hash::{DefaultHasher, Hash, Hasher};
use craft::menu::{Layout, LayoutOptions, NativeMenu, mac_layout};
use craft::ui::runtime::commands::{FireSource, fire, holder};
use craft::ui::runtime::windows::WindowHost;
@@ -59,74 +57,20 @@ pub fn poll(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
/// Once per frame after the pass: sets what may run from the menus and brings the menus up to date
/// when anything they show may have changed. Building the rows walks every command's enabled
/// state, so the layout runs only when [`state_hash`] changes or a menu event arrived.
/// when what they show changed: the model's bar (its revision) or the keymap whose keys the layout
/// gives way to.
pub fn sync(app: &mut PhotocraftApp, ctx: &egui::Context) {
// Taken out for the pass: the layout borrows the whole app.
let Some(mut native) = app.services.native_menu.take() else { return };
let (gate, rules) = crate::menus::menu_gate(app);
native.set_gate(gate.text_editing(WindowHost::of(ctx).typing()));
native.set_modal_rules(rules);
let state = state_hash(app, crate::menus::items::had_input(ctx).then_some(app.frame));
for c in native.sync_with(&state, || laid_out(app, ctx)) {
let shown = (items::model(app, ctx).bar.revision(), app.framework.keymap_inputs());
for c in native.sync_with(&shown, || laid_out(app, ctx)) {
log::info!("menu: {} is {} on macOS and {} in PhotoCraft; {}", c.shortcut.portable(), c.system, c.command.id, c.resolution);
}
app.services.native_menu = Some(native);
}
/// What the menus' rows depend on, cheaply: commands run, the documents (their names, in tab
/// order, for the Window menu) and the active one's revision, selection, recent files, panels and
/// view state, the keymap, and the preferences the rows show. `input` forces a change on frames with a click or key press, which
/// covers state the hash doesn't list.
pub(crate) fn state_hash(app: &PhotocraftApp, input: Option<u64>) -> u64 {
let mut h = DefaultHasher::new();
input.hash(&mut h);
let s = &app.session;
s.journal.len().hash(&mut h);
s.active_index().hash(&mut h);
for d in s.documents() {
(d.doc.id.0, &d.doc.name).hash(&mut h);
}
s.clipboard.is_some().hash(&mut h);
// A running job greys the commands that would change its document.
s.has_jobs().hash(&mut h);
(crate::actions::library::edit_undo_label(app), crate::vector_ui::pen_can_undo(app)).hash(&mut h);
if let Some(d) = s.active() {
(d.doc.id.0, d.revision, d.active_layer.map(|l| l.0), d.selected_layers.len(), d.isolated_layers.len()).hash(&mut h);
}
let ui = &app.ui;
(&ui.recent_files, &app.workspaces.set.current, app.ui.palette.open, ui.transform.is_some(), ui.text_edit.is_some(), app.dialog_count()).hash(&mut h);
// Cut and Copy are enabled while the typed text has a selection.
ui.text_edit.as_ref().map(|e| e.anchor != e.caret).hash(&mut h);
// The Window bars' ticks; the Contextual Task Bar's Hide bar and `ui.set` change them without a menu click (#15489).
// Not the task bar's place, which moves every frame of a drag.
let p = &ui.panels;
(p.options_bar, p.status_bar, p.menu_bar, p.context_task_bar).hash(&mut h);
(app.discard.is_some(), crate::distort_ui::modal_workspace(app)).hash(&mut h);
crate::prefs_ui::recording(app).hash(&mut h);
// The rows show the keymap's chords; the keymap follows these from the frame they change.
app.framework.keymap_inputs().hash(&mut h);
// Edit / Clear Selected Guides are enabled only while a guide is selected.
crate::guide_select::selected(app).hash(&mut h);
// The dock workspace's revision moves only on `replace`, so the arrangement is read as the panels in the layout and
// the keys of the hidden and floating ones; the checked flags cover panels opened or closed and the flyout of a
// panel in a column of icons.
let docking = &app.ui.docking;
docking.layout().panels().hash(&mut h);
docking.hidden().iter().map(|(panel, _)| panel).collect::<Vec<_>>().hash(&mut h);
docking.floated().iter().map(|(panel, _)| panel).collect::<Vec<_>>().hash(&mut h);
for panel in crate::panels::registry::PANELS {
crate::panel_docking::is_checked(app, panel.id).hash(&mut h);
}
serde_json::to_string(&(&ui.extras, &ui.view, ui.theme.id().as_str(), ui.theme.is_dark(), ui.tool)).unwrap_or_default().hash(&mut h);
// The preferences the rows show: the language, Edit › Menus (hidden rows, colours), the Quick Export label and
// the Font Preview Size tick.
let prefs = s.prefs();
prefs.interface.language.hash(&mut h);
(&prefs.menus.hidden, &prefs.menus.colors, prefs.interface.show_menu_colors).hash(&mut h);
(prefs.export.quick_export_format, prefs.type_.font_preview).hash(&mut h);
h.finish()
}
#[cfg(test)]
mod tests;
@@ -211,13 +211,13 @@ fn opening_or_closing_a_workspace_without_input_rebuilds_the_menus() {
let ctx = app.ctx().clone();
app.run("layer.new.layer", json!({})).unwrap();
app.run("edit.fill", json!({"color": "#808080"})).unwrap();
let closed = state_hash(&app, None);
let closed = crate::menus::facts::key(&app);
crate::gallery_ui::open(&mut app).unwrap();
let open = state_hash(&app, None);
let open = crate::menus::facts::key(&app);
assert_ne!(open, closed, "the menus grey out when an agent opens Filter Gallery");
let id = app.framework.dialogs.stack().top().unwrap();
app.framework.dialogs.cancel_by_id(&ctx, id);
assert_eq!(state_hash(&app, None), closed, "and come back when it is cancelled");
assert_eq!(crate::menus::facts::key(&app), closed, "and come back when it is cancelled");
}
/// The Contextual Task Bar's tick follows the bar when its Hide bar or `ui.set` turns it off without a menu click
@@ -243,16 +243,16 @@ fn the_task_bar_tick_follows_the_bar_hidden_without_a_menu_click() {
#[test]
fn the_menu_state_follows_the_preferences_the_rows_show() {
let mut app = app(false);
let shown = state_hash(&app, None);
let shown = crate::menus::facts::key(&app);
app.session.edit_prefs(|p| {
p.selected_tool = json!("Brush");
p.tool_colors = Default::default();
});
assert_eq!(state_hash(&app, None), shown, "the saved tool and colours are not in the menus");
assert_eq!(crate::menus::facts::key(&app), shown, "the saved tool and colours are not in the menus");
app.session.edit_prefs(|p| p.menus.hidden.push("filter.blur.gaussian".into()));
let hidden = state_hash(&app, None);
let hidden = crate::menus::facts::key(&app);
assert_ne!(hidden, shown, "Edit › Menus hides a row");
app.session.edit_prefs(|p| p.export.quick_export_format = photocraft_engine::prefs::QuickExportFormat::Jpg);
assert_ne!(state_hash(&app, None), hidden, "the Quick Export label names the format");
assert_ne!(crate::menus::facts::key(&app), hidden, "the Quick Export label names the format");
}
+4 -3
View File
@@ -26,7 +26,7 @@ pub use dispatch::{checked, handles, invoke, is_enabled, leave_full_screen_witho
pub use options::{persist, pixel_aspect_ratio, restore};
/// View › Show flags (Photoshop defaults).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft::ui::contract::MemoProps)]
#[serde(default)]
pub struct Show {
pub layer_edges: bool,
@@ -65,7 +65,7 @@ impl Default for Show {
}
/// View › Snap To targets (snapping itself is the `view.snap` master switch).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft::ui::contract::MemoProps)]
#[serde(default)]
pub struct SnapTo {
pub guides: bool,
@@ -82,11 +82,12 @@ impl Default for SnapTo {
}
/// View-, window- and type-preference state of the shell.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft::ui::contract::MemoProps)]
#[serde(default)]
pub struct ViewOptions {
/// View › Screen Mode (F cycles). Saved as "standard" | "fullScreenWithMenuBar" | "fullScreen".
#[serde(with = "screen_mode_names")]
#[memo_props(hash = "craft-shell's screen mode: a fieldless enum")]
pub screen_mode: ScreenMode,
/// View › Extras (⌘H): master switch for guides, grid, edges and other overlays.
pub extras: bool,
+2 -2
View File
@@ -414,11 +414,11 @@ mod tests {
let names: Vec<String> = app.session.presets.swatches.iter().map(|g| g.name.clone()).collect();
assert!(names.len() >= 2, "the default library has folders: {names:?}");
let last = names.last().unwrap().clone();
let rev = app.session.presets.rev;
let rev = app.session.presets.revision();
apply_edit(&mut app, SwatchEdit::move_group(last.clone(), 0));
let order: Vec<String> = app.session.presets.swatches.iter().map(|g| g.name.clone()).collect();
assert_eq!(order[0], last, "the dragged folder moved to the front: {order:?}");
assert_eq!(order[1], names[0]);
assert_ne!(app.session.presets.rev, rev, "the library saves its new order");
assert_ne!(app.session.presets.revision(), rev, "the library saves its new order");
}
}
+1 -1
View File
@@ -20,7 +20,7 @@ pub struct TypeInsertionStyle {
}
/// In-progress inline type editing (Type tool). Offsets are character indices.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, craft::ui::contract::MemoProps)]
pub struct TextEdit {
/// The edited layer.
pub layer: u64,
+1 -1
View File
@@ -231,7 +231,7 @@ impl PartialEq for CamTransform {
}
/// View-menu overlays.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft::ui::contract::MemoProps)]
#[serde(default)]
pub struct Extras {
pub rulers: bool,
+2 -2
View File
@@ -48,8 +48,8 @@ mod count_group_name_tests;
mod count_size_alert_tests;
/// The registry ids of the two panels the menu items toggle.
const MEASUREMENT_LOG: &str = "measurementLog";
const NOTES: &str = "notes";
pub(crate) const MEASUREMENT_LOG: &str = "measurementLog";
pub(crate) const NOTES: &str = "notes";
/// The Count tool options bar's number (#11764): with one group (or none), its markers; with two
/// or more, the markers of the visible groups, then the current group's in brackets (0 while it
@@ -1785,7 +1785,7 @@ mod multi_layer_formatting {
app.run("type.orientation.horizontal", json!({"layer": ids[1].0})).unwrap();
let checks = |app: &mut PhotocraftApp| -> Vec<String> {
let ctx = app.ctx().clone();
let rows = &crate::menus::model(app, &ctx).rows;
let rows = crate::menus::model(app, &ctx).rows();
for id in ["type.antiAlias.none", "type.antiAlias.crisp", "type.orientation.horizontal", "type.orientation.vertical"] {
let it = crate::menus::row(rows, id).unwrap();
assert!(it.kind.checked().is_some(), "{id} is a check item");
@@ -24,13 +24,13 @@ fn vertical(app: &PhotocraftApp) -> Vec<f64> {
#[test]
fn the_menu_cache_follows_the_selected_guide() {
let mut app = app();
let none = crate::native_menu::state_hash(&app, None);
let none = crate::menus::facts::key(&app);
crate::guide_select::select(&mut app, true, 0);
let one = crate::native_menu::state_hash(&app, None);
let one = crate::menus::facts::key(&app);
assert_ne!(none, one, "selecting a guide changes the menu state");
assert!(item(&app, "view.clearSelectedGuides").enabled);
crate::guide_select::clear(&mut app);
assert_eq!(crate::native_menu::state_hash(&app, None), none);
assert_eq!(crate::menus::facts::key(&app), none);
assert!(!item(&app, "view.clearSelectedGuides").enabled);
}