dialogs-w17: net change of 2 commits

- dialogs-w17: written by an agent
- dialogs-w17: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor committed 2026-11-27 14:51:30 +00:00
1 parent ac7ef11cde
commit 7353f0f171
2 files changed
+532 -172

No files matched your search

+420 -67
View File
@@ -1,57 +1,37 @@
use super::{Dialog, SlideApp, Value, json, theme};
//! The app's live preferences transaction and its nested AutoCorrect form.
/// What the Preferences dialog can change, as it was when the dialog opened.
pub(super) fn preferences_snapshot(app: &SlideApp) -> Value {
json!({
"dark": app.ui.brightness == theme::Brightness::Dark,
"uiScale": app.ui.ui_scale,
"prefs": serde_json::to_value(&app.session.prefs).unwrap_or(Value::Null),
})
}
use craft::behavior::{ColumnKey, ColumnWidth, keyed};
use craft::ui::buttons::Button;
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, CollectionEvent, ColumnSpec, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _};
use craft::ui::dialog::{DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field};
use craft::ui::layout_components::Row;
use craft::ui::list::{ListRow, RowEvent, TrailingFace, TrailingPart};
use craft::ui::patterns::form_dialogs::{FormButtons, FormDialog};
use craft::ui::patterns::preferences::{
Closed, GroupSpec, PageSpec, PrefValue, PreferencesDraft, PreferencesLayout, PreferencesMode, PreferencesModel, PreferencesState,
PreferencesWindow, RowKind, RowSpec,
};
use craft::ui::runtime::env::Word;
use craft::ui::table::Table;
use craft::ui::text::TextField;
use craft::ui::value_drag::Slider;
use deckcraft_geom::Unit;
use egui::{Context, Ui};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
/// Puts back the settings the Preferences dialog opened with (Cancel, Esc, the close button).
pub(super) fn restore_preferences(app: &mut SlideApp, d: &Dialog) {
let Some(before) = d.params.get("before") else { return };
if let Some(dark) = before.get("dark").and_then(Value::as_bool)
&& dark != (app.ui.brightness == theme::Brightness::Dark)
{
let _ = app.run("view.dark", json!({ "on": dark }));
}
if let Some(scale) = before.get("uiScale").and_then(Value::as_f64) {
app.ui.ui_scale = scale as f32;
}
if let Some(prefs) = before.get("prefs").and_then(|p| serde_json::from_value(p.clone()).ok()) {
app.session.prefs = prefs;
}
}
use crate::SlideApp;
use crate::state::Brightness;
/// Opens this typed dialog in the host.
#[allow(dead_code)] // P3(dialogs-w17): dl.A10
pub(crate) fn open(
app: &mut crate::SlideApp,
ctx: &egui::Context,
host: &mut craft::ui::dialog::DialogHost,
params: &serde_json::Value,
) -> Result<Option<craft::ui::dialog::DialogId>, String> {
let _ = (app, ctx, host, params);
todo!("dl.A10")
}
/// Advances this typed dialog in the host.
#[allow(dead_code)] // P3(dialogs-w17): dl.A10
pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) {
let _ = (app, ctx, host);
todo!("dl.A10")
}
/// The preferences draft with the app and engine setting types.
#[allow(dead_code)] // P3(dialogs-w17): dl.A14
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
/// The settings restored together when Preferences is cancelled.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct PrefDraft {
dark: bool,
ui_scale: f64,
units: deckcraft_geom::Unit,
/// The unit shared with the automation preferences writer.
pub(crate) units: Unit,
smart_guides: bool,
snap_to_grid: bool,
smart_quotes: bool,
@@ -66,28 +46,401 @@ pub(crate) struct PrefDraft {
ac_lists: bool,
}
/// Copies current preferences into a draft.
#[allow(dead_code)] // P3(dialogs-w17): dl.A14
pub(crate) fn of(app: &crate::SlideApp) -> PrefDraft {
let _ = app;
todo!("dl.A14")
// One order serves the form, automation and both directions of the flags transaction.
macro_rules! autocorrect_flags {
($($field:ident => ($key:literal, $label:literal)),+ $(,)?) => {
const FLAG_FIELDS: [(&str, &str); 8] = [$(($key, $label)),+];
impl PrefDraft {
fn flags(&self) -> [bool; 8] {
[$(self.$field),+]
}
fn set_flags(&mut self, flags: [bool; 8]) {
let [$($field),+] = flags;
$(self.$field = $field;)+
}
}
};
}
/// Applies a preferences draft.
#[allow(dead_code)] // P3(dialogs-w17): dl.A14
pub(crate) fn write(app: &mut crate::SlideApp, draft: &PrefDraft) {
let _ = (app, draft);
todo!("dl.A14")
autocorrect_flags! {
ac_two_initials => ("acTwoInitials", "Correct TWo INitial CApitals"),
ac_sentence_caps => ("acSentenceCaps", "Capitalize first letter of sentences"),
ac_days => ("acDays", "Capitalize names of days"),
ac_caps_lock => ("acCapsLock", "Correct accidental use of cAPS LOCK key"),
ac_fractions => ("acFractions", "Replace fractions (1/2) with fraction characters (½)"),
ac_ordinals => ("acOrdinals", "Ordinals (1st) with superscript"),
ac_lists => ("acLists", "Automatic bulleted and numbered lists"),
autocorrect => ("autocorrect", "Replace text as you type"),
}
/// Opens nested AutoCorrect while retaining its Preferences parent.
#[allow(dead_code)] // P3(dialogs-w17): dl.A10
pub(crate) fn open_autocorrect(
app: &mut crate::SlideApp,
ctx: &egui::Context,
host: &mut craft::ui::dialog::DialogHost,
params: &serde_json::Value,
) -> Result<Option<craft::ui::dialog::DialogId>, String> {
let _ = (app, ctx, host, params);
todo!("dl.A10")
/// Copies the settings that Preferences owns, excluding immediate replacement-list edits.
pub(crate) fn of(app: &SlideApp) -> PrefDraft {
let prefs = &app.session.prefs;
PrefDraft {
dark: app.ui.brightness == Brightness::Dark,
ui_scale: f64::from(app.ui.ui_scale),
units: prefs.units,
smart_guides: prefs.smart_guides,
snap_to_grid: prefs.snap_to_grid,
smart_quotes: prefs.smart_quotes,
autocorrect: prefs.autocorrect,
author: prefs.author.clone(),
ac_two_initials: prefs.ac_two_initials,
ac_sentence_caps: prefs.ac_sentence_caps,
ac_days: prefs.ac_days,
ac_caps_lock: prefs.ac_caps_lock,
ac_fractions: prefs.ac_fractions,
ac_ordinals: prefs.ac_ordinals,
ac_lists: prefs.ac_lists,
}
}
/// Applies the shared preferences value; persistence belongs to the shell's settings store.
pub(crate) fn write(app: &mut SlideApp, draft: &PrefDraft) {
if draft.dark != (app.ui.brightness == Brightness::Dark)
&& let Err(error) = app.run("view.dark", json!({ "on": draft.dark }))
{
app.set_status(error);
}
let scale = draft.ui_scale as f32;
if app.ui.ui_scale != scale {
app.ui.ui_scale = scale;
}
let prefs = &mut app.session.prefs;
macro_rules! assign {
($($field:ident),+ $(,)?) => {
$(if prefs.$field != draft.$field {
prefs.$field = draft.$field;
})+
};
}
assign!(
units, smart_guides, snap_to_grid, smart_quotes, autocorrect, ac_two_initials, ac_sentence_caps, ac_days, ac_caps_lock,
ac_fractions, ac_ordinals, ac_lists,
);
if prefs.author != draft.author {
prefs.author.clone_from(&draft.author);
}
}
struct AutoCorrectForm {
flags: [bool; 8],
from: String,
to: String,
entries: Vec<(String, String)>,
}
impl AutoCorrectForm {
fn new(draft: &PrefDraft, actions: &mut Vec<Value>) -> Self {
actions.push(json!({}));
Self { flags: draft.flags(), from: String::new(), to: String::new(), entries: Vec::new() }
}
fn show(&mut self, ui: &mut Ui, actions: &mut Vec<Value>) -> Option<Option<[bool; 8]>> {
let Self { flags, from, to, entries } = self;
let shown = FormDialog::new(Word::plain("AutoCorrect"), Bind::bound(flags)).buttons(FormButtons::OkCancel).show(ui, |ui, _, flags| {
for ((_, label), flag) in FLAG_FIELDS.iter().zip(flags.iter_mut()) {
Checkbox::new(Bind::bound(flag)).label(Word::plain(label)).show(ui);
}
Row::new().show(ui, |ui, _| {
TextField::new(Word::plain("Replace"), Bind::bound(&mut *from)).show(ui);
TextField::new(Word::plain("With"), Bind::bound(&mut *to)).show(ui);
if Button::new(Word::plain("Add")).enabled(!from.trim().is_empty()).show(ui).clicks > 0 {
actions.push(json!({ "add": [from.trim(), to] }));
from.clear();
to.clear();
}
});
let query = from.trim().to_lowercase();
let visible: Vec<_> = entries.iter().filter(|(key, _)| key.to_lowercase().starts_with(&query)).collect();
let source = keyed(&visible, |entry| entry.0.clone());
const FROM: ColumnKey = ColumnKey::new("from");
const TO: ColumnKey = ColumnKey::new("to");
let columns = vec![
ColumnSpec::new(FROM, Word::plain("Replace"), ColumnWidth::Content),
ColumnSpec::new(TO, Word::plain("With"), ColumnWidth::fill(1.0)),
];
const DELETE: TrailingPart = TrailingPart::new(0);
let shown = Table::new(Word::plain("Replacements"), columns).striped(true).max_rows(8).show_items(ui, &source, &mut |key, cx| {
let replacement = entries.iter().find(|(from, _)| from == key).map(|(_, to)| to.clone()).unwrap_or_default();
ListRow::new(key.clone()).cells(cx.cells()).striped(cx.row.striped).cell(TO, replacement).trailing_part(
DELETE,
TrailingFace::Strong(Word::plain("Delete").into()),
Word::plain("Delete"),
)
});
for event in shown.events {
if let CollectionEvent::Item(key, RowEvent::Trailing { part: DELETE, .. }) = event {
actions.push(json!({ "remove": key }));
}
}
true
});
if let Some(flags) = shown.accepted { Some(Some(flags)) } else { shown.closed.map(|_| None) }
}
}
struct PreferencesDialog {
state: PreferencesState,
draft: PrefDraft,
saved: PrefDraft,
applied: Option<PrefDraft>,
scale_shown: f64,
autocorrect: Option<AutoCorrectForm>,
actions: Vec<Value>,
}
impl PreferencesModel for PreferencesDialog {
fn pages(&self) -> Vec<PageSpec<'_>> {
let d = &self.draft;
let general = GroupSpec::new(
Some("General"),
vec![
RowSpec::new("dark", "Dark appearance", RowKind::Bool(d.dark)),
RowSpec::new("uiScale", "Interface size", RowKind::Custom),
RowSpec::new(
"units",
"Measurement units",
RowKind::choice(
match d.units {
Unit::Inches => "inches",
Unit::Centimeters => "centimeters",
Unit::Points => "points",
Unit::Pixels => "pixels",
},
vec![Entry::new("inches", "Inches"), Entry::new("centimeters", "Centimeters")],
),
)
.pills(true),
],
);
let editing = GroupSpec::new(
Some("Editing"),
vec![
RowSpec::new("smartGuides", "Show smart guides", RowKind::Bool(d.smart_guides)),
RowSpec::new("snapToGrid", "Snap objects to grid", RowKind::Bool(d.snap_to_grid)),
RowSpec::new("smartQuotes", "Replace straight quotes with smart quotes", RowKind::Bool(d.smart_quotes)),
RowSpec::new("autocorrect", "AutoCorrect as you type", RowKind::CustomRows).keywords("AutoCorrect Options"),
RowSpec::new("author", "Your name (comments)", RowKind::Text(&d.author)),
],
);
let mut page = PageSpec::new("preferences", "Preferences", Vec::new()).resettable(false);
page.groups = vec![general, editing];
vec![page]
}
fn set(&mut self, key: &str, value: PrefValue) {
let json = match value {
PrefValue::Bool(value) => json!(value),
PrefValue::Text(value) | PrefValue::Choice(value) => json!(value),
PrefValue::Float(value) => json!(value),
_ => return,
};
if set_serde_field(&mut self.draft, key, json).is_ok() && key == "uiScale" {
self.scale_shown = self.draft.ui_scale;
}
}
fn custom_row(&mut self, ui: &mut Ui, key: &str) -> bool {
match key {
"uiScale" => {
let response = Slider::new(Bind::bound(&mut self.scale_shown), 0.75..=1.75).label(Word::plain("Interface size")).show(ui);
// Applying Update would resize the track under the pointer.
if let Some(value) = response.events.committed() {
let changed = self.draft.ui_scale != *value;
self.draft.ui_scale = *value;
changed
} else {
false
}
}
"autocorrect" => {
let before = self.draft.autocorrect;
Row::new().show(ui, |ui, _| {
Checkbox::new(Bind::bound(&mut self.draft.autocorrect)).label(Word::plain("AutoCorrect as you type")).show(ui);
if Button::new(Word::plain("AutoCorrect Options…")).show(ui).clicks > 0 {
self.autocorrect = Some(AutoCorrectForm::new(&self.draft, &mut self.actions));
}
});
before != self.draft.autocorrect
}
_ => false,
}
}
fn custom_page(&mut self, _ui: &mut Ui, _page: &str) -> bool {
false
}
fn reset_page(&mut self, _page: &str) {}
fn nested(&mut self, ui: &mut Ui) {
let answer = self.autocorrect.as_mut().and_then(|form| form.show(ui, &mut self.actions));
if let Some(answer) = answer {
if let Some(flags) = answer {
self.draft.set_flags(flags);
}
self.autocorrect = None;
}
}
fn nested_open(&self) -> bool {
self.autocorrect.is_some()
}
}
impl PreferencesDraft for PreferencesDialog {
fn differs(&self) -> bool {
self.draft != self.saved
}
fn apply(&mut self) -> Result<(), String> {
self.applied = Some(self.draft.clone());
self.saved = self.draft.clone();
Ok(())
}
fn cancel(&mut self) {
self.draft = self.saved.clone();
self.scale_shown = self.draft.ui_scale;
}
}
impl StackDialog for PreferencesDialog {
type Result = Option<PrefDraft>;
fn id(&self) -> DialogId {
dialog_id("preferences")
}
fn key(&self) -> Option<&str> {
Some("preferences")
}
fn show(&mut self, ui: &mut Ui, _stack: &DialogStack) -> Option<DialogResult<Self::Result>> {
let mut state = std::mem::take(&mut self.state);
let output = PreferencesWindow::new(Bind::bound(&mut state))
.embedded()
.layout(PreferencesLayout::Cards)
.mode(PreferencesMode::LiveCancel)
.show(ui, self);
self.state = state;
match output.closed {
Some(Closed::Ok) => Some(DialogResult::Ok(Some(self.draft.clone()))),
Some(Closed::Cancel) => Some(DialogResult::Cancel),
_ => None,
}
}
fn confirm(&mut self, _ctx: &Context) -> Option<Self::Result> {
(!self.nested_open()).then(|| Some(self.draft.clone()))
}
fn take_actions(&mut self) -> Vec<Value> {
std::mem::take(&mut self.actions)
}
fn json_fields(&self) -> Option<Value> {
let mut draft = self.draft.clone();
if let Some(form) = &self.autocorrect {
draft.set_flags(form.flags);
}
let mut fields = serde_fields(&draft)?;
if let Some(form) = &self.autocorrect {
fields["from"] = json!(form.from);
fields["to"] = json!(form.to);
}
Some(fields)
}
fn set_json_field(&mut self, _ctx: &Context, field: &str, value: Value) -> Result<(), String> {
if let Some(form) = &mut self.autocorrect {
if let Some(index) = FLAG_FIELDS.iter().position(|(key, _)| *key == field) {
form.flags[index] = value.as_bool().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?;
return Ok(());
}
let text = match field {
"from" => Some(&mut form.from),
"to" => Some(&mut form.to),
_ => None,
};
if let Some(text) = text {
*text = value.as_str().ok_or_else(|| FieldRefusal::Rejects(&value).message(field))?.to_owned();
return Ok(());
}
}
set_serde_field(&mut self.draft, field, value)?;
if field == "uiScale" {
self.scale_shown = self.draft.ui_scale;
}
Ok(())
}
}
/// Opens Preferences, retaining an already-open transaction.
pub(crate) fn open(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost, _params: &Value) -> Result<Option<DialogId>, String> {
pump(app, ctx, host);
if host.get_mut::<PreferencesDialog>().is_none() {
let draft = of(app);
app.dialogs.preferences_opening = Some(draft.clone());
host.open(PreferencesDialog {
state: PreferencesState::default(),
saved: draft.clone(),
applied: None,
scale_shown: draft.ui_scale,
draft,
autocorrect: None,
actions: Vec::new(),
});
}
Ok(Some(dialog_id("preferences")))
}
/// Opens AutoCorrect over the current Preferences draft, creating its parent when needed.
pub(crate) fn open_autocorrect(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost, params: &Value) -> Result<Option<DialogId>, String> {
let id = open(app, ctx, host, params)?;
if let Some(dialog) = host.get_mut::<PreferencesDialog>()
&& dialog.autocorrect.is_none()
{
dialog.autocorrect = Some(AutoCorrectForm::new(&dialog.draft, &mut dialog.actions));
}
pump(app, ctx, host);
Ok(id)
}
/// Applies live settings and restores opening values for every external or window Cancel path.
pub(crate) fn pump(app: &mut SlideApp, _ctx: &Context, host: &mut DialogHost) {
for action in host.take_actions(dialog_id("preferences")) {
match app.run("text.autocorrect", action) {
Ok(reply) => {
if let Some(form) = host.get_mut::<PreferencesDialog>().and_then(|dialog| dialog.autocorrect.as_mut()) {
form.entries = reply.get("entries").cloned().and_then(|entries| serde_json::from_value(entries).ok()).unwrap_or_default();
}
}
Err(error) => app.set_status(error),
}
}
let applied = host.get_mut::<PreferencesDialog>().and_then(|dialog| dialog.applied.take());
if let Some(draft) = applied {
write(app, &draft);
}
if let Some(result) = host.take_by_id::<PreferencesDialog>(dialog_id("preferences")) {
match result {
DialogResult::Ok(draft) => {
if let Some(draft) = draft {
write(app, &draft);
}
app.dialogs.preferences_opening = None;
}
DialogResult::Cancel => {
if let Some(opening) = app.dialogs.preferences_opening.take() {
write(app, &opening);
}
}
_ => {}
}
}
}
+112 -105
View File
@@ -1,12 +1,13 @@
//! The Preferences (Options) dialog: controls apply as they change and Cancel, Esc and the
//! window's close button put the settings back the way they were (#752, reported as #878).
//! Preferences applies live and restores its opening settings through both Cancel paths.
use deckcraft_engine::Session;
use egui_kittest::kittest::Queryable;
use egui_kittest::{Harness, Node};
use serde_json::json;
use serde_json::{Value, json};
use crate::theme::Brightness;
use crate::control::{ControlRequest, Outcome, handle};
use crate::state::Brightness;
use crate::test_harness::harness;
use crate::{Services, SlideApp};
/// The slider itself, not the label drawn beside it.
@@ -17,22 +18,8 @@ fn interface_size<'a>(h: &'a Harness<'_, SlideApp>) -> Node<'a> {
slider
}
fn harness() -> Harness<'static, SlideApp> {
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state(
|ui, app: &mut SlideApp| {
app.logic(ui.ctx());
app.ui(ui);
},
// P3(dialogs-w17): sh.A2
SlideApp::new_base(Session::with_new(), Services::default()),
);
// The app keeps asking for frames, so step instead of run().
h.run_steps(3);
h
}
fn open_options(h: &mut Harness<'_, SlideApp>) {
h.state_mut().run("app.preferences", json!({})).expect("open Options");
h.state_mut().open_dialog("preferences", json!({}));
h.run_steps(3);
}
@@ -40,108 +27,128 @@ fn dark(app: &SlideApp) -> bool {
app.ui.brightness == Brightness::Dark
}
/// The interface size slider has a visible label, not just a bare "1.00" beside it.
#[test]
fn the_interface_size_slider_is_labelled_on_screen() {
let mut h = harness();
open_options(&mut h);
let label = h.query_by_label("Interface size:").expect("the slider's label is shown");
let slider = interface_size(&h);
let (label, slider) = (label.rect(), slider.rect());
assert!(label.max.x <= slider.min.x, "the label sits before the slider: {label:?}, {slider:?}");
assert!(label.center().y > slider.min.y && label.center().y < slider.max.y, "on the same row: {label:?}, {slider:?}");
fn request(h: &mut Harness<'_, SlideApp>, method: &str, params: Value) {
let (request, _reply) = ControlRequest::new(method, params);
let ctx = h.ctx.clone();
let Outcome::Done(answer) = handle(h.state_mut(), &ctx, &request) else { panic!("{method} must reply") };
assert_eq!(answer["ok"], true, "{method}: {answer}");
}
/// A checkbox applies as it is toggled and Cancel puts the old value back.
#[test]
fn options_cancel_undoes_the_changes() {
let mut h = harness();
let was = h.state().session.prefs.smart_guides;
open_options(&mut h);
h.query_by_label("Show smart guides").expect("the checkbox is there").click();
h.run_steps(2);
assert_eq!(h.state().session.prefs.smart_guides, !was, "the change applies as it is made");
h.query_by_label("Cancel").expect("the Cancel button is there").click();
h.run_steps(2);
assert_eq!(h.state().session.prefs.smart_guides, was, "Cancel restores the setting");
assert!(h.state().dialog.is_none(), "and the dialog closes");
fn set(h: &mut Harness<'_, SlideApp>, field: &str, value: Value) {
request(h, "ui.dialog.set", json!({ "dialog": "top", "field": field, "value": value }));
h.run_steps(1);
}
/// Every Editing setting and the name field go back on Cancel, not only the first checkbox: a
/// reporter who changed a different control and saw Cancel do nothing has the same answer.
/// Omitting any editing setting from the live writer or the opening snapshot loses either its preview or its rollback.
#[test]
fn options_cancel_undoes_every_editing_setting() {
let mut h = harness();
let before = h.state().session.prefs.clone();
open_options(&mut h);
for label in ["Snap objects to grid", "Replace straight quotes with smart quotes", "AutoCorrect as you type"] {
h.query_by_label(label).unwrap_or_else(|| panic!("the {label} checkbox is there")).click();
h.run_steps(1);
let mut h = harness(Session::with_new(), Services::default());
let before = serde_json::to_value(&h.state().session.prefs).expect("preferences serialize");
let mut edited = before.clone();
for key in [
"smartGuides",
"snapToGrid",
"smartQuotes",
"autocorrect",
"acTwoInitials",
"acSentenceCaps",
"acDays",
"acCapsLock",
"acFractions",
"acOrdinals",
"acLists",
] {
edited[key] = json!(!before[key].as_bool().expect("a boolean preference"));
}
// The name field: it writes into the settings as it is typed.
// The name field is the last text input of the dialog (the label is a separate widget).
let name = h.get_all_by_role(egui::accesskit::Role::TextInput).last().expect("the name field is there");
name.click();
h.run_steps(1);
h.event(egui::Event::Text("Z".into()));
h.run_steps(1);
let changed = h.state().session.prefs.clone();
assert_ne!(
(changed.snap_to_grid, changed.smart_quotes, changed.autocorrect),
(before.snap_to_grid, before.smart_quotes, before.autocorrect),
"the settings apply as they are changed"
);
assert_ne!(changed.author, before.author, "the name applies as it is typed: {:?}", changed.author);
edited["author"] = json!(format!("{} Z", h.state().session.prefs.author));
edited["units"] = json!(match h.state().session.prefs.units {
deckcraft_geom::Unit::Centimeters => deckcraft_geom::Unit::Inches,
_ => deckcraft_geom::Unit::Centimeters,
});
let changes: Vec<_> = edited.as_object().expect("preferences are an object").iter().filter(|(key, value)| before[*key] != **value).collect();
h.query_by_label("Cancel").expect("the Cancel button is there").click();
h.run_steps(2);
let after = h.state().session.prefs.clone();
assert_eq!(after.snap_to_grid, before.snap_to_grid, "snap to grid is restored");
assert_eq!(after.smart_quotes, before.smart_quotes, "smart quotes are restored");
assert_eq!(after.autocorrect, before.autocorrect, "autocorrect is restored");
assert_eq!(after.author, before.author, "the name is restored");
for closing in ["ui.dialog.cancel", "ui.dialog.confirm"] {
open_options(&mut h);
for (key, value) in &changes {
set(&mut h, key, (*value).clone());
let applied = serde_json::to_value(&h.state().session.prefs).expect("preferences serialize");
assert_eq!(&applied[*key], *value, "{key} applies before the dialog closes");
}
assert_eq!(serde_json::to_value(&h.state().session.prefs).unwrap(), edited, "all editing values applied");
request(&mut h, closing, json!({ "dialog": "top" }));
h.run_steps(1);
let expected = if closing == "ui.dialog.cancel" { &before } else { &edited };
assert_eq!(&serde_json::to_value(&h.state().session.prefs).unwrap(), expected, "{closing} settles the transaction");
assert!(!super::open_keys(&h.ctx).iter().any(|key| key == "preferences"), "the dialog closes");
}
}
/// The appearance toggle and the interface size go back on Cancel, too; Esc acts as Cancel.
/// Appearance and scale belong to the same transaction even though they live outside engine preferences.
#[test]
fn options_cancel_puts_the_appearance_and_scale_back() {
let mut h = harness();
let mut h = harness(Session::with_new(), Services::default());
h.ctx.on_end_pass(
"preferences input across two passes",
std::sync::Arc::new(|ui: &mut egui::Ui| {
if ui.ctx().output(|output| output.num_completed_passes) == 0 {
ui.ctx().request_discard("preferences input across two passes");
}
}),
);
let (dark_before, scale_before) = (dark(h.state()), h.state().ui.ui_scale);
open_options(&mut h);
let scale_edited = if scale_before < 1.5 { scale_before + 0.25 } else { scale_before - 0.25 };
let scale_committed = scale_edited - 0.1;
h.query_by_label("Dark appearance").expect("the checkbox is there").click();
h.run_steps(2);
assert!(dark(h.state()), "the appearance applies as it is toggled");
for confirm in [false, true] {
open_options(&mut h);
let _ = interface_size(&h);
set(&mut h, "dark", json!(!dark_before));
assert_ne!(dark(h.state()), dark_before, "appearance applies with the dialog open");
set(&mut h, "uiScale", json!(scale_edited));
assert!((h.state().ui.ui_scale - scale_edited).abs() < f32::EPSILON, "scale applies with the dialog open");
assert_ne!(h.state().ui.ui_scale, scale_before);
interface_size(&h).set_value_accesskit(f64::from(scale_committed));
h.run_steps(1);
assert!((h.state().ui.ui_scale - scale_committed).abs() < f32::EPSILON, "the slider's Set commits across a second pass");
// Clicking the slider's middle sets it near the middle of its range, away from the default.
interface_size(&h).click();
h.run_steps(2);
let scale_in_dialog = h.state().ui.ui_scale;
assert!((scale_in_dialog - scale_before).abs() > 1e-3, "the slider applied a new size");
h.key_press(egui::Key::Escape);
h.run_steps(2);
assert_eq!(dark(h.state()), dark_before, "Esc restores the appearance");
assert!((h.state().ui.ui_scale - scale_before).abs() < 1e-3, "Esc restores the size");
assert!(h.state().dialog.is_none(), "and the dialog closes");
if confirm {
request(&mut h, "ui.dialog.confirm", json!({ "dialog": "top" }));
} else {
h.key_press(egui::Key::Escape);
}
h.run_steps(2);
let expected_dark = if confirm { !dark_before } else { dark_before };
let expected_scale = if confirm { scale_committed } else { scale_before };
assert_eq!(dark(h.state()), expected_dark, "the closing path settles appearance");
assert!((h.state().ui.ui_scale - expected_scale).abs() < f32::EPSILON, "the closing path settles scale");
assert!(!super::open_keys(&h.ctx).iter().any(|key| key == "preferences"), "the dialog closes");
}
}
/// The window's close button is the same as Cancel: the settings go back.
/// Replacement-list edits apply independently of the nested flags and the parent's cancelled settings.
#[test]
fn options_close_button_restores_the_settings() {
let mut h = harness();
let was = h.state().session.prefs.smart_guides;
open_options(&mut h);
h.query_by_label("Show smart guides").expect("the checkbox is there").click();
h.run_steps(2);
assert_eq!(h.state().session.prefs.smart_guides, !was, "the change applies as it is made");
h.get_all_by_label("Close window").next().expect("the window's close button is there").click();
h.run_steps(2);
assert_eq!(h.state().session.prefs.smart_guides, was, "the close button restores the setting");
assert!(h.state().dialog.is_none(), "and the dialog closes");
fn autocorrect_list_edits_survive_nested_and_preferences_cancel() {
let mut h = harness(Session::with_new(), Services::default());
let (from, to) = ("zzw17entry", "replacement");
for remove in [false, true] {
open_options(&mut h);
h.state_mut().open_dialog("autocorrect", json!({}));
h.run_steps(3);
set(&mut h, "from", json!(from));
set(&mut h, "to", json!(to));
h.get_by_role_and_label(egui::accesskit::Role::Button, "Add").click_accesskit();
h.run_steps(2);
assert!(h.state().session.prefs.ac_entries.iter().any(|(key, value)| key == from && value == to), "Add reaches the engine");
if remove {
set(&mut h, "from", json!(from));
h.get_by_role_and_label(egui::accesskit::Role::Button, "Delete").click_accesskit();
h.run_steps(2);
assert!(!h.state().session.prefs.ac_entries.iter().any(|(key, _)| key == from), "Delete reaches the engine");
}
h.key_press(egui::Key::Escape);
h.run_steps(2);
request(&mut h, "ui.dialog.cancel", json!({ "dialog": "top" }));
h.run_steps(2);
assert_eq!(h.state().session.prefs.ac_entries.iter().any(|(key, _)| key == from), !remove, "neither Cancel undoes list edits");
}
}