mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 03:17:43 +00:00
files-w2: net change of 1 commits
- files-w2: written from its sheet
This commit is contained in:
@@ -8,8 +8,9 @@
|
||||
use craft_cms::ColorSpace;
|
||||
use craft_cms::profile::Profile;
|
||||
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, StackDialog, dialog_id};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::words::CommonWords;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
@@ -221,6 +222,8 @@ pub struct ProfileMismatchDialog {
|
||||
action: ProfileAction,
|
||||
rememberable: bool,
|
||||
remember: bool,
|
||||
profiles: Vec<String>,
|
||||
chosen: usize,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
@@ -239,6 +242,8 @@ impl ProfileMismatchDialog {
|
||||
action,
|
||||
rememberable: false,
|
||||
remember: false,
|
||||
profiles: Vec::new(),
|
||||
chosen: 0,
|
||||
open: true,
|
||||
}
|
||||
}
|
||||
@@ -253,9 +258,10 @@ impl ProfileMismatchDialog {
|
||||
/// The profiles the Assign profile `Select` lists under its radio row, a Missing Profile prompt only; it starts on
|
||||
/// the first name.
|
||||
#[must_use]
|
||||
pub fn profiles(self, names: Vec<String>) -> ProfileMismatchDialog {
|
||||
let _ = names;
|
||||
todo!("fl.F18")
|
||||
pub fn profiles(mut self, names: Vec<String>) -> ProfileMismatchDialog {
|
||||
self.profiles = names;
|
||||
self.chosen = 0;
|
||||
self
|
||||
}
|
||||
|
||||
/// Offers "Remember this choice"; only for a mismatch (ignored for a missing profile).
|
||||
@@ -265,14 +271,31 @@ impl ProfileMismatchDialog {
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether Assign profile is offered: a missing profile and a list of profiles to assign.
|
||||
fn offers_profile(&self) -> bool {
|
||||
!self.profiles.is_empty() && matches!(self.question, ProfileQuestion::Missing { .. })
|
||||
}
|
||||
|
||||
/// The actions the question offers, in radio order.
|
||||
fn offered(&self) -> &'static [ProfileAction] {
|
||||
fn offered(&self) -> Vec<ProfileAction> {
|
||||
match self.question {
|
||||
ProfileQuestion::Mismatch { .. } => &[ProfileAction::UseEmbedded, ProfileAction::ConvertToWorking, ProfileAction::Discard],
|
||||
ProfileQuestion::Missing { .. } => &[ProfileAction::LeaveAsIs, ProfileAction::AssignWorking],
|
||||
ProfileQuestion::Mismatch { .. } => vec![ProfileAction::UseEmbedded, ProfileAction::ConvertToWorking, ProfileAction::Discard],
|
||||
ProfileQuestion::Missing { .. } => {
|
||||
let mut offered = vec![ProfileAction::LeaveAsIs, ProfileAction::AssignWorking];
|
||||
if self.offers_profile() {
|
||||
offered.push(ProfileAction::AssignProfile);
|
||||
}
|
||||
offered
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer the dialog's state gives: the profile's name only for Assign profile.
|
||||
fn answer(&self) -> ProfileAnswer {
|
||||
let profile = if self.action == ProfileAction::AssignProfile { self.profiles.get(self.chosen).cloned() } else { None };
|
||||
ProfileAnswer { action: self.action, profile, remember: self.remember && self.can_remember() }
|
||||
}
|
||||
|
||||
/// Whether "Remember this choice" shows: a mismatch the app made rememberable.
|
||||
fn can_remember(&self) -> bool {
|
||||
self.rememberable && matches!(self.question, ProfileQuestion::Mismatch { .. })
|
||||
@@ -300,16 +323,16 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
|
||||
/// The chosen action, as OK gives it; `None` for an action the question does not offer.
|
||||
fn confirm(&mut self, _: &Context) -> Option<ProfileAnswer> {
|
||||
self.offered().contains(&self.action).then(|| ProfileAnswer {
|
||||
action: self.action,
|
||||
profile: None,
|
||||
remember: self.remember && self.can_remember(),
|
||||
})
|
||||
self.offered().contains(&self.action).then(|| self.answer())
|
||||
}
|
||||
|
||||
/// `action`, the chosen one of the question's actions, and `remember` while the box shows.
|
||||
/// `action`, the chosen one of the question's actions, `profile` while Assign profile is offered, and `remember`
|
||||
/// while the box shows.
|
||||
fn json_fields(&self) -> Option<serde_json::Value> {
|
||||
let mut fields = json!({ "action": action_name(self.action) });
|
||||
if self.offers_profile() {
|
||||
fields["profile"] = Value::String(self.profiles.get(self.chosen).cloned().unwrap_or_default());
|
||||
}
|
||||
if self.can_remember() {
|
||||
fields["remember"] = Value::Bool(self.remember);
|
||||
}
|
||||
@@ -323,6 +346,11 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
let Some(picked) = picked else { return Err(FieldRefusal::Rejects(&value).message(field)) };
|
||||
self.action = picked;
|
||||
}
|
||||
"profile" if self.offers_profile() => {
|
||||
let at = value.as_str().and_then(|name| self.profiles.iter().position(|profile| profile == name));
|
||||
let Some(at) = at else { return Err(FieldRefusal::Rejects(&value).message(field)) };
|
||||
self.chosen = at;
|
||||
}
|
||||
"remember" if self.can_remember() => match value.as_bool() {
|
||||
Some(on) => self.remember = on,
|
||||
None => return Err(FieldRefusal::Rejects(&value).message(field)),
|
||||
@@ -335,8 +363,10 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<ProfileAnswer>> {
|
||||
let env = Env::of(ui);
|
||||
let (words, common) = (env.words::<ProfileWords>(), env.words::<CommonWords>());
|
||||
let (offered, can_remember) = (self.offered(), self.can_remember());
|
||||
let Self { file_name, mode, question, action, remember, open, .. } = self;
|
||||
let (offered, can_remember, offers_profile) = (self.offered(), self.can_remember(), self.offers_profile());
|
||||
let entries: Vec<Entry<usize>> =
|
||||
if offers_profile { self.profiles.iter().enumerate().map(|(at, name)| Entry::new(at, name.clone())).collect() } else { Vec::new() };
|
||||
let Self { file_name, mode, question, action, remember, chosen, open, .. } = self;
|
||||
let mode_word = mode.word(&words);
|
||||
let name = file_name.as_str();
|
||||
let (title, message, embedded, working) = match &*question {
|
||||
@@ -365,10 +395,12 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
})
|
||||
.collect();
|
||||
let group_label = title.clone();
|
||||
let select_label = words.assign_profile.clone();
|
||||
let (remember_label, remember_tip) = (words.remember.clone(), words.remember_tip.clone());
|
||||
let answers = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)];
|
||||
let held = &mut *action;
|
||||
let ticked = &mut *remember;
|
||||
let picked_profile = &mut *chosen;
|
||||
let shown = Prompt::new(title, message)
|
||||
.answers(answers)
|
||||
.extras(move |ui| {
|
||||
@@ -377,6 +409,11 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
Radio::new(value).label(text).show(ui);
|
||||
}
|
||||
});
|
||||
if offers_profile {
|
||||
Select::new(select_label.clone(), Bind::bound(&mut *picked_profile), &entries)
|
||||
.enabled(*held == ProfileAction::AssignProfile)
|
||||
.show(ui);
|
||||
}
|
||||
if can_remember {
|
||||
Checkbox::new(Bind::bound(&mut *ticked)).label(remember_label.clone()).tooltip(remember_tip.clone()).show(ui);
|
||||
}
|
||||
@@ -384,7 +421,7 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
.opened(Bind::bound(open))
|
||||
.show(ui);
|
||||
match shown.picked {
|
||||
Some(0) => Some(DialogResult::Ok(ProfileAnswer { action: *action, profile: None, remember: *remember && can_remember })),
|
||||
Some(0) => Some(DialogResult::Ok(self.answer())),
|
||||
Some(_) => Some(DialogResult::Cancel),
|
||||
None => None,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Stories of the profile prompts.
|
||||
|
||||
use super::{ProfileMismatchDialog, ProfileMode, ProfileQuestion};
|
||||
use craft_ui::dialog::stories::hosted;
|
||||
use craft_ui::dialog::{DialogStack, StackDialog as _};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
@@ -18,6 +19,27 @@ fn profile_mismatch(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
shown(ui, ProfileMismatchDialog::new("photo.psd", ProfileMode::Rgb, question).rememberable(true))
|
||||
}
|
||||
|
||||
/// A Missing Profile prompt for a scan that offers `names` to assign.
|
||||
fn missing_with(names: &[&str]) -> ProfileMismatchDialog {
|
||||
let question = ProfileQuestion::Missing { working: "sRGB IEC61966-2.1".into() };
|
||||
ProfileMismatchDialog::new("photo.psd", ProfileMode::Rgb, question).profiles(names.iter().map(|name| (*name).to_owned()).collect())
|
||||
}
|
||||
|
||||
#[story(ProfileMismatchDialog, covers = [], drive = Drive::Never)]
|
||||
fn profile_missing_with_profiles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (), || missing_with(&["Adobe RGB (1998)", "Display P3", "ProPhoto RGB"]))
|
||||
}
|
||||
|
||||
#[story(ProfileMismatchDialog, covers = [], drive = Drive::Never)]
|
||||
fn profile_missing_with_long_profile_names(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (), || {
|
||||
missing_with(&[
|
||||
"Coated FOGRA39 (ISO 12647-2:2004) with a perceptual rendering intent and black point compensation",
|
||||
"Japan Color 2001 Coated",
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
#[story(ProfileMismatchDialog, covers = [], drive = Drive::Never)]
|
||||
fn profile_missing(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let question = ProfileQuestion::Missing { working: "sRGB IEC61966-2.1".into() };
|
||||
|
||||
@@ -11,6 +11,44 @@ fn fields(host: &DialogHost, id: DialogId) -> Value {
|
||||
host.open_dialogs().into_iter().find(|dialog| dialog.id == id).and_then(|dialog| dialog.fields).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// The Assign profile list is offered with a profile list only; `profile` refuses a name not listed; OK answers the
|
||||
/// name for Assign profile and none for another action.
|
||||
#[trial]
|
||||
fn assign_profile_answers_the_profile_chosen_in_its_list() {
|
||||
let ctx = Context::default();
|
||||
let mut host = DialogHost::new();
|
||||
let names = || vec!["Dot Gain 20%".to_owned(), "Gray Gamma 2.2".to_owned()];
|
||||
let missing = || ProfileMismatchDialog::new("scan.tif", ProfileMode::Gray, ProfileQuestion::missing("Gray Gamma 2.2"));
|
||||
|
||||
let id = host.open(missing());
|
||||
assert!(host.set_json_field(&ctx, id, "profile", json!("Dot Gain 20%")).is_err_and(|e| e.contains("unknown field")), "no list, no field");
|
||||
assert!(host.set_json_field(&ctx, id, "action", json!("assignProfile")).is_err(), "no list, no Assign profile");
|
||||
assert!(host.cancel_by_id(&ctx, id));
|
||||
host.take::<ProfileMismatchDialog>();
|
||||
|
||||
let id = host.open(missing().profiles(names()));
|
||||
assert_eq!(fields(&host, id), json!({"action": "leaveAsIs", "profile": "Dot Gain 20%"}));
|
||||
assert!(host.set_json_field(&ctx, id, "profile", json!("Nope")).is_err_and(|e| e.contains("can't take")));
|
||||
assert_eq!(host.set_json_field(&ctx, id, "profile", json!("Gray Gamma 2.2")), Ok(()));
|
||||
assert!(host.confirm_by_id(&ctx, id));
|
||||
let answer = host.take::<ProfileMismatchDialog>().and_then(DialogResult::ok);
|
||||
assert_eq!(answer.map(|answer| (answer.action, answer.profile)), Some((ProfileAction::LeaveAsIs, None)));
|
||||
|
||||
let id = host.open(missing().profiles(names()));
|
||||
assert_eq!(host.set_json_field(&ctx, id, "action", json!("assignProfile")), Ok(()));
|
||||
assert_eq!(host.set_json_field(&ctx, id, "profile", json!("Gray Gamma 2.2")), Ok(()));
|
||||
assert!(host.confirm_by_id(&ctx, id));
|
||||
let answer = host.take::<ProfileMismatchDialog>().and_then(DialogResult::ok);
|
||||
assert_eq!(
|
||||
answer.map(|answer| (answer.action, answer.profile)),
|
||||
Some((ProfileAction::AssignProfile, Some("Gray Gamma 2.2".to_owned())))
|
||||
);
|
||||
|
||||
let mismatch = ProfileMismatchDialog::new("poster.psd", ProfileMode::Rgb, ProfileQuestion::mismatch("Adobe RGB (1998)", "sRGB")).profiles(names());
|
||||
let id = host.open(mismatch);
|
||||
assert_eq!(fields(&host, id), json!({"action": "useEmbedded"}), "a mismatch has no profile list");
|
||||
}
|
||||
|
||||
/// A mismatch takes its three actions and, only when rememberable, `remember`; a missing profile has no `discard`;
|
||||
/// OK answers the action and the box as set.
|
||||
// craft-color-ui has no craft-automation dev-dependency (color/Cargo.toml is dialogs-w6's), so the trial drives the
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
//! `JobProgress`: the modal window of a running job, a configuration of `Prompt` with a progress bar.
|
||||
|
||||
use crate::runtime::env::Label;
|
||||
use super::prompt::{Prompt, Reply, buttons};
|
||||
use super::words::DialogWords;
|
||||
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use crate::display::{Progress, Text};
|
||||
use crate::layout_components::Row;
|
||||
use crate::runtime::env::{Env, Label};
|
||||
use crate::runtime::words::CommonWords;
|
||||
use crate::sections::DialogRole;
|
||||
use crate::style::TypeRole;
|
||||
use craft_theme::variant::Tone;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
/// Modal progress window for a running job: a progress bar (or an indeterminate one), counts and the percentage, the
|
||||
/// queued line, and Cancel (and Hide, when `can_hide`). Escape and the close action give Cancel.
|
||||
// P3(files-w2): fl.F12 `#[pattern(dialog)]` needs `StackDialog` (`dialog_probe`); plain `Pattern` registers it
|
||||
// PLAN: `#[pattern(dialog)]` needs `StackDialog` (`dialog_probe`); the app draws this window directly, so it registers as a plain `Pattern`
|
||||
#[derive(crate::contract::Pattern)]
|
||||
#[allow(dead_code)] // P3(files-w2): fl.F12
|
||||
pub struct JobProgress {
|
||||
title: Label,
|
||||
step: Label,
|
||||
@@ -20,42 +28,72 @@ pub struct JobProgress {
|
||||
impl JobProgress {
|
||||
/// A progress window titled `title` showing the current `step`.
|
||||
pub fn new(title: impl Into<Label>, step: impl Into<Label>) -> Self {
|
||||
let _ = (title, step);
|
||||
todo!("fl.F12")
|
||||
JobProgress { title: title.into(), step: step.into(), fraction: None, counts: None, queued: None, can_hide: false }
|
||||
}
|
||||
|
||||
/// The finished fraction in `0.0..=1.0`; `None` shows an indeterminate bar.
|
||||
#[must_use]
|
||||
pub fn fraction(self, fraction: Option<f32>) -> Self {
|
||||
let _ = fraction;
|
||||
todo!("fl.F12")
|
||||
pub fn fraction(mut self, fraction: Option<f32>) -> Self {
|
||||
self.fraction = fraction;
|
||||
self
|
||||
}
|
||||
|
||||
/// The counts line, shown muted with the percentage.
|
||||
#[must_use]
|
||||
pub fn counts(self, counts: impl Into<Label>) -> Self {
|
||||
let _ = counts;
|
||||
todo!("fl.F12")
|
||||
pub fn counts(mut self, counts: impl Into<Label>) -> Self {
|
||||
self.counts = Some(counts.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// The queued line.
|
||||
#[must_use]
|
||||
pub fn queued(self, queued: impl Into<Label>) -> Self {
|
||||
let _ = queued;
|
||||
todo!("fl.F12")
|
||||
pub fn queued(mut self, queued: impl Into<Label>) -> Self {
|
||||
self.queued = Some(queued.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the window offers Hide beside Cancel.
|
||||
#[must_use]
|
||||
pub fn can_hide(self, can_hide: bool) -> Self {
|
||||
let _ = can_hide;
|
||||
todo!("fl.F12")
|
||||
pub fn can_hide(mut self, can_hide: bool) -> Self {
|
||||
self.can_hide = can_hide;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the window; `answer` is `Some` the pass Cancel or Hide answers.
|
||||
pub fn show(self, ui: &mut Ui) -> JobProgressOutput {
|
||||
let _ = ui;
|
||||
todo!("fl.F12")
|
||||
let JobProgress { title, step, fraction, counts, queued, can_hide } = self;
|
||||
let env = Env::of(ui);
|
||||
let (words, common) = (env.words::<DialogWords>(), env.words::<CommonWords>());
|
||||
let percent = fraction.map(|fraction| env.view().format().percent(f64::from(Progress::clamped(fraction)), 0));
|
||||
let mut replies = vec![Reply::plain(common.cancel.clone(), DialogRole::Cancel)];
|
||||
if can_hide {
|
||||
replies.push(Reply::plain(words.job_progress_hide.clone(), DialogRole::Other));
|
||||
}
|
||||
// The open state is this pass's own: the app draws the window only while a job wants it, so an answer must not
|
||||
// leave a session slot closed for the next job.
|
||||
let mut open = true;
|
||||
let shown = Prompt::new(title, step)
|
||||
.answers(buttons(&env, replies))
|
||||
.extras(|ui| {
|
||||
match fraction {
|
||||
Some(fraction) => Progress::new(fraction).show(ui),
|
||||
None => Progress::indeterminate().show(ui),
|
||||
};
|
||||
if counts.is_some() || percent.is_some() {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
for text in counts.iter().cloned().chain(percent.iter().cloned().map(Label::from)) {
|
||||
Text::new(text).role(TypeRole::Caption).tone(Tone::Muted).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(queued) = &queued {
|
||||
Text::new(queued.clone()).show(ui);
|
||||
}
|
||||
})
|
||||
.opened(Bind::bound(&mut open))
|
||||
.show(ui);
|
||||
let answer = shown.picked.map(|index| if index == 0 { JobAnswer::Cancel } else { JobAnswer::Hide });
|
||||
JobProgressOutput { response: shown.response, answer }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Dialog shells and prompts: `Dialog`, `DialogFrame`, `BlockingOverlay`, `Prompt` with its
|
||||
//! configurations (`Alert`, `StandardPrompt`, `UnsavedChangesDialog`, `RecoveryDialog`) and the values an app routes
|
||||
//! configurations (`Alert`, `StandardPrompt`, `UnsavedChangesDialog`, `RecoveryDialog`, `JobProgress`) and the values an app routes
|
||||
//! its dialogs by (`DialogStack`, `DialogHost`). Form dialogs build on the shells.
|
||||
|
||||
mod alert;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `RecoveryDialog` (24.4): the offer to recover a document an earlier run autosaved and never saved, a
|
||||
//! configuration of `Prompt`.
|
||||
|
||||
use super::host::{DialogResult, StackDialog};
|
||||
use super::host::{DialogResult, FieldRefusal, StackDialog};
|
||||
use super::prompt::{Prompt, Reply, buttons};
|
||||
use super::stack::{DialogId, DialogStack, dialog_id};
|
||||
use super::words::DialogWords;
|
||||
@@ -11,6 +11,7 @@ use crate::runtime::overlay::CloseReason;
|
||||
use crate::sections::DialogRole;
|
||||
use craft_i18n::AgeStyle;
|
||||
use egui::{Context, Response, Ui};
|
||||
use serde_json::{Value, json};
|
||||
use std::time::Duration;
|
||||
|
||||
/// One autosaved document, as the app's recovery folder lists it.
|
||||
@@ -43,7 +44,8 @@ impl RecoveredDocument {
|
||||
|
||||
/// What the user chose for one document. Closing the dialog (Escape, the close action) is `DialogResult::Cancel`:
|
||||
/// the copy stays and is offered again at the next launch.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum RecoveryAnswer {
|
||||
/// Open the autosaved copy as an unsaved document.
|
||||
@@ -81,13 +83,14 @@ impl Outcome for RecoveryOutput {
|
||||
pub struct RecoveryDialog {
|
||||
id: DialogId,
|
||||
document: RecoveredDocument,
|
||||
choice: RecoveryAnswer,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
impl RecoveryDialog {
|
||||
/// A dialog offering to recover `document`.
|
||||
pub fn new(document: RecoveredDocument) -> Self {
|
||||
Self { id: dialog_id("recovery"), document, open: true }
|
||||
Self { id: dialog_id("recovery"), document, choice: RecoveryAnswer::Recover, open: true }
|
||||
}
|
||||
|
||||
/// The document asked about; the app reads its key with the answer.
|
||||
@@ -141,8 +144,27 @@ impl StackDialog for RecoveryDialog {
|
||||
Some(shown.answer.map_or(DialogResult::Cancel, DialogResult::Ok))
|
||||
}
|
||||
|
||||
/// Recover, the accepting answer; `None` while recovery is blocked.
|
||||
/// The chosen answer, Recover by default; `None` for Recover while recovery is blocked.
|
||||
fn confirm(&mut self, _: &Context) -> Option<RecoveryAnswer> {
|
||||
self.document.blocked.is_none().then_some(RecoveryAnswer::Recover)
|
||||
(self.choice != RecoveryAnswer::Recover || self.document.blocked.is_none()).then_some(self.choice)
|
||||
}
|
||||
|
||||
/// `choice`, the answer OK gives.
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
Some(json!({ "choice": self.choice }))
|
||||
}
|
||||
|
||||
/// `choice` takes `recover` (not while recovery is blocked) or `discard`.
|
||||
fn set_json_field(&mut self, _: &Context, field: &str, value: Value) -> Result<(), String> {
|
||||
if field != "choice" {
|
||||
return Err(FieldRefusal::Unknown.message(field));
|
||||
}
|
||||
match serde_json::from_value::<RecoveryAnswer>(value.clone()) {
|
||||
Ok(choice) if choice != RecoveryAnswer::Recover || self.document.blocked.is_none() => {
|
||||
self.choice = choice;
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(FieldRefusal::Rejects(&value).message(field)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Stories of the dialog shells.
|
||||
|
||||
use super::modal::ModalDragStrip;
|
||||
use super::{BlockingOverlay, ButtonPlace, Dialog, DialogFrame, DialogHost, StackDialog};
|
||||
use super::{BlockingOverlay, ButtonPlace, Dialog, DialogFrame, DialogHost, JobProgress, StackDialog};
|
||||
use crate::buttons::Button;
|
||||
use crate::choice::Checkbox;
|
||||
use crate::contract::{Bind, FooterSlot, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
@@ -250,6 +250,53 @@ fn blocking_overlay(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
overlay.cancellable(true).opened(Bind::bound(opener(ui, data, EXPORT))).show(ui, |_, _| {}).into()
|
||||
}
|
||||
|
||||
/// A job window behind its opener: the window shows while the story's value is on and the value goes off with an answer.
|
||||
fn job_window(ui: &mut Ui, data: &mut StoryData, window: JobProgress) -> StoryOutput {
|
||||
let open = opener(ui, data, "Show progress…");
|
||||
if *open && window.show(ui).answer.is_some() {
|
||||
*open = false;
|
||||
}
|
||||
StoryOutput::default()
|
||||
}
|
||||
|
||||
#[story(JobProgress, covers = [], drive = Drive::Never)]
|
||||
fn job_progress_counted(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let window = JobProgress::new("Exporting", "Exporting page 3 of 24").fraction(Some(0.125)).counts("3 of 24 pages").can_hide(true);
|
||||
job_window(ui, data, window)
|
||||
}
|
||||
|
||||
#[story(JobProgress, covers = [], drive = Drive::Never)]
|
||||
fn job_progress_indeterminate(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
job_window(ui, data, JobProgress::new("Exporting", "Preparing the export…").can_hide(true))
|
||||
}
|
||||
|
||||
#[story(JobProgress, covers = [], drive = Drive::Never)]
|
||||
fn job_progress_queued(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let window = JobProgress::new("Exporting", "Exporting page 3 of 24")
|
||||
.fraction(Some(0.5))
|
||||
.counts("12 of 24 pages")
|
||||
.queued("2 more exports are waiting")
|
||||
.can_hide(true);
|
||||
job_window(ui, data, window)
|
||||
}
|
||||
|
||||
#[story(JobProgress, covers = [], drive = Drive::Never)]
|
||||
fn job_progress_cancel_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
job_window(ui, data, JobProgress::new("Exporting", "Exporting page 3 of 24").fraction(Some(0.75)).counts("18 of 24 pages"))
|
||||
}
|
||||
|
||||
#[story(JobProgress, covers = [], drive = Drive::Never)]
|
||||
fn job_progress_long_title(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let window = JobProgress::new(
|
||||
"Exporting “Annual report with every regional appendix and the translated summaries” as a print-ready PDF",
|
||||
"Embedding fonts and flattening transparency on page 3 of 24",
|
||||
)
|
||||
.fraction(Some(0.125))
|
||||
.counts("3 of 24 pages")
|
||||
.can_hide(true);
|
||||
job_window(ui, data, window)
|
||||
}
|
||||
|
||||
#[story(ModalDragStrip, covers = [Default], drive = Drive::Never)]
|
||||
fn modal_drag_strip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let room = ui.max_rect();
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Built-in words of the dialog family.
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of the dialog family: the standard prompts, the unsaved-changes question and the recovery dialog.
|
||||
/// The words of the dialog family: the standard prompts, the unsaved-changes question, the recovery dialog and the
|
||||
/// job progress window.
|
||||
/// Cancel, OK and "Don't show again" are the common words. The unsaved-changes question asks Yes, No and Cancel
|
||||
/// on Windows and Linux and Save, Don't Save and Cancel on macOS.
|
||||
pub struct DialogWords {
|
||||
|
||||
@@ -6,8 +6,8 @@ use craft_quit::{CloseAnswer, CloseScope};
|
||||
use craft_ui::contract::{Common, Component, Cx, MeasureCx, PartsCx, Props as _, Role, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::stories::hosted;
|
||||
use craft_ui::dialog::{
|
||||
Alert, Dialog, DialogHost, DialogId, DialogResult, DialogStack, HostedAlert, PromptKind, StackDialog, StandardPrompt, StartupStage,
|
||||
UnsavedChangesDialog, dialog_id,
|
||||
Alert, Dialog, DialogHost, DialogId, DialogResult, DialogStack, HostedAlert, JobAnswer, JobProgress, PromptKind, RecoveredDocument,
|
||||
RecoveryAnswer, RecoveryDialog, StackDialog, StandardPrompt, StartupStage, UnsavedChangesDialog, dialog_id,
|
||||
};
|
||||
use craft_ui::runtime::windows::{WindowHit, WindowHost};
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
@@ -15,7 +15,9 @@ use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use craft_ui::testing::{Fixture, Frames, Story, StoryData, StoryOutput, trial};
|
||||
use egui::{Modifiers, Rect, Response, Ui, Vec2, ViewportId, vec2};
|
||||
use std::cell::{Cell, RefCell};
|
||||
use serde_json::json;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
/// A dialog with no content: it records whether it was the top of the stack when shown and finishes with
|
||||
/// `finish` once set.
|
||||
@@ -162,6 +164,55 @@ fn a_dialog_that_closed_itself_shows_when_opened_again() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Automation answers the recovery prompt through its `choice` field: Discard is reachable, Recover is refused while
|
||||
/// the document is blocked, and a value that is no answer is refused.
|
||||
#[trial]
|
||||
fn automation_answers_a_recovery_prompt_with_discard() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut host = DialogHost::new();
|
||||
let age = Duration::from_secs(300);
|
||||
|
||||
let blocked = RecoveredDocument::new("poster", "poster.psd", age).blocked("Stop recording first");
|
||||
let id = host.open(RecoveryDialog::new(blocked));
|
||||
assert!(host.set_json_field(&ctx, id, "choice", json!("recover")).is_err(), "a blocked document refuses recover");
|
||||
assert!(host.set_json_field(&ctx, id, "choice", json!("maybe")).is_err(), "an unknown choice is refused");
|
||||
assert!(host.set_json_field(&ctx, id, "other", json!("discard")).is_err(), "an unknown field is refused");
|
||||
assert_eq!(host.set_json_field(&ctx, id, "choice", json!("discard")), Ok(()));
|
||||
assert!(host.confirm_by_id(&ctx, id));
|
||||
assert_eq!(host.take::<RecoveryDialog>(), Some(DialogResult::Ok(RecoveryAnswer::Discard)));
|
||||
|
||||
let id = host.open(RecoveryDialog::new(RecoveredDocument::new("poster", "poster.psd", age)));
|
||||
assert!(host.confirm_by_id(&ctx, id));
|
||||
assert_eq!(host.take::<RecoveryDialog>(), Some(DialogResult::Ok(RecoveryAnswer::Recover)), "Recover is the default choice");
|
||||
}
|
||||
|
||||
/// A job window that answered Cancel shows again when the app draws it for the next job.
|
||||
#[trial]
|
||||
fn a_job_window_shows_again_for_the_next_job_after_cancel() {
|
||||
let drawing = Rc::new(Cell::new(true));
|
||||
let answered = Rc::new(Cell::new(None));
|
||||
let (on, got) = (Rc::clone(&drawing), Rc::clone(&answered));
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
if on.get() {
|
||||
if let Some(answer) = JobProgress::new("Exporting", "Page 1 of 3").show(ui).answer {
|
||||
got.set(Some(answer));
|
||||
}
|
||||
}
|
||||
});
|
||||
fixture.idle(6);
|
||||
assert!(fixture.by_label("Exporting").is_some(), "the window shows for the first job");
|
||||
let cancel = fixture.by_label("Cancel").expect("the window has Cancel");
|
||||
fixture.click(&cancel).idle(4);
|
||||
assert_eq!(answered.get(), Some(JobAnswer::Cancel));
|
||||
|
||||
drawing.set(false);
|
||||
fixture.idle(3);
|
||||
assert!(fixture.by_label("Exporting").is_none(), "the window is gone while no job wants it");
|
||||
drawing.set(true);
|
||||
fixture.idle(6);
|
||||
assert!(fixture.by_label("Exporting").is_some(), "the window shows for the next job");
|
||||
}
|
||||
|
||||
const BAND: PartKey = PartKey::new("band");
|
||||
|
||||
/// A style with no look.
|
||||
|
||||
Reference in New Issue
Block a user