diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export.rs b/crates/ui-patterns/src/patterns/form_dialogs/export.rs index 9b0e19acf..369c3bd06 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export.rs @@ -58,6 +58,16 @@ craft_ui::words! { no_estimate: "export.noEstimate" = "—"; estimating: "export.estimating" = "…"; untitled: "export.untitled" = "Untitled"; + scale_all: "export.scaleAll" = "Scale All"; + add_size: "export.addSize" = "Add a size"; + /// `{n}` is the row's number. + size_n: template "export.sizeN" = "Size {n}"; + suffix: "export.suffix" = "Suffix"; + /// `{n}` is the row's number. + suffix_n: template "export.suffixN" = "Suffix {n}"; + /// `{n}` is the row's number. + remove_size: template "export.removeSize" = "Remove size {n}"; + folder_needed: "export.folderNeeded" = "Exporting several sizes at once needs a folder, which this build can't write to; export one size at a time"; preset: "export.preset" = "Preset"; new_preset_name: "export.newPresetName" = "Export Preset"; /// `{size}`: the estimated file size, shown while the exact one is computed. @@ -158,12 +168,158 @@ pub enum ExportMetadata { #[non_exhaustive] pub enum ExportProfile { /// Uses the document's own profile. - #[default] Document, /// Converts to sRGB. + #[default] Srgb, } +/// A Scale All size: a multiple of the export size. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[non_exhaustive] +pub enum ScaleSize { + #[allow(missing_docs)] + #[serde(rename = "0.1x")] + X0_1, + #[allow(missing_docs)] + #[serde(rename = "0.25x")] + X0_25, + #[allow(missing_docs)] + #[serde(rename = "0.3x")] + X0_3, + #[allow(missing_docs)] + #[serde(rename = "0.33x")] + X0_33, + #[allow(missing_docs)] + #[serde(rename = "0.5x")] + X0_5, + #[allow(missing_docs)] + #[serde(rename = "0.75x")] + X0_75, + /// The export size itself. + #[default] + #[serde(rename = "1x")] + X1, + #[allow(missing_docs)] + #[serde(rename = "1.25x")] + X1_25, + #[allow(missing_docs)] + #[serde(rename = "1.5x")] + X1_5, + #[allow(missing_docs)] + #[serde(rename = "2x")] + X2, + #[allow(missing_docs)] + #[serde(rename = "3x")] + X3, +} + +impl ScaleSize { + /// Every size in the list's order. + pub const ALL: [ScaleSize; 11] = [ + ScaleSize::X0_1, + ScaleSize::X0_25, + ScaleSize::X0_3, + ScaleSize::X0_33, + ScaleSize::X0_5, + ScaleSize::X0_75, + ScaleSize::X1, + ScaleSize::X1_25, + ScaleSize::X1_5, + ScaleSize::X2, + ScaleSize::X3, + ]; + + /// The sizes the add button gives, in turn: the first one no row has yet (0.3x is never added). + pub const ADD_ORDER: [ScaleSize; 9] = [ + ScaleSize::X0_5, + ScaleSize::X0_75, + ScaleSize::X0_25, + ScaleSize::X2, + ScaleSize::X0_33, + ScaleSize::X1_5, + ScaleSize::X0_1, + ScaleSize::X3, + ScaleSize::X1_25, + ]; + + /// The multiple of the export size. + pub fn factor(self) -> f64 { + match self { + ScaleSize::X0_1 => 0.1, + ScaleSize::X0_25 => 0.25, + ScaleSize::X0_3 => 0.3, + ScaleSize::X0_33 => 0.33, + ScaleSize::X0_5 => 0.5, + ScaleSize::X0_75 => 0.75, + ScaleSize::X1 => 1.0, + ScaleSize::X1_25 => 1.25, + ScaleSize::X1_5 => 1.5, + ScaleSize::X2 => 2.0, + ScaleSize::X3 => 3.0, + } + } + + /// The size as the list shows it and a suffix names it: `0.5x`, `2x`. + pub fn name(self) -> &'static str { + match self { + ScaleSize::X0_1 => "0.1x", + ScaleSize::X0_25 => "0.25x", + ScaleSize::X0_3 => "0.3x", + ScaleSize::X0_33 => "0.33x", + ScaleSize::X0_5 => "0.5x", + ScaleSize::X0_75 => "0.75x", + ScaleSize::X1 => "1x", + ScaleSize::X1_25 => "1.25x", + ScaleSize::X1_5 => "1.5x", + ScaleSize::X2 => "2x", + ScaleSize::X3 => "3x", + } + } +} + +/// One Scale All row: a size and the suffix its file name takes. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct ScaleRow { + /// The multiple of the export size. + pub size: ScaleSize, + /// What the file name of this size ends with, before the extension; empty for none. + pub suffix: String, +} + +impl ScaleRow { + /// The most rows Scale All holds. + pub const MAX_ROWS: usize = 10; + /// The most characters of a suffix. + pub const MAX_SUFFIX: usize = 64; + + /// A row of `size` with `suffix`. + pub fn new(size: ScaleSize, suffix: impl Into) -> Self { + ScaleRow { size, suffix: suffix.into() } + } + + /// The row the add button appends to `rows`: the next size of [`ScaleSize::ADD_ORDER`] no row has, with the suffix + /// `@`; `None` at [`MAX_ROWS`](Self::MAX_ROWS) or when every size is taken. + pub fn next(rows: &[ScaleRow]) -> Option { + if rows.len() >= Self::MAX_ROWS { + return None; + } + let size = ScaleSize::ADD_ORDER.into_iter().find(|size| rows.iter().all(|row| row.size != *size))?; + Some(ScaleRow::new(size, format!("@{}", size.name()))) + } +} + +/// One file an export writes: its size and the suffix its name takes. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct ExportOutput { + /// The output size in pixels. + pub size: PixelSize, + /// What the file name ends with, before the extension; empty for none. + pub suffix: String, +} + /// Export As's values: the dialog's result and what the app keeps between opens. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[non_exhaustive] @@ -191,10 +347,14 @@ pub struct ExportOptions { /// How the pixels are made when the output size differs from the document's. #[serde(default = "default_resample")] pub resample: Resample, + /// Scale All: one file per row, each at its multiple of the export size. Empty reads as one 1x row with no + /// suffix. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub scale_all: Vec, } impl Default for ExportOptions { - /// PNG at 100 percent, aspect locked, quality 85, document profile embedded, no metadata. + /// PNG at 100 percent, aspect locked, quality 85, converted to sRGB with the profile embedded, no metadata. fn default() -> Self { Self { format: "png".to_owned(), @@ -204,10 +364,11 @@ impl Default for ExportOptions { size: ExportSize::Scale(FULL_SCALE), lock_aspect: true, metadata: ExportMetadata::None, - profile: ExportProfile::Document, + profile: ExportProfile::Srgb, embed_profile: true, bits: 0, resample: default_resample(), + scale_all: Vec::new(), } } } @@ -263,6 +424,25 @@ impl ExportOptions { ExportSize::Pixels { width, height } => PixelSize::new(width, height), } } + + /// Scale All's rows: the set ones, or one 1x row with no suffix. + pub fn scale_rows(&self) -> Vec { + if self.scale_all.is_empty() { vec![ScaleRow::default()] } else { self.scale_all.clone() } + } + + /// The files an export of a document of size `source` writes: one per Scale All row, each side the output size's + /// times the row's multiple, rounded, in 1 to the largest document side. + pub fn outputs(&self, source: PixelSize) -> Vec { + let size = self.output_size(source); + let side = |n: u32, factor: f64| (f64::from(n) * factor).round().clamp(1.0, MAX_DOCUMENT_SIDE) as u32; + self.scale_rows() + .into_iter() + .map(|row| ExportOutput { + size: PixelSize::new(side(size.width, row.size.factor()), side(size.height, row.size.factor())), + suffix: row.suffix, + }) + .collect() + } } /// The file size line under the preview. @@ -336,6 +516,9 @@ pub struct ExportAsResult { pub path: PathBuf, /// The output size in pixels. pub size: PixelSize, + /// The files to write ([`ExportOptions::outputs`]). With more than one, `path` is the folder the user chose and + /// the app names each file `.`. + pub outputs: Vec, remember: Option<(SaveKey, ExportOptions)>, } diff --git a/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs index 0e6fd4b86..864f0298e 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/export/as_dialog.rs @@ -4,12 +4,16 @@ use super::{ ExportAsResult, ExportFormat, ExportFormatDefaults, ExportMetadata, ExportOptions, ExportPreview, ExportProfile, ExportSize, ExportWords, - Revisions, SizeEstimate, export_file_name, size_error_label, + Revisions, ScaleRow, ScaleSize, SizeEstimate, export_file_name, size_error_label, }; +use crate::buttons::IconButton; +use crate::contract::clicked; use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field}; use crate::patterns::form_dialogs::form::{read_bind, write_bind}; use crate::patterns::presets::{GroupPath, NamedPresetEvent, NamedPresetRow, PickerField, PresetLibrary, PresetPicker, PresetRow, PresetState}; -use crate::runtime::requests::{HostAnswer, PathFilter, PathRequest}; +use crate::runtime::requests::{HostAnswer, PathFilter, PathKind, PathRequest}; +use crate::text::TextField; +use craft_behavior::IconId; use crate::choice::Checkbox; use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Remember as _, SaveKey, Show as _, ShowContainer as _}; @@ -112,10 +116,14 @@ impl Outcome for ExportAsOutput { /// computes. /// /// - The settings: the format, then that format's rows (Lossless, Quality, Bits/Pixel, Transparency), Metadata, -/// Color Space with Embed Color Profile, and Image Size (Scale, Width, Height, Constrain Proportions, Resample). -/// - Keys: Tab walks the fields, Enter is Export and Escape cancels. Holding Alt +/// Color Space (Convert to sRGB, on by default, and Embed Color Profile), Image Size (Scale, Width, Height, +/// Constrain Proportions, Resample) and Scale All: rows of a size and a file-name suffix, + adding the next size +/// ([`ScaleRow::next`]) and each row's trash button removing it while more than one is left. +/// - Keys: Tab walks the fields and Escape cancels; Enter does not export, only the Export button does. Holding Alt /// turns Cancel into Reset, which restores the settings the dialog opened with. Export asks the app for a file -/// to write (`ExportAsOutput::requests`) and the dialog stays open until the app answers with the path. +/// to write (`ExportAsOutput::requests`), or a folder with more than one Scale All row, and the dialog stays open +/// until the app answers with the path. Without [`folder_export`](ExportAsDialog::folder_export), more than one row +/// refuses Export with a note. /// - Settings: the dialog opens on the value in the bind, fitted to the document, and writes its edits back. /// - Previews: whenever the settings change, `wanted_preview` carries a new revision. The app encodes a proxy and /// gives it back with `preview`; a size estimate shows at once ("≈ 1.2 MB"), and the app may follow with an exact @@ -161,6 +169,10 @@ pub struct ExportAsDialog<'a> { /// pass (a field edited before the dialog was first shown is not the Reset target). #[prop] opening: Option, + /// Whether the app can write a folder of files, for more than one Scale All row; the default is true. A build + /// whose file dialog answers no folder (the browser) sets it off. + #[prop] + folder_export: bool, } impl<'a> ExportAsDialog<'a> { @@ -181,6 +193,7 @@ impl<'a> ExportAsDialog<'a> { presets: None, remember: None, opening: None, + folder_export: true, } } @@ -201,6 +214,7 @@ impl<'a> ExportAsDialog<'a> { mut presets, remember, opening, + folder_export, } = self; let env = Env::of(ui); let words = env.words::(); @@ -228,6 +242,7 @@ impl<'a> ExportAsDialog<'a> { .ok_label(words.export.clone()) .ok_enabled(!saving) .accept_stays_open(true) + .enter_confirms(false) .answers(answers); if let Some(open) = open { dialog = dialog.opened(open); @@ -257,10 +272,14 @@ impl<'a> ExportAsDialog<'a> { }); Stack::new().show(ui, |ui, _| pass.preview(ui, values, &mut held)); }); + let exportable = folder_export || values.scale_all.len() <= 1; + if !exportable { + Text::new(words.folder_needed.clone()).role(TypeRole::Caption).tone(Tone::Bad).show(ui); + } *wanted.borrow_mut() = held.revisions.request(values); *form.memory::() = held; *latest.borrow_mut() = Some(values.clone()); - true + exportable }); let FormOutput { response, closed, picked, accepted, mut requests, .. } = shown; @@ -281,8 +300,12 @@ impl<'a> ExportAsDialog<'a> { } } -/// The save dialog Export asks for: the document's name with the format's extension and filter. +/// The save dialog Export asks for: the document's name with the format's extension and filter; a folder for more than +/// one Scale All row. fn save_request(formats: &[ExportFormat], options: &ExportOptions, file_name: &str, words: &ExportWords) -> PathRequest { + if options.scale_all.len() > 1 { + return PathRequest::new(SAVE_KEY, PathKind::Folder); + } let format = formats.iter().find(|format| format.id == options.format); let extension = format.map_or("png", |format| format.extension); let name = format!("{}.{extension}", export_file_name(file_name, words.untitled.as_str())); @@ -293,7 +316,13 @@ fn save_request(formats: &[ExportFormat], options: &ExportOptions, file_name: &s /// What Export answers with: the confirmed options, the chosen path, the output size, and the options to remember when /// the dialog has a key. fn answer_of(options: ExportOptions, source: PixelSize, path: PathBuf, remember: Option) -> ExportAsResult { - ExportAsResult { size: options.output_size(source), remember: remember.map(|key| (key, options.clone())), options, path } + ExportAsResult { + size: options.output_size(source), + outputs: options.outputs(source), + remember: remember.map(|key| (key, options.clone())), + options, + path, + } } /// An [`ExportAsDialog`] the [`DialogHost`](crate::dialog::DialogHost) owns. It keeps the settings and the app's @@ -330,6 +359,7 @@ pub struct HostedExportAs { remember: Option, /// The path the host's save dialog answered, or automation set; Export finishes with it. path: Option, + folder_export: bool, #[cfg(feature = "testing")] facts: crate::testing::StoryOutput, } @@ -383,11 +413,19 @@ impl HostedExportAs { events: Vec::new(), remember: None, path: None, + folder_export: true, #[cfg(feature = "testing")] facts: crate::testing::StoryOutput::default(), } } + /// Whether the app can write a folder of files ([`ExportAsDialog::folder_export`]). + #[must_use] + pub fn folder_export(mut self, on: bool) -> Self { + self.folder_export = on; + self + } + /// The formats the list offers. #[must_use] pub fn formats(mut self, formats: Vec) -> Self { @@ -461,6 +499,9 @@ impl StackDialog for HostedExportAs { /// Answers what the save answer answers. Without a path it asks for the save dialog as Export does and answers /// none until the app answers the path. fn confirm(&mut self, ctx: &egui::Context) -> Option { + if !self.folder_export && self.options.scale_all.len() > 1 { + return None; + } let Some(path) = self.path.clone() else { if !self.saving { let words = Env::of_root(ctx).words::(); @@ -521,6 +562,7 @@ impl StackDialog for HostedExportAs { presets: self.with_presets.then(|| Bind::bound(&mut self.presets)), remember: self.remember.clone(), opening: Some(self.opening.clone()), + folder_export: self.folder_export, ..ExportAsDialog::new(self.file_name.clone(), self.source, Bind::bound(&mut self.options)) }; let mut shown = dialog.show(ui); @@ -629,15 +671,18 @@ impl Pass<'_> { Entry::new(ExportMetadata::All, words.metadata_all.clone()), ]; choose(ui, &words.metadata, "metadata", &metadata, &mut options.metadata); - let profiles = - [Entry::new(ExportProfile::Document, words.document_profile.clone()), Entry::new(ExportProfile::Srgb, words.convert_srgb.clone())]; - choose(ui, &words.color_space, "profile", &profiles, &mut options.profile); - check(ui, &words.embed_profile, "embed", &mut options.embed_profile); + Section::fixed(words.color_space.clone()).strength(HeaderStrength::Caption).id_salt("color-space").show(ui, |ui, _| { + let mut srgb = options.profile == ExportProfile::Srgb; + check(ui, &words.convert_srgb, "profile", &mut srgb); + options.profile = if srgb { ExportProfile::Srgb } else { ExportProfile::Document }; + check(ui, &words.embed_profile, "embed", &mut options.embed_profile); + }); Section::fixed(words.image_size.clone()) .strength(HeaderStrength::Caption) .id_salt("size") .show(ui, |ui, _| self.size(ui, options, held, format)); + Section::fixed(words.scale_all.clone()).strength(HeaderStrength::Caption).id_salt("scale-all").show(ui, |ui, _| self.scale_all(ui, options)); if let Some(library) = self.library { self.preset_row(ui, options, held, library); } @@ -693,6 +738,55 @@ impl Pass<'_> { } } + /// Scale All: a row per size, each a size list, a suffix field and a trash button (disabled while one row is left), + /// and + adding the next size. The rows are kept only while there is more than one, so a single 1x row with no + /// suffix is no rows. + fn scale_all(&self, ui: &mut Ui, options: &mut ExportOptions) { + let words = self.words; + let mut rows = options.scale_rows(); + let sizes: Vec> = ScaleSize::ALL.iter().map(|size| Entry::new(*size, size.name())).collect(); + let next = ScaleRow::next(&rows); + let add = IconButton::new(IconId::new("plus")) + .label(words.add_size.clone()) + .tooltip(words.add_size.clone()) + .enabled(next.is_some()) + .id_salt("add-size") + .show(ui); + if clicked(&add) + && let Some(row) = next + { + rows.push(row); + } + let single = rows.len() == 1; + let mut remove = None; + for (at, row) in rows.iter_mut().enumerate() { + let n = (at + 1).to_string(); + Row::new().id_salt(("scale-row", at)).show(ui, |ui, _| { + let name = words.size_n.fill(&[("n", n.as_str())]); + if let Some(size) = Select::new(name, Bind::given(row.size), &sizes).show(ui).value().copied() { + row.size = size; + } + let name = Label::from(words.suffix_n.fill(&[("n", n.as_str())])); + let typed = + TextField::new(name, Bind::given(row.suffix.clone())).limit(ScaleRow::MAX_SUFFIX).placeholder(words.suffix.clone()).show(ui); + if let Some(suffix) = typed.value().cloned() { + row.suffix = suffix; + } + let name = Label::from(words.remove_size.fill(&[("n", n.as_str())])); + if clicked(&IconButton::new(IconId::new("trash")).label(name.clone()).tooltip(name).enabled(!single).id_salt("remove").show(ui)) { + remove = Some(at); + } + }); + } + if let Some(at) = remove { + rows.remove(at); + } + let rows = if rows.len() == 1 && rows[0] == ScaleRow::default() { Vec::new() } else { rows }; + if rows != options.scale_all { + options.scale_all = rows; + } + } + /// The format list picked `index`: the format takes the app's default quality (and WebP mode). fn switch(&self, options: &mut ExportOptions, index: usize) { let Some(format) = self.formats.get(index) else { return }; diff --git a/crates/ui-patterns/src/patterns/form_dialogs/form.rs b/crates/ui-patterns/src/patterns/form_dialogs/form.rs index 3a594be75..8b0fa5e7c 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/form.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/form.rs @@ -153,7 +153,7 @@ type ResetWithFn<'a, V> = Box V + 'a>; /// /// - The bind holds the value. [`own`](FormDialog::own) binds the dialog's memory instead, and the value starts from /// `V::default()` each time the dialog opens. -/// - Keys: Enter is OK unless the body owns it, Escape cancels. Holding Alt turns Cancel into Reset, which restores +/// - Keys: Enter is OK unless the body owns it or [`enter_confirms`](FormDialog::enter_confirms) is off, Escape cancels. Holding Alt turns Cancel into Reset, which restores /// the value from when the dialog opened (and runs [`on_reset`](FormDialog::on_reset) for what the body keeps). /// - The body returns whether the value can be accepted; OK is enabled while it can and `ok_enabled` is true. /// - With [`history`](FormDialog::history), Cmd/Ctrl+Z and Shift+Cmd/Ctrl+Z step the dialog's own value; a drag or a @@ -178,6 +178,7 @@ pub struct FormDialog<'a, V: Value + Default> { collection_body: bool, closable: bool, accept_stays_open: bool, + enter_confirms: bool, footer_extra: Option>, /// The Preview check box when shown, over its owner's bind or (`None`) the footer's memory. preview: Option>>, @@ -208,6 +209,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> { collection_body: false, closable: true, accept_stays_open: false, + enter_confirms: true, footer_extra: None, preview: None, extra_buttons: Vec::new(), @@ -293,6 +295,13 @@ impl<'a, V: Value + Default> FormDialog<'a, V> { self } + /// Whether Enter, left untaken by the focused part, is OK; the default is true. Off, only a click (or the + /// button's own keys) gives OK, as Export As starts only from its Export button. + pub fn enter_confirms(mut self, on: bool) -> Self { + self.enter_confirms = on; + self + } + /// Controls before the buttons in the footer. pub fn footer_extra(mut self, extra: impl FnMut(&mut Ui) + 'a) -> Self { self.footer_extra = Some(Box::new(extra)); @@ -365,6 +374,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> { collection_body, closable, accept_stays_open, + enter_confirms, footer_extra, preview, extra_buttons, @@ -403,7 +413,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> { } } }; - let mut dialog = Dialog::new(title).closable(closable).close_on_enter(ok_enabled).outer_gesture(outer_gesture); + let mut dialog = Dialog::new(title).closable(closable).close_on_enter(ok_enabled && enter_confirms).outer_gesture(outer_gesture); dialog = reset.install(dialog, accept, restore); if let Some(open) = open { dialog = dialog.opened(open); diff --git a/crates/ui-patterns/src/patterns/form_dialogs/mod.rs b/crates/ui-patterns/src/patterns/form_dialogs/mod.rs index c732d1d32..01076d86e 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/mod.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/mod.rs @@ -86,9 +86,9 @@ mod export; pub use export::{ DdsCompression, DdsOptions, ExportAsDialog, ExportAsOutput, ExportAsResult, ExportFormat, ExportFormatDefaults, ExportMetadata, ExportOptions, - ExportOptionsKind, ExportPreview, ExportProfile, ExportSize, ExportWords, FormatOptions, FormatOptionsDialog, FormatOptionsOutput, + ExportOptionsKind, ExportOutput, ExportPreview, ExportProfile, ExportSize, ExportWords, FormatOptions, FormatOptionsDialog, FormatOptionsOutput, FormatOptionsWords, HostedExportAs, HostedFormatOptions, JpegFormat, JpegOptions, JpegPreset, OutputPathOutput, OutputPathRow, OutputPathWords, - SizeEstimate, TargaOptions, TiffCompression, TiffOptions, jpeg_quality_percent, + ScaleRow, ScaleSize, SizeEstimate, TargaOptions, TiffCompression, TiffOptions, jpeg_quality_percent, }; // Save PDF. diff --git a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs index 14dd6c641..08c4281fa 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/hosted.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/hosted.rs @@ -253,3 +253,63 @@ fn hosted_export_as_finishes_when_the_app_answers_its_save_request() { let answered = host.borrow_mut().take::().and_then(DialogResult::ok).map(|result| result.path); assert_eq!(answered, Some(path), "the answered path finishes the dialog with it"); } + +/// Export As: Enter alone does not export; Convert to sRGB starts on and its box gives the document's profile; + adds +/// 0.5x "@0.5x", then 0.75x, and a row's trash button removes it while more than one is left; two rows ask for a folder +/// and answer one output per row; without folder export, two rows refuse Export. +#[trial] +fn export_as_writes_one_file_per_scale_all_row_and_only_from_its_button() { + use craft_ui::patterns::form_dialogs::{ExportProfile, ScaleRow, ScaleSize}; + use craft_ui::runtime::requests::PathKind; + assert_eq!(ExportOptions::default().profile, ExportProfile::Srgb, "Convert to sRGB is on by default"); + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(HostedExportAs::new("Poster", PICTURE, ExportOptions::default())); + fixture.idle(10); + let options = |host: &Rc>| host.borrow().get::().map(|dialog| dialog.options().clone()).expect("open"); + let pick = |host: &Rc>| host.borrow_mut().get_mut::().and_then(HostedExportAs::pick_path); + + fixture.key(Key::Enter, Modifiers::NONE).idle(4); + assert!(pick(&host).is_none() && host.borrow().is_open::(), "Enter does not start the export"); + + let srgb = fixture.by_label("Convert to sRGB").expect("the Color Space box"); + fixture.click(&srgb).idle(4); + assert_eq!(options(&host).profile, ExportProfile::Document, "unticked keeps the document's profile"); + + let one = fixture.by_label("Remove size 1").expect("the first row's trash button"); + fixture.click(&one).idle(4); + assert_eq!(options(&host).scale_rows().len(), 1, "the last row stays"); + let add = fixture.by_label("Add a size").expect("the + button"); + fixture.click(&add).idle(4); + let add = fixture.by_label("Add a size").expect("the + button"); + fixture.click(&add).idle(4); + assert_eq!( + options(&host).scale_all, + [ScaleRow::default(), ScaleRow::new(ScaleSize::X0_5, "@0.5x"), ScaleRow::new(ScaleSize::X0_75, "@0.75x")], + "+ adds the next sizes" + ); + let third = fixture.by_label("Remove size 3").expect("the third row's trash button"); + fixture.click(&third).idle(4); + assert_eq!(options(&host).scale_all.len(), 2); + + let export = fixture.by_label("Export…").expect("the Export button"); + fixture.click(&export).idle(4); + let request = pick(&host).expect("Export asks where to write"); + assert!(matches!(request.kind, PathKind::Folder), "two rows ask for a folder"); + if let Some(dialog) = host.borrow_mut().get_mut::() { + dialog.answer_path(request.key.clone(), PathBuf::from("/tmp/out")); + } + fixture.idle(6); + let outputs = host.borrow_mut().take::().and_then(DialogResult::ok).map(|result| result.outputs).expect("answered"); + let listed: Vec<(PixelSize, &str)> = outputs.iter().map(|output| (output.size, output.suffix.as_str())).collect(); + assert_eq!(listed, [(PICTURE, ""), (PixelSize::new(800, 450), "@0.5x")], "one output per row"); + + let mut two = ExportOptions::default(); + two.scale_all = vec![ScaleRow::default(), ScaleRow::new(ScaleSize::X2, "@2x")]; + host.borrow_mut().open(HostedExportAs::new("Poster", PICTURE, two).folder_export(false)); + fixture.idle(10); + let export = fixture.by_label("Export…").expect("the Export button"); + fixture.click(&export).idle(4); + let ctx = fixture.ctx().clone(); + assert!(pick(&host).is_none() && !host.borrow_mut().confirm::(&ctx), "without a folder two rows refuse Export"); +}