Merge remote-tracking branch 'origin/main' into fix/main-ci-freebsd-headless-appearance

This commit is contained in:
FredApps committed 2026-12-02 16:03:38 +01:00
commit b4e0d97b7b
16 files changed
+574 -29

No files matched your search

+13 -2
View File
@@ -109,11 +109,18 @@ fn set_preset(s: &mut Session, p: &Value) -> Result<Value> {
[values.first().and_then(Value::as_f64).ok_or_else(fail)?, values.get(1).and_then(Value::as_f64).ok_or_else(fail)?]
}
};
let rotation_given = p.get("rotation").is_some();
let rotation = match p.get("rotation") {
None => 0.0,
Some(v) => v.as_f64().ok_or_else(fail)?,
};
let preset = PresetSymmetry::new(mode, center, rotation).ok_or_else(fail)?;
// Only an unturned preset starts on the canvas diagonal: that is the start the issue measured.
// A caller that names a turn — Transform Symmetry sends its preview back through here — keeps
// the turn it was given, so the canvas angle is never added a second time.
let preset = match rotation_given {
true => PresetSymmetry::new(mode, center, rotation).ok_or_else(fail)?,
false => PresetSymmetry::for_canvas(mode, center, 0.0, [st.doc.size.width, st.doc.size.height]).ok_or_else(fail)?,
};
let symmetry = PaintingSymmetry::Preset(preset);
let result = symmetry.inspect();
s.active_mut().ok_or(EngineError::NoDocument)?.symmetry = Some(symmetry);
@@ -301,6 +308,7 @@ pub fn specs() -> Vec<CommandSpec> {
mod tests {
use super::*;
use photocraft_doc::vector::Subpath;
use photocraft_paint::symmetry::diagonal_start_angle;
#[test]
fn curved_axis_reflects_near_local_segment() {
@@ -338,7 +346,10 @@ mod tests {
s.execute("image.imageRotation.flipCanvasHorizontal", json!({})).unwrap();
let p = preset(&s);
assert_eq!(p.center, [90.0, 40.0], "edge coordinates mirror about the canvas width, not the last pixel");
assert!((p.rotation - 90.0).abs() < 1e-9, "the 45° axis mirrors to 135°: {}", p.rotation);
// The 120×200 canvas' own diagonal (59.04°) mirrors to 120.96° on a horizontal flip; the
// stored turn is that angle over the 45° line `directions` still starts from.
let mirrored = (diagonal_start_angle([120, 200]).unwrap() - 45.0).rem_euclid(360.0) + (180.0 - 2.0 * diagonal_start_angle([120, 200]).unwrap());
assert!((p.rotation - mirrored).abs() < 1e-9, "the canvas-diagonal axis mirrors to its flipped angle: {} vs {mirrored}", p.rotation);
// A turned dual preset under a non-uniform Image Size: its axes (135° and 45°) map to
// 153.4° and 26.6°, no longer perpendicular; the preset splits the difference.
s.execute("paint.setSymmetry", json!({"mode": "dual", "center": [30, 40], "rotation": 45})).unwrap();
@@ -1,4 +1,5 @@
use super::*;
use photocraft_paint::symmetry::diagonal_start_angle;
fn session(depth: u8, mode: &str) -> Session {
let mut s = crate::session();
@@ -16,7 +17,10 @@ fn presets_validate_atomically_and_leave_document_paths_and_history_untouched()
s.execute("paint.setSymmetry", json!({"mode":mode.id()})).unwrap();
let p = s.active().unwrap().symmetry.as_ref().unwrap().preset().unwrap();
assert_eq!(p.center, [40.5, 30.5]);
assert_eq!(p.rotation, 0.0);
// Diagonal starts on the 81×61 canvas' own diagonal, so its stored turn is the difference
// to the 45° line `directions` starts from; the other modes start at their own angle.
let start = if mode == SymmetryMode::Diagonal { (diagonal_start_angle([81, 61]).unwrap() - 45.0).rem_euclid(360.0) } else { 0.0 };
assert!((p.rotation - start).abs() < 1.0e-9, "{mode:?} starts where its mode starts: {}", p.rotation);
assert_eq!(crate::inspect::document(s.active().unwrap())["symmetry"]["mode"], mode.id());
assert_eq!(s.active().unwrap().doc, before);
assert_eq!((s.active().unwrap().history.past_len(), s.active().unwrap().revision), (history, revision));
@@ -56,3 +60,17 @@ fn presets_validate_atomically_and_leave_document_paths_and_history_untouched()
assert!(!empty.is_enabled("paint.setSymmetry"));
assert!(empty.execute("paint.setSymmetry", json!({"mode":"vertical"})).is_err());
}
#[test]
fn a_turned_diagonal_keeps_the_turn_it_was_given() {
// Transform Symmetry reads the stored turn back out and sends it in again; re-folding the
// canvas angle on that round trip would drift the axis every time the panel commits.
let mut s = session(8, "rgb");
let turn = |s: &Session| s.active().unwrap().symmetry.as_ref().unwrap().preset().unwrap().rotation;
s.execute("paint.setSymmetry", json!({"mode":"diagonal"})).unwrap();
let started = turn(&s);
s.execute("paint.setSymmetry", json!({"mode":"diagonal","rotation":started})).unwrap();
assert!((turn(&s) - started).abs() < 1.0e-9, "sending the stored turn back keeps the axis put: {started} -> {}", turn(&s));
s.execute("paint.setSymmetry", json!({"mode":"diagonal","rotation":30.0})).unwrap();
assert!((turn(&s) - 30.0).abs() < 1.0e-9, "a named turn means what it meant before: {}", turn(&s));
}
+1 -1
View File
@@ -574,7 +574,7 @@ mod shortcuts;
mod store;
mod validate;
pub use cmds::specs;
pub use cmds::{RESET_WARNING_DIALOGS, WARNING_DIALOG_KEYS, WARNING_DIALOG_RESTORED, specs};
#[cfg(test)]
pub(crate) use files::write_files_atomically;
pub use saved::{LEGACY_PREFS_FILE, SavedPrefs, SavedPrefsExt, parse_legacy_prefs, parse_legacy_slots, parse_prefs_json, reset_value};
+45
View File
@@ -3,6 +3,22 @@ use super::validate::{SECTIONS, get_path, keyed};
use super::{CommandSpec, EngineError, Map, Result, Session, ToolbarCustomization, Value, json};
use crate::color_cmds::ColorExt;
pub const RESET_WARNING_DIALOGS: &str = "prefs.resetWarningDialogs";
/// Preference entries used by the app's "Don't show again" warnings.
pub const WARNING_DIALOG_KEYS: &[&str] = &[
"layer.delete.confirmation",
"path.deleteAnchor.liveShape",
"edit.assignProfile.layers",
"notes.delete.confirmation",
"contentAwareMove.noPixelsSelected",
"contentAwareFill.customSampling",
"quickMask.noPixelsSelected",
"objectSelection.notFound",
"layer.layerMask.replace",
];
/// A restored warning starts with its checkbox checked the first time the dialog is shown.
pub const WARNING_DIALOG_RESTORED: &str = "checkByDefault";
// ------------------------------------------------------------------ commands
fn always(_: &Session) -> std::result::Result<(), String> {
@@ -106,6 +122,25 @@ fn prefs_reset(s: &mut Session, p: &Value) -> Result<Value> {
}
}
fn reset_warning_dialogs(s: &mut Session, p: &Value) -> Result<Value> {
if !p.is_null() && !p.as_object().is_some_and(Map::is_empty) {
return Err(bad(RESET_WARNING_DIALOGS, "no parameters are accepted"));
}
let silenced: Vec<_> = WARNING_DIALOG_KEYS
.iter()
.copied()
.filter(|key| s.prefs().dialogs.get(*key).and_then(|v| v.get("skip")).and_then(Value::as_bool) == Some(true))
.collect();
if !silenced.is_empty() {
s.edit_prefs(|prefs| {
for key in &silenced {
prefs.dialogs.insert((*key).into(), json!({ (WARNING_DIALOG_RESTORED): true }));
}
});
}
Ok(json!({"reset": silenced.len()}))
}
/// `edit.preferences.<section>`: the section's values (the GUI opens the dialog on it instead).
fn preferences_section(s: &mut Session, p: &Value) -> Result<Value> {
let section = p.get("__section").and_then(Value::as_str).unwrap_or("general").to_string();
@@ -196,6 +231,16 @@ pub fn specs() -> Vec<CommandSpec> {
false
),
spec!("prefs.reset", "Reset Preferences", [], None, r##"{"path":"section|section.key"?=everything}"##, prefs_reset, false),
CommandSpec {
id: RESET_WARNING_DIALOGS,
label: "Reset All Warning Dialogs",
menu: &[],
shortcut: None,
params: "{} → {reset:count}",
enabled: always,
run: reset_warning_dialogs,
journal: false,
},
// Photoshop: ⌘K opens Preferences › General (⌘, is Layer › Hide Layers).
section!("edit.preferences.general", "General…", Some("Cmd+K")),
section!("edit.preferences.interface", "Interface…"),
@@ -637,6 +637,7 @@ layer.copyToDocument
prefs.get
prefs.set
prefs.reset
prefs.resetWarningDialogs
edit.preferences.general
edit.preferences.interface
edit.preferences.workspace
+3
View File
@@ -519,3 +519,6 @@ mod brush_noise_strength_tests;
#[cfg(test)]
mod brush_size_fade_end_tests;
#[cfg(test)]
mod symmetry_diagonal_angle_tests;
+24
View File
@@ -5,6 +5,19 @@ use serde::{Deserialize, Serialize};
pub const MAX_COORDINATE: f64 = 1_000_000.0;
/// The Diagonal preset's starting direction, in clockwise degrees over +x (document Y points
/// down). The centred 75 % box has the canvas' own aspect, so its diagonal runs at
/// `atan2(height, width)`: 45° only on a square canvas. `None` when a dimension is zero, which
/// leaves no diagonal to follow.
#[must_use = "the Diagonal preset needs the canvas angle to start on the canvas diagonal"]
pub fn diagonal_start_angle(canvas: [u32; 2]) -> Option<f64> {
let (width, height) = (f64::from(canvas[0]), f64::from(canvas[1]));
if width <= 0.0 || height <= 0.0 {
return None;
}
Some(height.atan2(width).to_degrees())
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, craft_ui_macros::PlainData)]
#[serde(rename_all = "lowercase")]
pub enum SymmetryMode {
@@ -44,6 +57,17 @@ impl PresetSymmetry {
}
Some(Self { mode, center, rotation: rotation.rem_euclid(360.0) })
}
/// The preset for a canvas of `canvas` pixels. Diagonal starts along that canvas' diagonal
/// instead of the fixed 45° line [`Self::directions`] gives it, so the canvas angle is folded
/// into `rotation`, which still means "turned away from the mode's start". Every other mode,
/// and every `canvas` other than a degenerate one, is [`Self::new`].
pub fn for_canvas(mode: SymmetryMode, center: [f64; 2], rotation: f64, canvas: [u32; 2]) -> Option<Self> {
let start = match mode {
SymmetryMode::Diagonal => diagonal_start_angle(canvas)? - 45.0,
_ => 0.0,
};
Self::new(mode, center, rotation + start)
}
pub fn directions(self) -> Vec<[f64; 2]> {
let initial: f64 = match self.mode {
SymmetryMode::Horizontal => 0.0,
@@ -0,0 +1,100 @@
//! #17377: the Diagonal symmetry preset follows the canvas, not a fixed 45° line.
//! The measured rows come from the issue's specification of the reference application; the
//! geometry itself (the diagonal of the centred 75 % box) is ours.
use crate::{
StrokePoint,
symmetry::{PresetSymmetry, SymmetryMode, diagonal_start_angle},
};
const TOL: f64 = 1.0e-9;
fn near(a: [f64; 2], b: [f64; 2], tol: f64) -> bool {
(a[0] - b[0]).abs() < tol && (a[1] - b[1]).abs() < tol
}
fn mirrored(p: PresetSymmetry, x: f64, y: f64) -> [f64; 2] {
let r = p.reflected_passes(&[StrokePoint::new(x, y, 1.0)])[0][0];
[r.x, r.y]
}
#[test]
fn on_800x600_the_diagonal_axis_is_the_canvas_diagonal() {
let s = PresetSymmetry::for_canvas(SymmetryMode::Diagonal, [400.0, 300.0], 0.0, [800, 600]).unwrap();
let d = s.directions()[0];
// The spec's axis runs (100,75)-(700,525): slope 450/600, so its direction is (0.8, 0.6).
assert!(near(d, [0.8, 0.6], 1.0e-9), "expected the (100,75)-(700,525) direction, got {d:?}");
let angle = diagonal_start_angle([800, 600]).unwrap();
assert!((angle - 36.87).abs() < 0.01, "the axis sits at 36.87 degrees, not 45: {angle}");
// The drawn axis stays inside the canvas and keeps that slope end to end.
let [[a, b]] = s.segments([800.0, 600.0])[..].try_into().expect("one diagonal segment");
assert!(near(a, [0.0, 0.0], 1.0e-9) && near(b, [800.0, 600.0], 1.0e-9), "clipped to the canvas diagonal: {a:?} {b:?}");
}
#[test]
fn on_800x600_a_dot_at_170_142_mirrors_to_about_184_123() {
let s = PresetSymmetry::for_canvas(SymmetryMode::Diagonal, [400.0, 300.0], 0.0, [800, 600]).unwrap();
let got = mirrored(s, 170.0, 142.0);
assert!(near(got, [184.0, 123.0], 0.5), "the spec mirrors (170,142) to about (184,123), got {got:?}");
}
#[test]
fn the_axis_slope_follows_the_canvas_aspect() {
for canvas in [[1000u32, 400u32], [300, 900], [640, 480], [800, 600]] {
let (w, h) = (f64::from(canvas[0]), f64::from(canvas[1]));
let s = PresetSymmetry::for_canvas(SymmetryMode::Diagonal, [w / 2.0, h / 2.0], 0.0, canvas).unwrap();
let [dx, dy] = s.directions()[0];
assert!((dy / dx - h / w).abs() < 1.0e-9, "{canvas:?}: the axis follows the canvas aspect, got slope {}", dy / dx);
}
}
#[test]
fn a_square_canvas_keeps_the_45_degree_axis() {
let s = PresetSymmetry::for_canvas(SymmetryMode::Diagonal, [400.0, 400.0], 0.0, [800, 800]).unwrap();
let [dx, dy] = s.directions()[0];
assert!((dx - dy).abs() < TOL, "a square canvas stays at 45 degrees: {dx} {dy}");
assert!((diagonal_start_angle([800, 800]).unwrap() - 45.0).abs() < TOL, "45 degrees on a square canvas");
// A 45° axis through the centre swaps the point's offsets, which is today's result.
assert!(near(mirrored(s, 170.0, 142.0), [142.0, 170.0], 1.0e-9), "the square mirror is unchanged");
}
#[test]
fn transform_symmetry_can_still_rotate_the_axis() {
let s = PresetSymmetry::for_canvas(SymmetryMode::Diagonal, [400.0, 300.0], 90.0, [800, 600]).unwrap();
let d = s.directions()[0];
let dot = d[0] * 0.8 + d[1] * 0.6;
assert!(dot.abs() < 1.0e-9, "a 90 degree turn is perpendicular to the canvas diagonal: {d:?} dot {dot}");
let s45 = PresetSymmetry::for_canvas(SymmetryMode::Diagonal, [400.0, 300.0], 45.0, [800, 600]).unwrap();
let turned = s45.directions()[0];
assert!(
(turned[1] / turned[0] - (diagonal_start_angle([800, 600]).unwrap() + 45.0).to_radians().tan()).abs() < 1.0e-9,
"the turn adds to the canvas angle: {turned:?}"
);
}
#[test]
fn vertical_horizontal_and_dual_are_unchanged_on_a_non_square_canvas() {
for mode in [SymmetryMode::Vertical, SymmetryMode::Horizontal, SymmetryMode::Dual] {
let plain = PresetSymmetry::new(mode, [400.0, 300.0], 0.0).unwrap();
let on_canvas = PresetSymmetry::for_canvas(mode, [400.0, 300.0], 0.0, [800, 600]).unwrap();
assert_eq!(plain.directions(), on_canvas.directions(), "{mode:?} keeps its own start angle");
assert_eq!(plain.mirror_count(), on_canvas.mirror_count(), "{mode:?} keeps its pass count");
for (a, b) in
plain.reflected_passes(&[StrokePoint::new(170.0, 142.0, 1.0)]).iter().zip(on_canvas.reflected_passes(&[StrokePoint::new(170.0, 142.0, 1.0)]))
{
assert!(near([a[0].x, a[0].y], [b[0].x, b[0].y], TOL), "{mode:?} mirrors the same way");
}
}
let dual = PresetSymmetry::for_canvas(SymmetryMode::Dual, [400.0, 300.0], 0.0, [800, 600]).unwrap();
let axes = dual.directions();
assert_eq!(axes.len(), 2, "dual keeps two axes");
assert!((axes[0][0] * axes[1][0] + axes[0][1] * axes[1][1]).abs() < TOL, "the dual axes stay perpendicular");
}
#[test]
fn a_canvas_without_area_has_no_diagonal_angle() {
assert!(diagonal_start_angle([0, 600]).is_none(), "a zero width has no diagonal");
assert!(diagonal_start_angle([800, 0]).is_none(), "a zero height has no diagonal");
assert!(PresetSymmetry::for_canvas(SymmetryMode::Diagonal, [400.0, 300.0], 0.0, [0, 600]).is_none(), "and so no diagonal preset");
assert!(PresetSymmetry::for_canvas(SymmetryMode::Vertical, [400.0, 300.0], 0.0, [0, 600]).is_some(), "the other modes need no angle");
}
+9 -4
View File
@@ -266,10 +266,11 @@ pub(crate) fn tab_title_at(app: &PhotocraftApp, i: usize, zoom: f32) -> String {
};
let layer = active_layer.map(|l| format!("{}, ", l.name)).unwrap_or_default();
// An Indexed or Bitmap document names only its mode, with no bit depth: "(Index)",
// "(Bitmap)" (#17607). A mask target and every other mode keep "RGB/8" and so on.
let mode = match (mask || quick_mask, st.doc.mode) {
(false, photocraft_doc::ColorMode::Indexed) => "Index".to_string(),
(false, photocraft_doc::ColorMode::Bitmap) => "Bitmap".to_string(),
// "(Bitmap)" (#17607). Indexed Quick Mask also omits the bit depth (#19009).
let mode = match (mask, quick_mask, st.doc.mode) {
(_, true, photocraft_doc::ColorMode::Indexed) => model,
(false, false, photocraft_doc::ColorMode::Indexed) => "Index".to_string(),
(false, false, photocraft_doc::ColorMode::Bitmap) => "Bitmap".to_string(),
_ => format!("{model}/{}", st.doc.depth.bits()),
};
// A save in progress: "name @ 100% (Layer 1, RGB/16) - Saving 45%", as Photoshop does (#3389).
@@ -314,6 +315,10 @@ pub(super) fn move_target_after_filter(visible: &[usize], from: usize, to: usize
#[path = "../file_info_copyright_title_tests.rs"]
mod file_info_copyright_title_tests;
#[cfg(test)]
#[path = "../quick_mask_indexed_tab_title_tests.rs"]
mod quick_mask_indexed_tab_title_tests;
#[cfg(test)]
#[path = "tab_indexed_bitmap_label_tests.rs"]
mod tab_indexed_bitmap_label_tests;
+3 -15
View File
@@ -8,7 +8,7 @@ use craft::host::Host;
use craft::settings::Remembered;
use craft::ui::dialog::{DialogId, DialogResult, HeldOk, PromptAnswer, StandardPrompt};
use photocraft_doc::DocId;
use photocraft_engine::prefs::Preferences;
use photocraft_engine::prefs::{Preferences, WARNING_DIALOG_KEYS};
use serde_json::Value;
use crate::PhotocraftApp;
@@ -559,6 +559,7 @@ pub fn run(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
crate::filter_dialog::reconcile_match_color(app);
filter_preview_ui::feed(app, ui.ctx());
crate::prefs_ui::feed(app);
alerts::feed_restored_warning(app, ui.ctx());
app.framework.dialogs.run(ui);
take_results(app, &ui.ctx().clone());
}
@@ -693,23 +694,10 @@ const ENGINE_READ: &[&str] =
/// copied there only while it holds none. An empty recorded Content-Aware Fill step plays with the engine's copy (#14254).
const ENGINE_READ_SHARED: &[&str] = &[photocraft_engine::atn_cmds::CAF_WORKSPACE_PREFS];
/// The "Don't show again" entries (`{"skip": true}`), by key, as their prompt modules read them. Told apart by key, not
/// by the shape of the value.
fn dont_show_again_keys() -> [&'static str; 6] {
[
delete_layer_prompt::PREF,
live_shape_prompt::PREF,
assign_profile_layers_alert::PREF,
crate::analysis::note_alerts::DELETE_NOTE_PREF,
crate::retouch_ui::CAM_NO_PIXELS_PREF,
replace_layer_mask_prompt::PREF,
]
}
/// Where the remembered value of the preference entry `key` goes: `None` keeps it in `Preferences.dialogs`, else the
/// scope it moves to. Order: keep, then route, then the generic `photocraft.<key>`.
fn memory_destination(key: &str) -> Option<String> {
if ENGINE_READ.contains(&key) || dont_show_again_keys().contains(&key) {
if ENGINE_READ.contains(&key) || WARNING_DIALOG_KEYS.contains(&key) {
return None;
}
// The keys the app passes to a workspace or dialog (`select.refineEdge.workspace`, `edit.contentAwareFill.workspace`,
+54
View File
@@ -8,6 +8,7 @@
use craft::behavior::IconId;
use craft::ui::dialog::{Alert, DialogId, HostedAlert, PromptAnswer, PromptChoice, StackDialog, StandardPrompt};
use photocraft_engine::prefs::{RESET_WARNING_DIALOGS, WARNING_DIALOG_RESTORED};
use serde_json::{Value, json};
use crate::PhotocraftApp;
@@ -17,6 +18,8 @@ pub(crate) struct AlertOnce {
pref: &'static str,
}
struct ResetWarningDialogs;
/// The title every alert of the app carries.
const TITLE: &str = "PhotoCraft";
@@ -57,6 +60,48 @@ pub fn dismissed(app: &PhotocraftApp, pref: &str) -> bool {
app.session.prefs().dialogs.get(pref).and_then(|v| v.get("skip")).and_then(Value::as_bool) == Some(true)
}
/// Confirms the immediate reset independently of the Preferences window's draft.
pub(crate) fn ask_reset_warning_dialogs(app: &mut PhotocraftApp) {
let prompt = StandardPrompt::custom(tl!("Show previously dismissed warning dialogs again?"))
.title(tl!("Preferences"))
.icon(IconId::new("info"))
.button(PromptChoice::Proceed, tl!("OK"))
.button(PromptChoice::Cancel, tl!("Cancel"))
.tag(ResetWarningDialogs);
let _ = open_prompt(app, prompt);
}
fn warning_pref(prompt: &StandardPrompt) -> Option<&'static str> {
use super::{assign_profile_layers_alert, delete_layer_prompt, live_shape_prompt, replace_layer_mask_prompt};
use crate::analysis::note_alerts::{DELETE_NOTE_PREF, NoteQuestion};
if let Some(once) = prompt.tag_as::<AlertOnce>() {
Some(once.pref)
} else if prompt.tag_as::<delete_layer_prompt::PendingDelete>().is_some() {
Some(delete_layer_prompt::PREF)
} else if prompt.tag_as::<live_shape_prompt::LiveShapeAsk>().is_some() {
Some(live_shape_prompt::PREF)
} else if prompt.tag_as::<assign_profile_layers_alert::AssignProfileAsk>().is_some() {
Some(assign_profile_layers_alert::PREF)
} else if matches!(prompt.tag_as::<NoteQuestion>(), Some(NoteQuestion::Delete { .. })) {
Some(DELETE_NOTE_PREF)
} else if prompt.tag_as::<replace_layer_mask_prompt::ReplaceMask>().is_some() {
Some(replace_layer_mask_prompt::PREF)
} else {
None
}
}
/// Apply the reset's initial checkbox value once, before the prompt first receives input.
pub(crate) fn feed_restored_warning(app: &mut PhotocraftApp, ctx: &egui::Context) {
let Some(prompt) = app.framework.dialogs.get_mut::<StandardPrompt>() else { return };
let Some(pref) = warning_pref(prompt) else { return };
let restored = app.session.prefs().dialogs.get(pref).and_then(|value| value.get(WARNING_DIALOG_RESTORED)).and_then(Value::as_bool) == Some(true);
if restored && prompt.set_json_field(ctx, "skip", json!(true)).is_ok() {
app.session.edit_prefs(|prefs| prefs.dialogs.remove(pref));
}
}
/// [`alert_once`] with the catalog's info icon beside the message, as the reference shows for the
/// Content-Aware Fill workspace's Custom sampling alert (#16693). The other alerts keep their look.
pub fn info_once(app: &mut PhotocraftApp, message: impl Into<String>, pref: &'static str) -> Option<DialogId> {
@@ -105,6 +150,15 @@ pub(crate) fn report(app: &mut PhotocraftApp, result: Result<Value, String>) {
/// The `PROMPTS` entry of [`alert_once`]: stores a ticked box. `false` when the answer is another
/// family's.
pub(crate) fn answer(app: &mut PhotocraftApp, _ctx: &egui::Context, answer: &mut PromptAnswer) -> bool {
if answer.take_tag::<ResetWarningDialogs>().is_some() {
if answer.choice == PromptChoice::Proceed {
let result = app.run(RESET_WARNING_DIALOGS, json!({})).and_then(|_| crate::prefs_ui::save_preferences(app));
if let Err(error) = result {
report_error(app, error);
}
}
return true;
}
let Some(AlertOnce { pref }) = answer.take_tag::<AlertOnce>() else { return false };
if answer.skip {
remember_skip(app, pref);
@@ -22,7 +22,7 @@ use craft::ui::style::TypeRole;
use craft::ui::text::{NumberField, TextField, TextWords};
use serde_json::{Value, json};
use super::fields::{PrefPages, choice_label};
use super::fields::{PrefPages, RESET_WARNING_DIALOGS_ROW, choice_label};
use super::{PhotocraftApp, prefs};
use craft::ui::patterns::preferences::{CustomSettings, SettingsDraft};
use photocraft_engine::prefs::{RawSharpen, RawSharpenAmount};
@@ -91,6 +91,11 @@ impl PrefsCustom {
impl CustomSettings<PrefPages> for PrefsCustom {
fn row(&mut self, ui: &mut egui::Ui, key: &str, draft: &mut SettingsDraft) -> bool {
match key {
RESET_WARNING_DIALOGS_ROW => {
if Button::new(tl!("Reset All Warning Dialogs")).show(ui).clicked() {
ui.data_mut(|data| data.insert_temp(reset_warning_dialogs_id(), true));
}
}
MEMORY_PERCENT => memory_percent_row(ui, draft),
MEMORY_MB => self.memory_mb_row(ui, draft),
RENDERING_MODE => rendering_mode_row(ui, draft),
@@ -121,6 +126,10 @@ impl CustomSettings<PrefPages> for PrefsCustom {
}
}
pub(super) fn reset_warning_dialogs_id() -> egui::Id {
egui::Id::unique(RESET_WARNING_DIALOGS_ROW)
}
/// The GPU memory budget lines of Performance › Graphics.
fn gpu_memory_lines(app: &PhotocraftApp) -> Vec<String> {
let mut v = Vec::new();
+19 -3
View File
@@ -216,13 +216,21 @@ impl StackDialog for PrefsDialog {
}
fn json_fields(&self) -> Option<Value> {
let values = self.doc.as_ref()?.draft().to::<Value>()?;
let mut values = self.doc.as_ref()?.draft().to::<Value>()?;
if let Some(general) = values.get_mut("general").and_then(Value::as_object_mut) {
general.remove("resetWarningDialogs");
}
Some(json!({"values": values, "page": self.state.selected}))
}
fn set_json_field(&mut self, _ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> {
fn set_json_field(&mut self, _ctx: &egui::Context, field: &str, mut value: Value) -> Result<(), String> {
match field {
"values" => self.doc.as_mut().ok_or("Preferences is not open")?.draft_mut().replace(&value).map_err(|e| format!("`values` is not valid: {e}")),
"values" => {
if let Some(general) = value.get_mut("general").and_then(Value::as_object_mut) {
general.insert("resetWarningDialogs".into(), json!(false));
}
self.doc.as_mut().ok_or("Preferences is not open")?.draft_mut().replace(&value).map_err(|e| format!("`values` is not valid: {e}"))
}
"page" => {
self.state.selected = value.as_str().ok_or("`page` is not valid: not text")?.to_string();
Ok(())
@@ -340,6 +348,10 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
if let Some(message) = range_alert {
let _ = crate::dialogs::alerts::alert(app, message);
}
// The reset button requests its own confirmation, even when Preferences closes in this pass.
if ctx.data_mut(|data| data.remove_temp::<bool>(super::custom_rows::reset_warning_dialogs_id())).unwrap_or(false) {
crate::dialogs::alerts::ask_reset_warning_dialogs(app);
}
if let Some((key, color)) = crate::color_picker_ui::answer_for_window(app, PickWindow::Preferences)
&& let Some(doc) = app.framework.dialogs.get_mut::<PrefsDialog>().and_then(|d| d.doc.as_mut())
{
@@ -352,6 +364,10 @@ pub(crate) fn take(app: &mut PhotocraftApp, ctx: &egui::Context) {
}
}
#[cfg(test)]
#[path = "../reset_warning_dialogs_tests.rs"]
mod reset_warning_dialogs_tests;
/// Applies the open window's draft as its Apply button does and keeps the window open. `Err` when it is closed, a
/// colour picker it opened is still open, or the engine refuses a value.
pub fn apply_window(app: &mut PhotocraftApp) -> Result<Value, String> {
+17 -2
View File
@@ -14,7 +14,7 @@ use serde_json::{Map, Value};
#[derive(Serialize, Deserialize, Default, Clone, PartialEq)]
#[serde(default, rename_all = "camelCase")]
pub(super) struct PrefPages {
general: prefs::General,
general: GeneralPage,
interface: prefs::Interface,
workspace: prefs::Workspace,
tools: prefs::Tools,
@@ -35,11 +35,22 @@ pub(super) struct PrefPages {
integrations: prefs::Integrations,
}
/// The General page adds a button after its engine-backed settings. Its placeholder never becomes a preference.
#[derive(Serialize, Deserialize, Default, Clone, PartialEq)]
#[serde(default, rename_all = "camelCase")]
struct GeneralPage {
#[serde(flatten)]
settings: prefs::General,
reset_warning_dialogs: bool,
}
pub(super) const RESET_WARNING_DIALOGS_ROW: &str = "general.resetWarningDialogs";
impl PrefPages {
/// The pages of `prefs`.
pub(super) fn of(prefs: &prefs::Preferences) -> Self {
PrefPages {
general: prefs.general.clone(),
general: GeneralPage { settings: prefs.general.clone(), ..Default::default() },
interface: prefs.interface.clone(),
workspace: prefs.workspace.clone(),
tools: prefs.tools.clone(),
@@ -66,6 +77,9 @@ impl PrefPages {
let mut values = Map::new();
let mut resets = Vec::new();
for (key, value) in edits {
if key == RESET_WARNING_DIALOGS_ROW {
continue;
}
match value {
Some(value) => {
if let Ok(json) = serde_json::to_value(&value) {
@@ -197,6 +211,7 @@ pub(super) fn rules(ctx: &egui::Context) -> Vec<SettingRule> {
// The pause that bundles arrow-key nudges means nothing with Bundle Arrow-Key Nudges off.
tweak(&mut rules, "tools.nudgeBundlePauseMs", |r| r.shown_when("tools.bundleNudges", "true"));
tweak(&mut rules, RESET_WARNING_DIALOGS_ROW, |r| r.label("Reset All Warning Dialogs").custom_rows());
rules.into_values().collect()
}
@@ -0,0 +1,180 @@
//! General's warning reset uses the real Preferences window, dialog host and saved preferences.
use std::sync::Arc;
use craft::settings::testing::MemoryFiles;
use egui::accesskit::{Role, Toggled};
use egui::{Key, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_engine::prefs::{RESET_WARNING_DIALOGS, WARNING_DIALOG_KEYS, WARNING_DIALOG_RESTORED};
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::dialogs::alerts;
const LABEL: &str = "Reset All Warning Dialogs";
const WARNING: &str = crate::retouch_ui::CAM_NO_PIXELS_PREF;
const UNRELATED: &str = "file.print";
const DELETE_LAYER: &str = "layer.delete.confirmation";
const ASK: &str = "Show previously dismissed warning dialogs again?";
type H = Harness<'static, Box<PhotocraftApp>>;
fn seed(app: &mut PhotocraftApp) {
app.session.edit_prefs(|prefs| {
for key in WARNING_DIALOG_KEYS.iter().copied() {
prefs.dialogs.insert(key.into(), json!({"skip": true}));
}
prefs.dialogs.insert(UNRELATED.into(), json!({"paper": "a4", "skip": true}));
});
}
fn harness(files: &Arc<MemoryFiles>, page: Option<&'static str>) -> H {
let files = Arc::clone(files);
let mut h = Harness::builder().with_size(vec2(1280.0, 1000.0)).build_eframe(move |cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), photocraft_engine::Session::new(), crate::testing::services_over(&files));
if let Some(page) = page {
super::open_preferences(&mut app, page);
}
app
});
h.run_steps(4);
h
}
fn assert_restored(app: &PhotocraftApp) {
for key in WARNING_DIALOG_KEYS {
assert!(!alerts::dismissed(app, key), "{key} is no longer silenced");
assert_eq!(app.session.prefs().dialogs.get(*key).and_then(|v| v.get(WARNING_DIALOG_RESTORED)), Some(&Value::Bool(true)));
}
assert_eq!(app.session.prefs().dialogs.get(UNRELATED), Some(&json!({"paper": "a4", "skip": true})));
}
#[test]
fn confirmation_resets_only_known_warnings_and_persists_even_if_preferences_is_cancelled() -> Result<(), String> {
let files = Arc::new(MemoryFiles::new());
let mut h = harness(&files, Some("general"));
seed(h.state_mut());
crate::prefs_ui::save_preferences(h.state_mut())?;
let button = h.get_by_role_and_label(Role::Button, LABEL);
let last_option = h.get_by_role_and_label(Role::CheckBox, "Automatically Check for Updates");
assert!(button.rect().top() > last_option.rect().top());
assert!(!button.accesskit_node().is_disabled());
button.click();
h.run_steps(4);
assert!(h.query_all_by_label(ASK).next().is_some());
h.key_press(Key::Escape);
h.run_steps(4);
assert!(super::window_open(h.state()));
assert!(WARNING_DIALOG_KEYS.iter().all(|key| alerts::dismissed(h.state(), key)));
h.get_by_role_and_label(Role::Button, LABEL).click();
h.run_steps(4);
assert!(h.query_all_by_label(ASK).next().is_some());
h.key_press(Key::Enter);
h.run_steps(4);
assert!(super::window_open(h.state()));
assert_restored(h.state());
h.key_press(Key::Escape);
h.run_steps(4);
assert!(!super::window_open(h.state()));
assert_restored(h.state());
drop(h);
let mut restarted = harness(&files, None);
assert_restored(restarted.state());
assert!(alerts::alert_once(restarted.state_mut(), "No pixels are selected.", WARNING).is_some());
restarted.run_steps(4);
let check = "Don't show again";
assert_eq!(restarted.get_by_role_and_label(Role::CheckBox, check).accesskit_node().toggled(), Some(Toggled::True));
restarted.get_by_role_and_label(Role::CheckBox, check).click();
restarted.run_steps(4);
assert_eq!(restarted.get_by_role_and_label(Role::CheckBox, check).accesskit_node().toggled(), Some(Toggled::False));
restarted.key_press(Key::Enter);
restarted.run_steps(4);
assert!(!alerts::dismissed(restarted.state(), WARNING));
assert!(alerts::alerts(restarted.state()).is_empty());
assert!(alerts::alert_once(restarted.state_mut(), "No pixels are selected.", WARNING).is_some());
restarted.run_steps(4);
assert_eq!(restarted.get_by_role_and_label(Role::CheckBox, check).accesskit_node().toggled(), Some(Toggled::False));
restarted.key_press(Key::Enter);
restarted.run_steps(4);
restarted.state_mut().run("file.new", json!({"width": 8, "height": 8}))?;
restarted.state_mut().run("layer.new.layer", json!({"name": "Keep this layer"}))?;
assert_eq!(restarted.state_mut().run("layer.delete", json!({"__trash": true}))?["confirmationPending"], true);
restarted.run_steps(4);
assert_eq!(restarted.get_by_role_and_label(Role::CheckBox, check).accesskit_node().toggled(), Some(Toggled::True));
restarted.key_press(Key::Escape);
restarted.run_steps(4);
assert!(!alerts::dismissed(restarted.state(), DELETE_LAYER));
assert!(restarted.state().session.active().is_some_and(|st| st.doc.layers.iter().any(|layer| layer.name == "Keep this layer")));
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn automation_can_reset_warnings_without_opening_a_dialog_or_recording_an_action_step() -> Result<(), String> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
seed(&mut app);
assert!(app.run(RESET_WARNING_DIALOGS, json!({"allPreferences": true})).is_err());
assert!(WARNING_DIALOG_KEYS.iter().all(|key| alerts::dismissed(&app, key)));
app.run("actions.record", json!({"name": "Warning reset should not record"}))?;
let ctx = app.ctx().clone();
let (request, _reply) = crate::control::ControlRequest::new("engine.execute", json!({"command": RESET_WARNING_DIALOGS, "params": {}}));
let crate::control::Reply::Done(reply) = crate::control::handle(&mut app, &ctx, &request) else {
return Err("warning reset should return an immediate reply".into());
};
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(reply["result"]["reset"], WARNING_DIALOG_KEYS.len());
assert_restored(&app);
assert!(app.framework.dialogs.open_dialogs().is_empty());
assert_eq!(app.run("actions.stop", json!({}))?["steps"], 0);
assert_eq!(app.run(RESET_WARNING_DIALOGS, json!({}))?["reset"], 0);
Ok(())
}
#[test]
fn closing_preferences_does_not_consume_the_pending_reset_confirmation() {
use super::super::custom_rows::reset_warning_dialogs_id;
for confirm_preferences in [false, true] {
let files = Arc::new(MemoryFiles::new());
let mut h = harness(&files, Some("general"));
seed(h.state_mut());
let ctx = h.ctx.clone();
let id = craft::ui::dialog::dialog_id("photocraft.preferences");
// The General button has emitted its request when the host also closes Preferences.
ctx.data_mut(|data| data.insert_temp(reset_warning_dialogs_id(), true));
let dialogs = &mut h.state_mut().framework.dialogs;
let closed = if confirm_preferences { dialogs.confirm_by_id(&ctx, id) } else { dialogs.cancel_by_id(&ctx, id) };
assert!(closed);
assert!(!super::window_open(h.state()));
super::take(h.state_mut(), &ctx);
h.run_steps(4);
assert!(h.query_all_by_label(ASK).next().is_some());
assert!(alerts::dismissed(h.state(), WARNING), "closing Preferences does not confirm the reset");
h.key_press(Key::Enter);
h.run_steps(4);
assert_restored(h.state());
assert!(h.query_all_by_label(ASK).next().is_none(), "the request is consumed once");
}
}
#[test]
fn reset_restores_dismissals_from_object_selection_quick_mask_and_content_aware_fill() -> Result<(), String> {
let keys = ["objectSelection.notFound", "quickMask.noPixelsSelected", "contentAwareFill.customSampling"];
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.session.edit_prefs(|prefs| {
for key in keys {
prefs.dialogs.insert(key.into(), json!({"skip": true}));
}
});
assert_eq!(app.run(RESET_WARNING_DIALOGS, json!({}))?["reset"], keys.len());
for key in keys {
assert!(!alerts::dismissed(&app, key));
assert_eq!(app.session.prefs().dialogs.get(key).and_then(|v| v.get(WARNING_DIALOG_RESTORED)), Some(&Value::Bool(true)));
}
Ok(())
}
@@ -0,0 +1,76 @@
use serde_json::json;
use crate::PhotocraftApp;
use super::tab_title_at;
fn app(depth: u8) -> Box<PhotocraftApp> {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 40, "height": 30, "name": "oracle", "depth": depth})).unwrap();
app
}
fn indexed(app: &mut PhotocraftApp) {
app.run("image.mode.indexedColor", json!({"palette": "exact", "forced": "none", "dither": "none", "transparency": false})).unwrap();
}
fn quick_mask(app: &mut PhotocraftApp, on: bool) {
app.run("select.editInQuickMaskMode", json!({"on": on})).unwrap();
}
fn title(app: &PhotocraftApp) -> String {
tab_title_at(app, 0, 100.0)
}
#[test]
fn indexed_quick_mask_omits_the_depth_and_restores_index_on_exit() {
let mut app = app(8);
indexed(&mut app);
assert_eq!(title(&app), "oracle @ 100% (Index)");
quick_mask(&mut app, true);
assert_eq!(title(&app), "oracle @ 100% (Quick Mask)");
quick_mask(&mut app, false);
assert_eq!(title(&app), "oracle @ 100% (Index)");
app.run("layer.new.layer", json!({"name": "Top"})).unwrap();
quick_mask(&mut app, true);
assert_eq!(title(&app), "oracle @ 100% (Top, Quick Mask)");
}
#[test]
fn rgb_quick_mask_displays_the_document_depth() {
for depth in [8, 16, 32] {
let mut app = app(depth);
quick_mask(&mut app, true);
assert_eq!(title(&app), format!("oracle @ 100% (Quick Mask/{depth})"));
}
}
#[test]
fn other_measured_modes_keep_the_depth_in_quick_mask() {
for command in ["image.mode.grayscale", "image.mode.cmyk", "image.mode.lab", "image.mode.multichannel"] {
let mut app = app(8);
app.run(command, json!({})).unwrap();
quick_mask(&mut app, true);
assert_eq!(title(&app), "oracle @ 100% (Quick Mask/8)", "{command}");
}
}
#[test]
fn bitmap_outside_quick_mask_omits_the_depth() {
let mut app = app(8);
app.run("image.mode.grayscale", json!({})).unwrap();
app.run("image.mode.bitmap", json!({"method": "threshold"})).unwrap();
assert_eq!(title(&app), "oracle @ 100% (Bitmap)");
}
#[test]
fn indexed_layer_mask_keeps_its_depth() {
let mut app = app(8);
indexed(&mut app);
app.run("layer.new.layer", json!({"name": "Top"})).unwrap();
let layer = app.session.active().unwrap().active_layer.unwrap();
app.run("layer.layerMask.revealAll", json!({"layer": layer.0})).unwrap();
app.run("channel.target", json!({"channel": "mask"})).unwrap();
assert_eq!(title(&app), "oracle @ 100% (Top, Layer Mask/8)");
}