Merge branch 'pdf-port/fwb-c' into pdf-port/followups

This commit is contained in:
Dylan M. Taylor
2026-11-19 11:07:38 -05:00
14 changed files with 349 additions and 46 deletions
+4 -1
View File
@@ -168,8 +168,11 @@ impl RecoveryStore {
adopted.get(&id).cloned().unwrap_or_else(|| format!("doc-{}-{id}", self.session))
}
/// Writes a copy of document `id`; call from a job.
/// Writes a copy of document `id`; call from a job. Makes the folder again if it was removed
/// since the store opened.
// pdfcraft: crates/ui-egui/src/persist/recovery.rs:215 (create_dir before the write)
pub fn write(&self, id: u64, meta: &RecoveryMeta, bytes: &[u8]) -> std::io::Result<()> {
create_private_dir(&self.dir)?;
let key = self.key(id);
let mut meta = meta.clone();
meta.extension = sanitize_extension(&meta.extension);
+21 -5
View File
@@ -82,12 +82,15 @@ pub struct Autosave {
saved: HashMap<u64, u64>,
in_flight: HashMap<u64, u64>,
due_now: bool,
/// A document has changes no autosave holds or is writing: a dirty revision neither autosaved
/// nor in flight, or one whose autosave failed.
pending: bool,
}
impl Autosave {
/// `None` turns autosave off (PhotoCraft's `fileHandling.autosave = false`).
pub fn new(interval: Option<Duration>) -> Self {
Self { interval, next: None, saved: HashMap::new(), in_flight: HashMap::new(), due_now: false }
Self { interval, next: None, saved: HashMap::new(), in_flight: HashMap::new(), due_now: false, pending: false }
}
/// A changed preference; the next deadline moves to now plus the new interval.
@@ -131,6 +134,7 @@ impl Autosave {
self.in_flight.remove(id);
}
let mut due = AutosaveDue { save: Vec::new(), discard };
self.pending = docs.iter().any(|d| self.needs_save(d));
let Some(interval) = self.interval else {
self.next = None;
return due;
@@ -146,14 +150,20 @@ impl Autosave {
}
self.next = Some(now + interval);
for d in docs {
if d.dirty && self.saved.get(&d.id) != Some(&d.revision) && !self.in_flight.contains_key(&d.id) {
if self.needs_save(&d) {
self.in_flight.insert(d.id, d.revision);
due.save.push(d.id);
}
}
self.pending = false;
due
}
/// Whether `doc` has a revision to autosave that no autosave holds or is writing.
fn needs_save(&self, doc: &AutosaveDoc) -> bool {
doc.dirty && self.saved.get(&doc.id) != Some(&doc.revision) && !self.in_flight.contains_key(&doc.id)
}
/// An autosave ended. On success `revision` is remembered; on failure the status text
/// ([`AUTOSAVE_FAILED`] filled in) comes back for the status bar.
pub fn finished(&mut self, id: u64, revision: u64, result: Result<(), String>) -> Option<String> {
@@ -168,7 +178,10 @@ impl Autosave {
self.saved.insert(id, revision);
None
}
Err(error) => Some(AUTOSAVE_FAILED.replace("{error}", &error)),
Err(error) => {
self.pending = true;
Some(AUTOSAVE_FAILED.replace("{error}", &error))
}
}
}
@@ -179,8 +192,11 @@ impl Autosave {
self.in_flight.remove(&id);
}
/// When the next interval ends, for `request_repaint_after`.
/// When the next interval ends, for `request_repaint_after`; `None` while nothing is left to
/// autosave (as of the last [`due`](Self::due), or a failed [`finished`](Self::finished)), so
/// an idle window can sleep. The clock keeps running: an edit wakes the window, and its `due`
/// call brings the deadline back.
pub fn deadline(&self) -> Option<Instant> {
self.next
self.next.filter(|_| self.pending)
}
}
+34
View File
@@ -78,6 +78,40 @@ fn due_picks_dirty_changed_documents_each_interval() {
assert_eq!(timer.deadline(), None);
}
// The deadline wakes the window only while something waits to be autosaved: none when every
// document is clean, autosaved or being written; back on an edit or a failed write.
#[test]
fn the_deadline_is_none_while_nothing_waits_to_be_autosaved() {
let minute = Duration::from_secs(60);
let t0 = Instant::now();
let mut timer = Autosave::new(Some(minute));
timer.due(t0, [doc(1, 1, false)]);
assert_eq!(timer.deadline(), None, "a clean document has nothing to save");
timer.due(t0 + minute / 2, [doc(1, 2, true)]);
assert!(timer.deadline().is_some(), "an edit brings the deadline back");
assert_eq!(timer.due(t0 + minute, [doc(1, 2, true)]).save, vec![1]);
assert_eq!(timer.deadline(), None, "the revision is being written");
assert_eq!(timer.finished(1, 2, Ok(())), None);
timer.due(t0 + minute * 2, [doc(1, 2, true)]);
assert_eq!(timer.deadline(), None, "the revision is autosaved");
timer.due(t0 + minute * 5 / 2, [doc(1, 3, true)]);
assert!(timer.deadline().is_some());
assert_eq!(timer.due(t0 + minute * 3, [doc(1, 3, true)]).save, vec![1]);
assert!(timer.finished(1, 3, Err("disk full".into())).is_some());
assert!(timer.deadline().is_some(), "a failed revision is tried again");
}
// An autosave after the recovery folder was removed (a cleaner, the user) makes it again.
#[test]
fn a_write_after_the_folder_was_removed_makes_it_again() {
let scratch = Scratch::new();
let dir = scratch.0.join("Recovery");
let store = RecoveryStore::open(&dir).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
store.write(1, &meta("a.psd", 1), b"work").unwrap();
assert_eq!(std::fs::read(dir.join(format!("{}.pcraft", store.key(1)))).unwrap(), b"work");
}
// A copy written by a run that is gone is a leftover; one of a live instance (its lock held) is
// not; discard removes copy and sidecar.
#[test]
+15 -4
View File
@@ -16,7 +16,7 @@ use craft_ui::layout::RowAlign;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::patterns::form_dialogs::{
DialogFields, FieldValue, FormDialog, HostRequests, PagerStep, PanePager, Param, ParamRows, set_color_field, set_param_field,
DialogFields, FieldValue, FormDialog, HostRequests, PagerStep, PanePager, Param, ParamKind, ParamRows, set_color_field,
};
use craft_ui::primitives::{ContentPainterCx, TextRun, Wrap, fill_polygon};
use craft_ui::runtime::env::{Env, Label};
@@ -1231,7 +1231,9 @@ impl StackDialog for HostedPrint {
}
/// The `Settings` keys (`printer`, `copies`, `duplex`, `grayscale`, `collate`) and each section parameter's value as
/// [`DialogFields`] serializes it. `printer` is the printer's name, or `null` for Save as PDF.
/// [`DialogFields`] serializes it. `printer` is the printer's name, or `null` for Save as PDF. With a preview pager,
/// `sheet` is the sheet it shows (from 1) and `sheets` how many there are. `notes` lists the keys of the sections'
/// read-only text rows ([`Param::read_only_text`]) the values show, in order: what the dialog tells the user.
fn json_fields(&self) -> Option<serde_json::Value> {
let mut map = match serde_json::to_value(&self.fields).ok()? {
serde_json::Value::Object(map) => map,
@@ -1247,6 +1249,13 @@ impl StackDialog for HostedPrint {
map.insert("duplex".to_owned(), duplex_json(settings.duplex));
map.insert("grayscale".to_owned(), settings.grayscale.into());
map.insert("collate".to_owned(), settings.collate.into());
if let Some(pager) = &self.preview_pager {
map.insert("sheet".to_owned(), pager.shown.into());
map.insert("sheets".to_owned(), pager.count.into());
}
let notes = self.sections.iter().flat_map(|section| &section.params);
let notes = notes.filter(|param| matches!(param.kind, ParamKind::ReadOnlyText { .. }) && param.visible(&self.fields));
map.insert("notes".to_owned(), notes.map(|param| serde_json::Value::from(param.key.clone())).collect());
if let Some(form) = &self.json_form {
form(&self.fields, &mut map);
}
@@ -1255,7 +1264,9 @@ impl StackDialog for HostedPrint {
/// Sets a `Settings` key, or a section parameter through the shared parameter-field rule. `printer` takes a listed
/// printer's name, or `null` for Save as PDF where the layout offers it; the write is a choice the app takes with
/// [`take_printer_chosen`](HostedPrint::take_printer_chosen).
/// [`take_printer_chosen`](HostedPrint::take_printer_chosen). A section parameter's set is recorded as an edit of its
/// row, as the user's is ([`HostRequests::set_field`]): the app reads it with `take_edited` in its next pass, so
/// the app's own value does not overwrite it.
fn set_json_field(&mut self, _: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> {
match field {
"printer" => {
@@ -1281,7 +1292,7 @@ impl StackDialog for HostedPrint {
let section =
self.sections.iter().find(|section| section.params.iter().any(|param| param.key == field || param.unit_key() == Some(field)));
let section = section.ok_or_else(|| FieldRefusal::Unknown.message(field))?;
return set_param_field(&section.params, &mut self.fields, field, value);
return self.requests.set_field(&section.params, &mut self.fields, field, value);
}
}
Ok(())
+35 -2
View File
@@ -6,11 +6,12 @@ use std::sync::mpsc::channel;
use craft_behavior::EditEvent;
use craft_print::ui::{
Destination, DriverControls, HostedPrint, PrintDialog, PrintFinish, PrintLayout, PrintSheet, Printer, Settings, SheetPage, State,
Destination, DriverControls, HostedPrint, PrintDialog, PrintFinish, PrintLayout, PrintSection, PrintSheet, Printer, Settings, SheetPage,
State,
};
use craft_ui::contract::Bind;
use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, StackDialog as _, dialog_id};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, PanePager, Param};
use craft_ui::primitives::TextureCache;
use craft_ui::runtime::env::{Label, Scale};
use craft_ui::testing::{Fixture, trial};
@@ -129,6 +130,38 @@ fn the_json_form_adds_to_the_listing() {
assert!(listed.get("copies").is_some(), "the settings keys stay");
}
/// The listing carries the preview pager's sheet and count, and the keys of the note rows the values show: a note
/// whose row is hidden is not listed.
#[trial]
fn the_listing_carries_the_pager_and_the_shown_notes() {
let notes = vec![
Param::read_only_text("note.shown", Label::default(), "Printed as asked."),
Param::read_only_text("note.hidden", Label::default(), "Two-sided is off.").visible_when("two_sided", FieldValue::Bool(true)),
Param::parse_list(r#"{"range":1..9=1}"#).remove(0),
];
let mut dialog = HostedPrint::new(State::default(), DialogFields::default(), vec![PrintSection::new("Paper", notes)]);
dialog.set_preview_pager(Some(PanePager { shown: 2, count: 3, ..PanePager::default() }));
let listed = dialog.json_fields().expect("a listing");
assert_eq!((listed["sheet"].as_u64(), listed["sheets"].as_u64()), (Some(2), Some(3)));
assert_eq!(listed["notes"], serde_json::json!(["note.shown"]), "only the shown note rows, and no other row");
dialog.fields_mut().set("two_sided", FieldValue::Bool(true));
assert_eq!(dialog.json_fields().expect("a listing")["notes"], serde_json::json!(["note.shown", "note.hidden"]));
}
/// A section value set through automation is recorded as an edit of its row, as the user's edit is, so the app's pass
/// that writes its own values back leaves it; a settings key is no row.
#[trial]
fn a_section_value_set_through_automation_is_an_edit() {
let rows = PrintSection::new("Pages", Param::parse_list(r#"{"range":1..9=1}"#));
let mut dialog = HostedPrint::new(State::default(), DialogFields::default(), vec![rows]);
let ctx = egui::Context::default();
dialog.set_json_field(&ctx, "range", serde_json::json!(4)).expect("the range row takes a number");
dialog.set_json_field(&ctx, "copies", serde_json::json!(2)).expect("copies takes a count");
assert_eq!(dialog.requests_mut().take_edited(), ["range"]);
assert_eq!(dialog.fields_mut().number("range"), Some(4.0));
}
/// A held print dialog over the printer "Office", in a `DialogHost` run every pass. While `twice` is on, egui runs each
/// frame twice and gives the frame's input to its first pass only.
fn held_print(twice: &Rc<Cell<bool>>) -> (Fixture, Rc<RefCell<DialogHost>>) {
+1 -1
View File
@@ -38,7 +38,7 @@ match store.update(&base, SelectionChange::pick_theme(&picked)) {
| `ThemeRecord`, `ThemeEntry`, `format` | a parsed user theme file (`craft-design-theme` v1, craft-theme's `format`) with its stored bytes, unknown keys included; the library skips files in another format, such as the pilot's `craft-theme` |
| `SuiteClient` | what an app calls: per-frame `sync`, the optimistic `shown` choice, `change`, conflict and failure notices with `apply_mine` and `retry`, the `theme` lookup, `preview` for any theme's picker card |
| `SuiteWatch`, `Snapshot`, `Op`, `OpOutput` | the store on a worker thread: snapshots by generation, queued operations with results |
| `ui` (feature `ui`) | the Preferences appearance page `AppearancePage` (modes, light and dark theme rows of `ThemeChip`s with favorites, Size and UI Font Size; tokens `theme_chip.*`); feature `screen-testing` adds egui_kittest input tests of the page |
| `ui` (feature `ui`) | the Preferences appearance page `AppearancePage` (modes, light and dark theme rows of `ThemeChip`s with favorites, Size, UI Font Size, Contrast and Motion, where an app leaves out favorites and the rows it does not keep; tokens `theme_chip.*`); feature `screen-testing` adds egui_kittest input tests of the page |
| `FileStamp`, `library_files`, `selection_stamp`, `theme_stamp`, `parse_counts` | cheap change checks for a watcher |
`Store` methods block on file I/O and on the lock (up to 2 s). Apps use `SuiteClient` over a
+7 -2
View File
@@ -115,6 +115,10 @@ pub struct ThemeChip<'a> {
/// Whether the chip shows the favourite star.
#[prop]
favorite: bool,
/// Whether the chip offers the favourite star (default on). Off, for an app that keeps no favourites, the chip has
/// no badge and says nothing of favourites.
#[prop]
can_favorite: bool,
checked: bool,
sampled: [Color32; 3],
star: Option<Rect>,
@@ -129,6 +133,7 @@ impl<'a> ThemeChip<'a> {
theme,
dark,
favorite: false,
can_favorite: true,
checked: false,
sampled: [Color32::TRANSPARENT; 3],
star: None,
@@ -178,7 +183,7 @@ impl Component for ThemeChip<'_> {
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
self.star = None;
if !(self.favorite || cx.hovered()) {
if !self.can_favorite || !(self.favorite || cx.hovered()) {
return;
}
// The badge sits in the chip's top end corner, inside its rect: overhanging it would reach into the next chip.
@@ -213,7 +218,7 @@ impl Component for ThemeChip<'_> {
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let words = cx.words::<AppearanceWords>();
if self.favorite {
if self.favorite && self.can_favorite {
access.value(words.favorite.as_str());
}
if self.star.is_some() {
+37 -15
View File
@@ -73,7 +73,9 @@ impl Outcome for AppearancePageOutput {
/// Rows, top to bottom, with the labels at the start: Appearance Mode (Sync with system, Dark, Light), Light Theme and
/// Dark Theme (a row of [`ThemeChip`]s each: the built-in themes, then the library's, each in the rows for the modes it
/// has; "Active" after the chips of the row for the mode the app shows now), Size (Compact, Comfortable), UI Font Size
/// (the [`TextSize`] steps), Contrast and Motion (Sync with system, Standard or Full, High or Reduced).
/// (the [`TextSize`] steps), Contrast and Motion (Sync with system, Standard or Full, High or Reduced). An app that keeps
/// its own appearance shows only what it keeps: the `size`, `text_size` and `contrast` props leave those rows out, and
/// `can_favorite` the favourite stars and their menu.
///
/// The page edits the bound draft, a [`SelectionChange`] the Preferences model keeps; the chips and lists show
/// [`SuiteClient::shown`] (through the [`SuiteView`]) with the draft applied. Nothing reaches the suite until the window applies: the model's
@@ -88,9 +90,19 @@ pub struct AppearancePage<'a> {
/// The themes marked with a filled star.
#[prop]
favorites: &'a [ThemeId],
/// Offers favourites (default on): the chips' stars and their Add to Favorites / Remove from Favorites menu. An app
/// that keeps no favourites turns it off; the page then reports no `favorite_toggled`.
#[prop]
can_favorite: bool,
/// Shows the Size row (default on); an app that keeps no size of its own turns it off.
#[prop]
size: bool,
/// Shows the UI Font Size row (default on); an app with its own text-size control turns it off.
#[prop]
text_size: bool,
/// Shows the Contrast row (default on); an app that keeps no contrast choice turns it off.
#[prop]
contrast: bool,
/// The system shows its dark mode: which row is active when the mode follows the system.
#[prop]
system_dark: bool,
@@ -99,12 +111,12 @@ pub struct AppearancePage<'a> {
impl<'a> AppearancePage<'a> {
/// The page over the suite `suite` (from [`SuiteClient::view`]), editing `draft`.
pub fn new(suite: &'a SuiteView, draft: Bind<'a, SelectionChange>) -> Self {
AppearancePage { suite, draft, favorites: &[], text_size: true, system_dark: false }
AppearancePage { suite, draft, favorites: &[], can_favorite: true, size: true, text_size: true, contrast: true, system_dark: false }
}
/// Shows the page.
pub fn show(self, ui: &mut Ui) -> AppearancePageOutput {
let AppearancePage { suite, draft, favorites, text_size, system_dark } = self;
let AppearancePage { suite, draft, favorites, can_favorite, size, text_size, contrast, system_dark } = self;
let words = Env::of(ui).words::<AppearanceWords>();
let themes = themes(suite);
let mut held = Held::new(draft);
@@ -130,6 +142,7 @@ impl<'a> AppearancePage<'a> {
}
for dark in [false, true] {
let (title, chosen) = if dark { (&words.dark_theme, &shown.theme_dark) } else { (&words.light_theme, &shown.theme_light) };
let favorites = can_favorite.then_some(favorites);
let row = ChipRow { title, dark, active: dark == dark_active, chosen: chosen.as_ref(), themes: &themes, favorites, words: &words };
let (picked, flipped) = row.show(ui);
if let Some(id) = picked {
@@ -137,9 +150,11 @@ impl<'a> AppearancePage<'a> {
}
toggled = toggled.take().or(flipped);
}
let sizes = [Entry::new(Size::Compact, words.compact.clone()), Entry::new(Size::Comfortable, words.comfortable.clone())];
if let Some(size) = pick(ui, &words.size, "size", shown.size.unwrap_or_default(), &sizes) {
now.size = Some(size);
if size {
let sizes = [Entry::new(Size::Compact, words.compact.clone()), Entry::new(Size::Comfortable, words.comfortable.clone())];
if let Some(size) = pick(ui, &words.size, "size", shown.size.unwrap_or_default(), &sizes) {
now.size = Some(size);
}
}
if text_size {
let steps = [
@@ -152,13 +167,15 @@ impl<'a> AppearancePage<'a> {
now.text_size = Some(step);
}
}
let contrasts = [
Entry::new(ContrastChoice::System, words.contrast_system.clone()),
Entry::new(ContrastChoice::Standard, words.contrast_standard.clone()),
Entry::new(ContrastChoice::High, words.contrast_high.clone()),
];
if let Some(contrast) = pick(ui, &words.contrast, "contrast", shown.contrast.unwrap_or_default(), &contrasts) {
now.contrast = Some(contrast);
if contrast {
let contrasts = [
Entry::new(ContrastChoice::System, words.contrast_system.clone()),
Entry::new(ContrastChoice::Standard, words.contrast_standard.clone()),
Entry::new(ContrastChoice::High, words.contrast_high.clone()),
];
if let Some(contrast) = pick(ui, &words.contrast, "contrast", shown.contrast.unwrap_or_default(), &contrasts) {
now.contrast = Some(contrast);
}
}
let motions = [
Entry::new(MotionChoice::System, words.motion_system.clone()),
@@ -204,7 +221,8 @@ struct ChipRow<'a> {
active: bool,
chosen: Option<&'a ThemeId>,
themes: &'a [ThemeDef],
favorites: &'a [ThemeId],
/// The favourite themes; `None` offers no favourites.
favorites: Option<&'a [ThemeId]>,
words: &'a AppearanceWords,
}
@@ -220,7 +238,11 @@ impl ChipRow<'_> {
let group = RadioGroup::new(self.title.clone(), Bind::given(self.chosen.cloned())).id_salt("group").show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
for theme in self.themes.iter().filter(|theme| fits(theme)) {
let favorite = self.favorites.contains(&theme.id);
let Some(favorites) = self.favorites else {
ThemeChip::new(theme, self.dark).can_favorite(false).id_salt(theme.id.as_str()).show(ui);
continue;
};
let favorite = favorites.contains(&theme.id);
let chip = ThemeChip::new(theme, self.dark).favorite(favorite).id_salt(theme.id.as_str()).show(ui);
if chip.favorite_clicked {
flipped = Some(theme.id.clone());
+24
View File
@@ -27,6 +27,30 @@ fn appearance_page_without_text_size(ui: &mut Ui, data: &mut StoryData) -> Story
AppearancePage::new(&client, Bind::bound(data.value("plain", SelectionChange::default()))).text_size(false).system_dark(true).show(ui).into()
}
/// The page of an app that keeps its own appearance: the mode, the two theme rows without favourite stars, and Motion.
#[story(AppearancePage<'static>, covers = [], drive = Drive::Never)]
fn appearance_page_with_kept_rows_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let client = SuiteClient::memory().view();
let draft = Bind::bound(data.value("kept", SelectionChange::default()));
AppearancePage::new(&client, draft).can_favorite(false).size(false).text_size(false).contrast(false).show(ui).into()
}
/// Chips that offer no favourite star, for an app that keeps no favourites.
#[story(ThemeChip<'static>, covers = [], drive = Drive::Never)]
fn theme_chips_without_favorites(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let themes = builtins();
let chosen = data.value("chosen", Some(themes[1].id.clone()));
RadioGroup::new("Light Theme", Bind::bound(chosen))
.show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
for theme in themes.iter().take(4) {
ThemeChip::new(theme, false).can_favorite(false).id_salt(theme.id.as_str()).show(ui);
}
});
})
.into()
}
/// One theme's chips in a group: plain, chosen, favourite, and both. A click on a star toggles the chip's favourite.
#[story(ThemeChip<'static>, covers = [Default], drive = Drive::Never)]
fn theme_chips(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
+39
View File
@@ -1 +1,40 @@
//! The screen tests of craft-theme-store, folded into the lib's test target.
use craft_theme::builtins;
use craft_theme_store::ui::AppearancePage;
use craft_theme_store::{SelectionChange, SuiteClient};
use craft_ui::contract::Bind;
use craft_ui::testing::{Fixture, trial};
/// The page over a memory suite with the first built-in theme a favourite; `keep_only` leaves out favourites, Size and
/// Contrast, as an app with its own appearance setting does.
fn page(keep_only: bool) -> Fixture {
let favorites = vec![builtins()[0].id.clone()];
let mut draft = SelectionChange::default();
let mut fixture = Fixture::new(move |ui| {
let client = SuiteClient::memory().view();
let page = AppearancePage::new(&client, Bind::bound(&mut draft)).favorites(&favorites);
let page = if keep_only { page.can_favorite(false).size(false).contrast(false) } else { page };
page.show(ui);
});
fixture.settle();
fixture
}
// An app that keeps its own appearance shows only what it keeps: no Size or Contrast row and no favourite star, while
// the mode, theme and Motion rows stay; the full page has them all.
#[trial]
fn an_app_with_its_own_appearance_shows_only_the_rows_it_keeps() {
let star = format!("Remove from Favorites: {}", builtins()[0].name);
let full = page(false);
for label in ["Size", "Contrast", star.as_str()] {
assert!(full.by_label(label).is_some(), "the full page has {label}");
}
let kept = page(true);
for label in ["Size", "Contrast", star.as_str()] {
assert!(kept.by_label(label).is_none(), "the kept page leaves out {label}");
}
for label in ["Appearance Mode", "Light Theme", "Dark Theme", "Motion"] {
assert!(kept.by_label(label).is_some(), "the kept page keeps {label}");
}
}
@@ -7,7 +7,7 @@ use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, List
use super::form::{FormDialog, FormDialogWords};
use super::host_requests::HostRequests;
use super::param::{Param, ParamKind, edited_rows, open_fields, set_color_field};
use super::param::{Param, ParamKind, open_fields, set_color_field};
use super::preview::{PagerStep, PaneOverlay, PanePager, PreviewPane, PreviewState, PreviewView, PreviewZoom};
use super::rows::{ParamRows, ParamRowsOutput};
@@ -1082,7 +1082,9 @@ type Build = dyn for<'b> Fn(&'b mut DialogFields) -> ParamDialog<'b> + Send;
/// capture a picture that changes; [`is_previewing`](HostedParamDialog::is_previewing) and
/// [`is_comparing`](HostedParamDialog::is_comparing) say what to render.
/// - What the host's jobs find about the values comes the same way: the lines under the rows from
/// [`set_notes`](HostedParamDialog::set_notes), and whether OK can be pressed from
/// [`set_notes`](HostedParamDialog::set_notes), a row's label and whether it shows from
/// [`set_param_label`](HostedParamDialog::set_param_label) and [`set_param_shown`](HostedParamDialog::set_param_shown),
/// and whether OK can be pressed from
/// [`set_ready`](HostedParamDialog::set_ready). What the values alone decide stays in `build`.
/// - With [`held_ok`](HostedParamDialog::held_ok), OK files its answer for the host to check
/// ([`take_ok`](HostedParamDialog::take_ok)) and the dialog waits, OK disabled, for
@@ -1120,6 +1122,8 @@ pub struct HostedParamDialog {
tint: Option<DataColor>,
/// The lines under the rows the host last gave (`set_notes`).
notes: Vec<Label>,
/// The row labels and shown states the host last gave (`set_param_label`, `set_param_shown`).
rows: HostRows,
/// Whether the host lets OK be pressed, and why not (`set_ready`).
ready: Result<(), Label>,
/// The tab a tabbed dialog shows: bound to the dialog's `tab` prop, so the host sets it before a pass.
@@ -1142,6 +1146,44 @@ struct ShownState {
centre: Option<Pos2>,
}
/// What a [`HostedParamDialog`]'s host says about rows `build` makes, by row key: the label, and whether the row shows.
#[derive(Default)]
struct HostRows {
labels: Vec<(String, Label)>,
shown: Vec<(String, bool)>,
}
impl HostRows {
/// Puts `value` under `key`, replacing what `key` had.
fn put<T>(list: &mut Vec<(String, T)>, key: String, value: T) {
match list.iter_mut().find(|(k, _)| *k == key) {
Some((_, old)) => *old = value,
None => list.push((key, value)),
}
}
/// Gives the rows of `dialog`, shared and in every tab, the host's labels and shown states.
fn apply(&self, dialog: &mut ParamDialog<'_>) {
if self.labels.is_empty() && self.shown.is_empty() {
return;
}
let apply = |params: &mut [Param]| {
for param in params {
if let Some((_, label)) = self.labels.iter().find(|(key, _)| *key == param.key) {
param.label = label.clone();
}
if let Some((_, shown)) = self.shown.iter().find(|(key, _)| *key == param.key) {
param.shown = *shown;
}
}
};
apply(dialog.params.to_mut());
for tab in &mut dialog.tabs {
apply(&mut tab.params);
}
}
}
impl HostedParamDialog {
/// A hosted dialog for the command `key`, opening with `fields`; `build` makes the dialog over the values. The
/// values open now, as a `ParamDialog`'s first pass opens its own: the remembered values `ctx` keeps over
@@ -1174,6 +1216,7 @@ impl HostedParamDialog {
overlay: None,
tint: None,
notes: Vec::new(),
rows: HostRows::default(),
ready: Ok(()),
tab: 0,
shown: ShownState::default(),
@@ -1269,6 +1312,19 @@ impl HostedParamDialog {
self.notes = notes;
}
/// Sets the label of the row `key` from the next pass on, over the one `build` gives: when the words come from the
/// host's jobs (the pages a box applies to), which `build` cannot capture as they change.
pub fn set_param_label(&mut self, key: impl Into<String>, label: impl Into<Label>) {
HostRows::put(&mut self.rows.labels, key.into(), label.into());
}
/// Sets whether the row `key` shows from the next pass on, over `build`'s [`Param::shown`]: when the host's jobs
/// decide it (a box offered only when a check finds something). A hidden row takes no space and refuses a set
/// through automation, as one hidden by [`Param::visible_when`]; its value stays in the fields and the result.
pub fn set_param_shown(&mut self, key: impl Into<String>, shown: bool) {
HostRows::put(&mut self.rows.shown, key.into(), shown);
}
/// Sets whether the host lets OK be pressed from the next pass on: `Err` disables OK, Enter and `confirm`, with
/// the label as the disabled button's tooltip, whatever `build` allows; `Ok` leaves OK to `build`. A host whose
/// jobs decide OK (a check that runs over the document) sets it as their results come in.
@@ -1499,6 +1555,7 @@ impl StackDialog for HostedParamDialog {
// A measuring run keeps the centre: the real run of the pass takes it.
let centre = if measuring { self.centre } else { self.centre.take() };
let mut dialog = (self.build)(&mut self.fields);
self.rows.apply(&mut dialog);
self.previews = dialog.previews;
dialog = dialog
.preview_on(Bind::bound(&mut self.preview_on))
@@ -1621,20 +1678,16 @@ impl StackDialog for HostedParamDialog {
/// Keeps `value` when the row `field` names (a parameter or its unit choice) is shown, takes input, and takes
/// the value ([`set_param_field`]).
fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> {
let ParamDialog { params, tabs, read_only, .. } = (self.build)(&mut self.fields);
let (params, read_only) = {
let mut dialog = (self.build)(&mut self.fields);
self.rows.apply(&mut dialog);
let ParamDialog { params, tabs, read_only, .. } = dialog;
(every_param(params, &tabs).into_owned(), read_only)
};
if read_only {
return Err(FieldRefusal::Inactive.message(field));
}
let params = every_param(params, &tabs).into_owned();
let before = self.fields.clone();
set_param_field(&params, &mut self.fields, field, value)?;
for param in params.iter().filter(|param| matches!(param.kind, ParamKind::Files { .. })) {
if let Some(request) = param.listing_after(&before, &self.fields) {
self.requests.request_listing(request);
}
}
self.requests.request_edited(edited_rows(&params, &before, &self.fields));
Ok(())
self.requests.set_field(&params, &mut self.fields, field, value)
}
/// Shows a child picker's live colour in the colour row `key`, as [`HostedParamDialog::preview_color`] does.
@@ -1,10 +1,13 @@
//! `HostRequests`: what a hosted dialog's rows ask of the host, kept until the host takes it.
use super::fields::DialogFields;
use super::param::{Param, ParamKind, edited_rows};
use super::preview::PagerStep;
use super::rows::ParamRowsOutput;
use crate::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer, ListingRequest, PathRequest};
use craft_theme::Srgba;
use egui::Pos2;
use serde_json::Value;
use std::path::PathBuf;
/// A request to render a preview of `options`, numbered so the host's answer can be matched to the settings it was
@@ -172,6 +175,22 @@ impl HostRequests {
}
}
/// Sets `field` of `fields` to `value` through automation, by the shared parameter-field rule
/// ([`set_param_field`](super::set_param_field)) over `params`, and files what an edit in the row files: the rows
/// it changed as edited, and the listing of a files row's new folder. A hosted dialog's `set_json_field` goes
/// through here, so its host reads the set as the user's edit and does not write its own value over it.
pub fn set_field(&mut self, params: &[Param], fields: &mut DialogFields, field: &str, value: Value) -> Result<(), String> {
let before = fields.clone();
super::set_param_field(params, fields, field, value)?;
for param in params.iter().filter(|param| matches!(param.kind, ParamKind::Files { .. })) {
if let Some(request) = param.listing_after(&before, fields) {
self.request_listing(request);
}
}
self.request_edited(edited_rows(params, &before, fields));
Ok(())
}
/// The row keys an edit changed since the last take.
pub fn take_edited(&mut self) -> Vec<String> {
std::mem::take(&mut self.edited)
@@ -559,6 +559,10 @@ pub struct Param {
/// The row is shown only while every condition holds: `fields[key]` equals the value ([`Param::visible_when`]). A
/// hidden row takes no space; its value stays in the fields and in the result.
pub visible_when: Vec<(String, FieldValue)>,
/// Whether the row is shown at all, whatever the values ([`Param::shown`]): what decides it lies outside the
/// values, such as what a host's job found. A hidden row takes no space; its value stays in the fields and in the
/// result.
pub shown: bool,
/// A Browse button after a [`ParamKind::Text`] field.
pub browse: Option<PathKind>,
/// The hint and tooltip, boxed so rows without them stay small.
@@ -577,6 +581,7 @@ impl Param {
unit: None,
enable: Enable::Always,
visible_when: Vec::new(),
shown: true,
browse: None,
texts: None,
options: None,
@@ -822,6 +827,16 @@ impl Param {
self
}
/// Whether the row is shown at all; a hidden row takes no space, as one whose
/// [`visible_when`](Param::visible_when) fails. For what the values do not decide; a
/// [`HostedParamDialog`](super::HostedParamDialog) host sets it between passes with
/// [`set_param_shown`](super::HostedParamDialog::set_param_shown).
#[must_use]
pub fn shown(mut self, shown: bool) -> Self {
self.shown = shown;
self
}
/// The row takes input only while `fields[key]` equals `value`; otherwise it is shown disabled. The one-value case
/// of [`enabled_when_in`](Param::enabled_when_in).
#[must_use]
@@ -1017,7 +1032,7 @@ impl Param {
/// Whether the row is shown with `fields`.
pub fn visible(&self, fields: &DialogFields) -> bool {
self.visible_when.iter().all(|(key, value)| fields.get(key) == Some(value))
self.shown && self.visible_when.iter().all(|(key, value)| fields.get(key) == Some(value))
}
/// Whether the row takes input with `fields`.
@@ -1,6 +1,6 @@
//! `ParamDialog` and `HostedParamDialog`: the dialog's own undo history, the Preview box's hold-to-compare, Enter in
//! a multi-line row and on a focused Cancel, Alt+Reset to `reset_to`, the held OK, the host's notes and OK state,
//! reopening under the same key, the
//! a multi-line row and on a focused Cancel, Alt+Reset to `reset_to`, the held OK, the host's notes, OK state and row
//! labels and shown states, reopening under the same key, the
//! request slots and the rows an edit changed, disabled options and the remembered values a row refuses.
use craft_ui::buttons::Button;
@@ -288,6 +288,35 @@ fn notes_and_the_ok_state_the_host_sets_show_in_the_next_pass() {
assert!(!fixture.tree().is_disabled_key(ok.node), "`Ok` leaves OK to the build again");
}
/// A row label the host's job words.
const PAGES_3_TO_5: &str = "Smooth pages 3–5";
// A row label and a hidden row the host sets between passes show in the next pass, over what `build` gives: the row
// takes the host's words, and a hidden row is gone and refuses a set through automation until the host shows it.
#[trial]
fn a_row_label_and_shown_state_the_host_sets_show_in_the_next_pass() {
let (host, twice) = (Rc::new(RefCell::new(DialogHost::new())), Rc::new(Cell::new(false)));
let mut fixture = host_fixture(&host, &twice);
host.borrow_mut().open(HostedParamDialog::new(fixture.ctx(), "blur", DialogFields::new(), blur));
fixture.idle(4);
on_dialog(&host, |dialog| dialog.set_param_label("smooth", PAGES_3_TO_5));
fixture.idle(1);
assert!(fixture.by_label(PAGES_3_TO_5).is_some(), "the row shows the host's label");
assert!(fixture.by_label("Smooth").is_none(), "the build's label is replaced");
on_dialog(&host, |dialog| dialog.set_param_shown("smooth", false));
fixture.idle(1);
assert!(fixture.by_label(PAGES_3_TO_5).is_none(), "the hidden row is gone");
let ctx = fixture.ctx().clone();
assert!(host.borrow_mut().set_json_field(&ctx, dialog_id("blur"), "smooth", json!(true)).is_err(), "a hidden row refuses a set");
assert!(fixture.by_label("Radius").is_some(), "the other rows stay");
on_dialog(&host, |dialog| dialog.set_param_shown("smooth", true));
fixture.idle(1);
assert!(fixture.by_label(PAGES_3_TO_5).is_some(), "the row shows again");
assert_eq!(host.borrow_mut().set_json_field(&ctx, dialog_id("blur"), "smooth", json!(true)), Ok(()));
}
// A dialog the app opens again under the same key, in the pass it takes the first one's Cancel, shows and answers.
#[trial]
fn a_hosted_dialog_reopened_under_the_same_key_opens() {