diff --git a/crates/text/src/ui/character/paragraph_dialog.rs b/crates/text/src/ui/character/paragraph_dialog.rs index 13eb118d5..20a3bf729 100644 --- a/crates/text/src/ui/character/paragraph_dialog.rs +++ b/crates/text/src/ui/character/paragraph_dialog.rs @@ -12,20 +12,28 @@ //! } //! ``` +use std::borrow::Cow; use std::cell::Cell; use crate::ui::length::{DocUnit, length_field, shown}; -use craft_behavior::{Axis, EditEvent, Metrics, Mixed, NumberCodec}; +use craft_behavior::{Axis, EditEvent, Metrics, Mixed, NumberCodec, SelectionChange, keyed}; use craft_theme::variant::Tone; -use craft_ui::contract::{Bind, Common, Component, Cx, Entry, MeasureCx, PaintUi, Props as _, Role, Show as _, ShowContainer as _}; -use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft_ui::choice::{Checkbox, Radio, RadioGroup}; +use craft_ui::contract::{ + Bind, CollectionEvent, Common, Component, Cx, Entry, FieldLayout, MeasureCx, PaintUi, Props as _, Role, Show as _, ShowCollection as _, + ShowContainer as _, SideLabel, +}; +use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id, serde_fields, set_serde_field}; +use craft_ui::display::Text; use craft_ui::form::{Field, FieldGroup, Help}; +use craft_ui::layout_components::Stack; use craft_ui::pickers::Select; use craft_ui::primitives::TextRun; use craft_ui::runtime::env::{Env, Label, UnitKind, Units}; use craft_ui::runtime::words::CommonWords; use craft_ui::sections::{DialogRole, FooterButton, GroupBox}; use craft_ui::style::{ComponentStyle, Corners, StyleColor, StyleCx, SurfaceKind, TypeRole}; +use craft_ui::tabs::{Tab, TabKind, TabStrip}; use craft_ui::text::NumberField; use egui::{Rect, Response, Ui, Vec2, pos2, vec2}; @@ -65,11 +73,35 @@ craft_ui::words! { at_least: "paragraphDialog.atLeast" = "At least"; sample: "paragraphDialog.sample" = "Sample Text"; out_of_range: template "paragraphDialog.outOfRange" = "{field} must be from {min} to {max}"; + indents_and_spacing: "paragraphDialog.tabIndents" = "Indents and Spacing"; + line_and_page_breaks: "paragraphDialog.tabBreaks" = "Line and Page Breaks"; + asian_typography: "paragraphDialog.tabAsian" = "Asian Typography"; + direction: "paragraphDialog.direction" = "Direction:"; + left_to_right: "paragraphDialog.leftToRight" = "Left-to-right"; + right_to_left: "paragraphDialog.rightToLeft" = "Right-to-left"; + mirror_indents: "paragraphDialog.mirrorIndents" = "Mirror indents"; + inside: "paragraphDialog.inside" = "Inside"; + outside: "paragraphDialog.outside" = "Outside"; + exceptions: "paragraphDialog.exceptions" = "Formatting exceptions"; + widow_control: "paragraphDialog.widowControl" = "Widow/Orphan control"; + keep_with_next: "paragraphDialog.keepWithNext" = "Keep with next"; + keep_lines_together: "paragraphDialog.keepLinesTogether" = "Keep lines together"; + page_break_before: "paragraphDialog.pageBreakBefore" = "Page break before"; + suppress_line_numbers: "paragraphDialog.suppressLineNumbers" = "Suppress line numbers"; + dont_hyphenate: "paragraphDialog.dontHyphenate" = "Don't hyphenate"; + line_breaking: "paragraphDialog.lineBreaking" = "Line breaking"; + character_spacing: "paragraphDialog.characterSpacing" = "Character Spacing"; + kinsoku: "paragraphDialog.kinsoku" = "Apply Asian line-breaking rules (kinsoku)"; + word_wrap: "paragraphDialog.wordWrap" = "Allow Latin text to wrap in the middle of a word"; + overflow_punct: "paragraphDialog.overflowPunct" = "Allow hanging punctuation"; + top_line_punct: "paragraphDialog.topLinePunct" = "Compress punctuation at the start of a line"; + auto_space_de: "paragraphDialog.autoSpaceDe" = "Add space between Asian and Latin text"; + auto_space_dn: "paragraphDialog.autoSpaceDn" = "Add space between Asian text and numbers"; } } /// PowerPoint's alignments (Word has the first four). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub enum ParagraphAlign { /// Left. @@ -88,7 +120,7 @@ pub enum ParagraphAlign { } /// The first line against the others. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub enum SpecialIndent { /// None. @@ -102,7 +134,7 @@ pub enum SpecialIndent { /// What a paragraph's spacing before or after counts, as DeckCraft keeps it (`spaceBeforeKind` /// and `spaceAfterKind`, `pts` or `pct`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub enum SpacingKind { /// A distance in points. @@ -113,7 +145,7 @@ pub enum SpacingKind { } /// Line spacing. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub enum LineSpacing { /// A multiple of single spacing: Single is 1, 1.5 lines 1.5, Double 2, Multiple any other. @@ -130,9 +162,26 @@ impl Default for LineSpacing { } } +/// Serde form of a row that is hidden (outer `None`), shown empty (`Some(None)`) or shown with a value: a hidden row has +/// no key and an empty one is `null`, so a round trip through JSON keeps the two apart. +mod shown_or_hidden { + use serde::{Deserialize, Deserializer, Serialize, Serializer}; + + pub(super) fn serialize(value: &Option>, serializer: S) -> Result { + match value { + Some(shown) => shown.serialize(serializer), + None => serializer.serialize_none(), + } + } + + pub(super) fn deserialize<'de, T: Deserialize<'de>, D: Deserializer<'de>>(deserializer: D) -> Result>, D::Error> { + Option::::deserialize(deserializer).map(Some) + } +} + /// What the dialog edits; `None` where the selected paragraphs differ (the field starts empty /// and a field left empty is left as it was). -#[derive(Clone, Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] #[non_exhaustive] pub struct ParagraphFormat { /// The align. @@ -141,6 +190,7 @@ pub struct ParagraphFormat { pub before_text: Option, /// Word's right indent ("After text"). The outer `None` hides the field (PowerPoint has /// none); `Some(None)` shows it empty, for paragraphs that differ. + #[serde(default, skip_serializing_if = "Option::is_none", with = "shown_or_hidden")] pub after_text: Option>, /// The special first-line indent: none, first line or hanging. pub special: Option, @@ -160,8 +210,10 @@ pub struct ParagraphFormat { pub line_spacing: Option, /// The paragraph's direction. The outer `None` hides the row; `Some(None)` shows it empty, for paragraphs that /// differ. + #[serde(default, skip_serializing_if = "Option::is_none", with = "shown_or_hidden")] pub direction: Option>, /// Mirror indents: Left and Right read Inside and Outside when on. The outer `None` hides it; `Some(None)` is mixed. + #[serde(default, skip_serializing_if = "Option::is_none", with = "shown_or_hidden")] pub mirror_indents: Option>, /// The Line and Page Breaks check boxes. `None` hides the page. pub breaks: Option, @@ -205,7 +257,7 @@ pub struct AsianTypography { } /// The page of Word's Paragraph dialog the dialog opens on. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub enum ParagraphTab { /// Indents and Spacing. #[default] @@ -249,8 +301,10 @@ pub struct ParagraphDialog { word: bool, /// The format the dialog opened with: a spacing that returns to its value takes its kind back. opened: ParagraphFormat, - #[allow(dead_code)] // P3(dialogs-w3): dg.F9 tab: ParagraphTab, + /// Whether OK files its answer for the app to judge instead of closing. + hold: bool, + held: HeldAnswer, } impl ParagraphDialog { @@ -262,6 +316,8 @@ impl ParagraphDialog { unit: DocUnit::new(UnitKind::Inches, UnitKind::POINTS_PER_INCH), word: false, tab: ParagraphTab::default(), + hold: false, + held: HeldAnswer::new(), } } @@ -549,22 +605,125 @@ impl ParagraphDialog { } } + /// Whether the dialog shows Word's three pages. + fn paged(&self) -> bool { + self.word && self.format.breaks.is_some() && self.format.asian.is_some() + } + fn body(&mut self, ui: &mut Ui, scope: &Scope<'_>, valid: &Cell) { let words = scope.words; valid.set(true); + let paged = self.paged(); + if paged { + self.tab_strip(ui, words); + } + match self.tab { + ParagraphTab::LineAndPageBreaks if paged => self.breaks_page(ui, words), + ParagraphTab::AsianTypography if paged => self.asian_page(ui, words), + _ => self.indents_page(ui, scope, valid), + } + if !self.out_of_range().is_empty() { + valid.set(false); + } + } + + fn indents_page(&mut self, ui: &mut Ui, scope: &Scope<'_>, valid: &Cell) { + let words = scope.words; FieldGroup::new(words.title.clone()).show(ui, |ui, _| { - GroupBox::new(words.general.clone(), None).show(ui, |ui, _| self.alignment(ui, words)); - GroupBox::new(words.indentation.clone(), None).show(ui, |ui, _| self.indentation(ui, scope, valid)); + GroupBox::new(words.general.clone(), None).show(ui, |ui, _| { + self.direction(ui, words); + self.alignment(ui, words); + }); + GroupBox::new(words.indentation.clone(), None).show(ui, |ui, _| { + self.indentation(ui, scope, valid); + self.mirror(ui, words); + }); GroupBox::new(words.spacing.clone(), None).show(ui, |ui, _| self.spacing(ui, scope, valid)); GroupBox::new(words.preview.clone(), None).show(ui, |ui, _| { ParagraphPreview::new(words.preview.clone(), &self.format, words.sample.as_str()).show(ui); }); }); - if !self.out_of_range().is_empty() { - valid.set(false); + } + + fn tab_strip(&mut self, ui: &mut Ui, words: &ParagraphDialogWords) { + let tabs = [ + (ParagraphTab::IndentsAndSpacing, words.indents_and_spacing.as_str().to_owned()), + (ParagraphTab::LineAndPageBreaks, words.line_and_page_breaks.as_str().to_owned()), + (ParagraphTab::AsianTypography, words.asian_typography.as_str().to_owned()), + ]; + let source = keyed(&tabs[..], |tab: &(ParagraphTab, String)| tab.0).with_text(|tab| Cow::Borrowed(tab.1.as_str())); + let strip = TabStrip::new(words.title.clone()).kind(TabKind::Text).shown(self.tab).natural_height(true); + let out = strip.show_items(ui, &source, &mut |key, _| { + Tab::new(tabs.iter().find(|tab| tab.0 == *key).map_or_else(String::new, |tab| tab.1.clone())) + }); + for event in out.response.events { + if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event + && let Some(chosen) = keys.last() + { + self.tab = *chosen; + } } } + /// Left to right and Right to left; a paragraph with another or differing direction leaves both unchecked. + fn direction(&mut self, ui: &mut Ui, words: &ParagraphDialogWords) { + let Some(current) = self.format.direction else { return }; + let before = current.filter(|direction| matches!(direction, super::ParagraphDirection::LeftToRight | super::ParagraphDirection::RightToLeft)); + let mut picked = before; + RadioGroup::new(words.direction.clone(), Bind::bound(&mut picked)).show(ui, |ui, _| { + Stack::new().show(ui, |ui, cx| { + Text::new(words.direction.clone()).show(ui); + let options = [ + (super::ParagraphDirection::LeftToRight, &words.left_to_right), + (super::ParagraphDirection::RightToLeft, &words.right_to_left), + ]; + for (at, (direction, label)) in options.into_iter().enumerate() { + cx.labelled(ui, at, label.clone(), SideLabel::new().layout(FieldLayout::After), Radio::new(Some(direction))); + } + }); + }); + if picked != before + && let Some(direction) = picked + { + self.format.direction = Some(Some(direction)); + } + } + + fn mirror(&mut self, ui: &mut Ui, words: &ParagraphDialogWords) { + let Some(current) = self.format.mirror_indents else { return }; + if let Some(on) = check(ui, &words.mirror_indents, current) { + self.format.mirror_indents = Some(Some(on)); + } + } + + fn breaks_page(&mut self, ui: &mut Ui, words: &ParagraphDialogWords) { + let Some(breaks) = self.format.breaks.as_mut() else { return }; + GroupBox::new(words.line_and_page_breaks.clone(), None).show(ui, |ui, _| { + toggle(ui, &words.widow_control, &mut breaks.widow_control); + toggle(ui, &words.keep_with_next, &mut breaks.keep_with_next); + toggle(ui, &words.keep_lines_together, &mut breaks.keep_lines_together); + toggle(ui, &words.page_break_before, &mut breaks.page_break_before); + }); + GroupBox::new(words.exceptions.clone(), None).show(ui, |ui, _| { + toggle(ui, &words.suppress_line_numbers, &mut breaks.suppress_line_numbers); + toggle(ui, &words.dont_hyphenate, &mut breaks.dont_hyphenate); + }); + } + + fn asian_page(&mut self, ui: &mut Ui, words: &ParagraphDialogWords) { + let Some(asian) = self.format.asian.as_mut() else { return }; + GroupBox::new(words.line_breaking.clone(), None).show(ui, |ui, _| { + toggle(ui, &words.kinsoku, &mut asian.kinsoku); + toggle(ui, &words.word_wrap, &mut asian.word_wrap); + toggle(ui, &words.overflow_punct, &mut asian.overflow_punct); + }); + GroupBox::new(words.character_spacing.clone(), None).show(ui, |ui, _| { + toggle(ui, &words.top_line_punct, &mut asian.top_line_punct); + toggle(ui, &words.auto_space_de, &mut asian.auto_space_de); + toggle(ui, &words.auto_space_dn, &mut asian.auto_space_dn); + }); + } + fn alignment(&mut self, ui: &mut Ui, words: &ParagraphDialogWords) { let every = [ (ParagraphAlign::Left, &words.left), @@ -594,9 +753,13 @@ impl ParagraphDialog { fn indentation(&mut self, ui: &mut Ui, scope: &Scope<'_>, valid: &Cell) { let words = scope.words; - self.field(ui, scope, Row::BeforeText, &words.before_text, valid); + // Mirrored indents are measured from the inside and outside edges. + let mirrored = self.format.mirror_indents == Some(Some(true)); + let before = if mirrored { &words.inside } else { &words.before_text }; + self.field(ui, scope, Row::BeforeText, before, valid); if self.format.after_text.is_some() { - self.field(ui, scope, Row::AfterText, &words.after_text, valid); + let after = if mirrored { &words.outside } else { &words.after_text }; + self.field(ui, scope, Row::AfterText, after, valid); } let entries = [ Entry::new(SpecialIndent::None, words.special_none.clone()), @@ -651,22 +814,55 @@ impl ParagraphDialog { } } +/// A check box over a value that may differ between paragraphs: it shows mixed while `None`, and a click makes it +/// `Some`. Returns the click's value. +fn check(ui: &mut Ui, label: &Label, value: Option) -> Option { + let shown = value.map_or(Mixed::Mixed, Mixed::Same); + Checkbox::new(Bind::given(shown)).label(label.clone()).show(ui).value().copied() +} + +/// [`check`] writing a click into `slot`. +fn toggle(ui: &mut Ui, label: &Label, slot: &mut Option) { + if let Some(on) = check(ui, label, *slot) { + *slot = Some(on); + } +} + +/// The dialog's values as automation sees them: the format's fields and the page shown. +#[derive(serde::Serialize, serde::Deserialize)] +struct JsonFields { + #[serde(flatten)] + format: ParagraphFormat, + tab: ParagraphTab, +} + impl ParagraphDialog { /// OK files its answer for the app to accept or refuse before the dialog closes. #[must_use] - pub fn held_ok(self) -> Self { - todo!("dg.F12") + pub fn held_ok(mut self) -> Self { + self.hold = true; + self } /// The answer OK filed, once, for the app to judge. pub fn take_ok(&mut self) -> Option { - todo!("dg.F12") + self.held.take() } /// The app's answer to the filed answer: `Ok` closes the dialog with it, `Err` shows the reason and enables OK. pub fn answer_ok(&mut self, answer: Result<(), Label>) { - let _ = answer; - todo!("dg.F12") + self.held.answer(answer); + } + + /// Files `answer` and keeps the dialog open when OK is held; a plain dialog closes with it. + fn settle(&mut self, answer: ParagraphAnswer) -> Option { + if !self.hold { + return Some(answer); + } + if !self.held.is_waiting() { + self.held.file(answer); + } + None } } @@ -678,16 +874,22 @@ impl StackDialog for ParagraphDialog { } fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + if let Some(answer) = self.held.finish() { + return Some(DialogResult::Ok(answer)); + } let env = Env::of(ui); let words = env.words::(); let common = env.words::(); let units = env.units(); let scope = Scope { words: &words, units: &units }; let valid = Cell::new(self.out_of_range().is_empty()); + let waiting = self.held.is_waiting(); + let refused = self.held.refusal().map(|(reason, answer)| (reason.clone(), answer.format.clone())); + let unchanged = Cell::new(true); let buttons = [ - FooterButton::new(common.ok.clone(), DialogRole::Accept), + FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(self.hold), FooterButton::new(common.cancel.clone(), DialogRole::Cancel), - FooterButton::new(words.tabs.clone(), DialogRole::Other), + FooterButton::new(words.tabs.clone(), DialogRole::Other).stays_open(self.hold), ]; let shown = Dialog::new(words.title.clone()) .side_buttons(true) @@ -695,21 +897,57 @@ impl StackDialog for ParagraphDialog { .settle_buttons(|_, buttons| { for (at, button) in buttons.iter_mut().enumerate() { if at != CANCEL { - button.set_enabled(valid.get()); + button.set_enabled(valid.get() && !waiting); } } }) - .show(ui, |ui, _| self.body(ui, &scope, &valid)); + .refusal(|| refused.as_ref().filter(|_| unchanged.get()).map(|(reason, _)| reason.clone())) + .show(ui, |ui, _| { + self.body(ui, &scope, &valid); + if let Some((_, format)) = &refused { + unchanged.set(*format == self.format); + } + }); + if refused.is_some() && !unchanged.get() { + self.held.clear_refusal(); + } let tabs = shown.output.picked == Some(TABS); match shown.output.result(|| tabs) { - Some(DialogResult::Ok(open_tabs)) if valid.get() => Some(DialogResult::Ok(self.answer(open_tabs))), + Some(DialogResult::Ok(open_tabs)) if valid.get() => { + let answer = self.answer(open_tabs); + self.settle(answer).map(DialogResult::Ok) + } Some(DialogResult::Cancel) => Some(DialogResult::Cancel), _ => None, } } fn confirm(&mut self, _: &egui::Context) -> Option { - self.out_of_range().is_empty().then(|| self.answer(false)) + if let Some(answer) = self.held.finish() { + return Some(answer); + } + if !self.out_of_range().is_empty() { + return None; + } + let answer = self.answer(false); + self.settle(answer) + } + + fn held_state(&self) -> Option { + self.held.state() + } + + fn json_fields(&self) -> Option { + serde_fields(&JsonFields { format: self.format.clone(), tab: self.tab }) + } + + fn set_json_field(&mut self, _: &egui::Context, field: &str, value: serde_json::Value) -> Result<(), String> { + let mut fields = JsonFields { format: self.format.clone(), tab: self.tab }; + set_serde_field(&mut fields, field, value)?; + self.format = fields.format; + self.tab = fields.tab; + self.held.clear_refusal(); + Ok(()) } } diff --git a/crates/text/src/ui/character/stories.rs b/crates/text/src/ui/character/stories.rs index 5a845053c..5e09df4e4 100644 --- a/crates/text/src/ui/character/stories.rs +++ b/crates/text/src/ui/character/stories.rs @@ -3,11 +3,12 @@ #[cfg(feature = "font-picker")] use super::FaceAxes; use super::{ - BaselinePosition, Caps, CharacterControls, CharacterValues, Kerning, Leading, LineSpacing, ParagraphAlign, ParagraphControls, ParagraphDialog, - ParagraphFormat, ParagraphPreview, ParagraphValues, SpacingKind, SpecialIndent, TextAlign, + AsianTypography, BaselinePosition, Caps, CharacterControls, CharacterValues, Kerning, Leading, LineBreakOptions, LineSpacing, ParagraphAlign, + ParagraphControls, ParagraphDialog, ParagraphFormat, ParagraphPreview, ParagraphTab, ParagraphValues, SpacingKind, SpecialIndent, TextAlign, }; use craft_theme::Rgba; use craft_ui::contract::Show as _; +use craft_ui::dialog::stories::hosted; use craft_ui::dialog::{DialogStack, StackDialog as _}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -116,6 +117,24 @@ fn indented() -> ParagraphFormat { space_after: Some(1.0), space_after_kind: SpacingKind::Lines, line_spacing: Some(LineSpacing::Exactly(20.0)), + direction: Some(Some(super::ParagraphDirection::LeftToRight)), + mirror_indents: Some(Some(false)), + breaks: Some(LineBreakOptions { + widow_control: Some(true), + keep_with_next: None, + keep_lines_together: Some(false), + page_break_before: Some(false), + suppress_line_numbers: Some(false), + dont_hyphenate: Some(true), + }), + asian: Some(AsianTypography { + kinsoku: Some(true), + word_wrap: Some(false), + overflow_punct: None, + top_line_punct: Some(true), + auto_space_de: Some(true), + auto_space_dn: Some(false), + }), ..ParagraphFormat::default() } } @@ -127,6 +146,16 @@ fn indents_and_spacing(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { StoryOutput::default() } +#[story(ParagraphDialog, covers = [], drive = Drive::Never)] +fn line_and_page_breaks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + hosted(ui, data, (), || ParagraphDialog::new(indented()).word(true).tab(ParagraphTab::LineAndPageBreaks)) +} + +#[story(ParagraphDialog, covers = [], drive = Drive::Never)] +fn asian_typography(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + hosted(ui, data, (), || ParagraphDialog::new(indented()).word(true).tab(ParagraphTab::AsianTypography)) +} + #[story(ParagraphPreview, covers = [Default], drive = Drive::Never)] fn preview(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { ParagraphPreview::new("Preview", &indented(), "Sample Text").show(ui).into() diff --git a/crates/text/src/ui/columns.rs b/crates/text/src/ui/columns.rs index 96f53191d..24f52f8c1 100644 --- a/crates/text/src/ui/columns.rs +++ b/crates/text/src/ui/columns.rs @@ -10,7 +10,7 @@ use craft_ui::contract::{ Bind, Common, Component, Cx, Entry, FieldLayout, MeasureCx, PaintUi, Props as _, Role, Show as _, ShowContainer as _, SideLabel, Sizing, Validity, clicked, }; -use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::Row; use craft_ui::pickers::Select; @@ -144,6 +144,9 @@ pub struct TextColumnsDialog { unit: DocUnit, /// The edited columns from before the running gesture: Escape restores them. draft: Option, + /// Whether OK files its result for the app to judge instead of closing. + hold: bool, + held: HeldAnswer>, } impl TextColumnsDialog { @@ -157,6 +160,8 @@ impl TextColumnsDialog { apply_choices: Vec::new(), unit: DocUnit::default(), draft: None, + hold: false, + held: HeldAnswer::new(), } } @@ -596,19 +601,30 @@ fn bare(caption: &str) -> &str { impl TextColumnsDialog { /// OK files its result for the app to accept or refuse before the dialog closes. #[must_use] - pub fn held_ok(self) -> Self { - todo!("dg.F12") + pub fn held_ok(mut self) -> Self { + self.hold = true; + self } /// The result OK filed, once, for the app to judge. pub fn take_ok(&mut self) -> Option> { - todo!("dg.F12") + self.held.take() } /// The app's answer to the filed result: `Ok` closes the dialog with it, `Err` shows the reason and enables OK. pub fn answer_ok(&mut self, answer: Result<(), Label>) { - let _ = answer; - todo!("dg.F12") + self.held.answer(answer); + } + + /// Files `changes` and keeps the dialog open when OK is held; a plain dialog closes with them. + fn settle(&mut self, changes: Option) -> Option> { + if !self.hold { + return Some(changes); + } + if !self.held.is_waiting() { + self.held.file(changes); + } + None } } @@ -621,26 +637,59 @@ impl StackDialog for TextColumnsDialog { } fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option>> { + if let Some(changes) = self.held.finish() { + return Some(DialogResult::Ok(changes)); + } let env = Env::of(ui); let words = env.words::(); let common = env.words::(); let units = env.units(); let valid = Cell::new(self.is_valid()); - let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; + let waiting = self.held.is_waiting(); + let refused = self.held.refusal().map(|(reason, changes)| (reason.clone(), changes.clone())); + let unchanged = Cell::new(true); + let buttons = [ + FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(self.hold), + FooterButton::new(common.cancel.clone(), DialogRole::Cancel), + ]; let shown = Dialog::new(words.title.clone()) .buttons(buttons) .settle_buttons(|_, buttons| { if let Some(ok) = buttons.first_mut() { - ok.set_enabled(valid.get()); + ok.set_enabled(valid.get() && !waiting); } }) - .show(ui, |ui, _| self.body(ui, &words, &units, &valid)); + .refusal(|| refused.as_ref().filter(|_| unchanged.get()).map(|(reason, _)| reason.clone())) + .show(ui, |ui, _| { + self.body(ui, &words, &units, &valid); + if let Some((_, changes)) = &refused { + unchanged.set(self.changes() == *changes); + } + }); + if refused.is_some() && !unchanged.get() { + self.held.clear_refusal(); + } match shown.output.result(|| self.changes()) { - Some(DialogResult::Ok(changes)) if valid.get() => Some(DialogResult::Ok(changes)), + Some(DialogResult::Ok(changes)) if valid.get() => self.settle(changes).map(DialogResult::Ok), Some(DialogResult::Cancel) => Some(DialogResult::Cancel), _ => None, } } + + fn confirm(&mut self, _: &egui::Context) -> Option> { + if let Some(changes) = self.held.finish() { + return Some(changes); + } + if !self.is_valid() { + return None; + } + let changes = self.changes(); + self.settle(changes) + } + + fn held_state(&self) -> Option { + self.held.state() + } } /// The preview's style: a sunken well holding a raised page with the columns' text lines. diff --git a/crates/text/src/ui/tabs_dialog.rs b/crates/text/src/ui/tabs_dialog.rs index 44c6ea629..29ac8366a 100644 --- a/crates/text/src/ui/tabs_dialog.rs +++ b/crates/text/src/ui/tabs_dialog.rs @@ -16,7 +16,7 @@ use craft_ui::buttons::Button; use craft_ui::contract::{ Bind, CollectionEvent, ColumnSpec, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, clicked, }; -use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id}; +use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id}; use craft_ui::form::Field; use craft_ui::layout_components::Row; use craft_ui::list::ListRow; @@ -28,7 +28,7 @@ use craft_ui::sections::{DialogRole, FooterButton}; use craft_ui::table::Table; use egui::Ui; use std::borrow::Cow; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; #[cfg(feature = "screen-testing")] mod stories; @@ -105,6 +105,9 @@ pub struct TabStopsDialog { draft: Option<(usize, f32)>, /// The selected row's Position field takes the focus the next time it shows: Set moves into the new stop. to_edit: bool, + /// Whether OK files its result for the app to judge instead of closing. + hold: bool, + held: HeldAnswer, } impl TabStopsDialog { @@ -121,6 +124,8 @@ impl TabStopsDialog { unit: DocUnit::default(), draft: None, to_edit: false, + hold: false, + held: HeldAnswer::new(), } } @@ -248,19 +253,35 @@ impl ItemSource for Stops<'_> {} impl TabStopsDialog { /// OK files its result for the app to accept or refuse before the dialog closes. #[must_use] - pub fn held_ok(self) -> Self { - todo!("dg.F12") + pub fn held_ok(mut self) -> Self { + self.hold = true; + self } /// The result OK filed, once, for the app to judge. pub fn take_ok(&mut self) -> Option { - todo!("dg.F12") + self.held.take() } /// The app's answer to the filed result: `Ok` closes the dialog with it, `Err` shows the reason and enables OK. pub fn answer_ok(&mut self, answer: Result<(), craft_ui::runtime::env::Label>) { - let _ = answer; - todo!("dg.F12") + self.held.answer(answer); + } + + /// Files `result` and keeps the dialog open when OK is held; a plain dialog closes with it. + fn settle(&mut self, result: TabStopsResult) -> Option { + if !self.hold { + return Some(result); + } + if !self.held.is_waiting() { + self.held.file(result); + } + None + } + + /// Whether the stops, the cleared positions and the interval are those of `result`. + fn matches(&self, result: &TabStopsResult) -> bool { + self.stops == result.stops && self.cleared == result.cleared && self.default_interval == result.default_interval } } @@ -272,13 +293,53 @@ impl StackDialog for TabStopsDialog { } fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + if let Some(result) = self.held.finish() { + return Some(DialogResult::Ok(result)); + } let env = Env::of(ui); let words = env.words::(); let common = env.words::(); let units = env.units(); - let buttons = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]; - let shown = Dialog::new(words.title.clone()).buttons(buttons).show(ui, |ui, _| self.body(ui, &words, &units)); - shown.output.result(|| self.result()) + let waiting = self.held.is_waiting(); + let refused = self.held.refusal().map(|(reason, result)| (reason.clone(), result.clone())); + let unchanged = Cell::new(true); + let buttons = [ + FooterButton::new(common.ok.clone(), DialogRole::Accept).stays_open(self.hold), + FooterButton::new(common.cancel.clone(), DialogRole::Cancel), + ]; + let shown = Dialog::new(words.title.clone()) + .buttons(buttons) + .settle_buttons(|_, buttons| { + if let Some(ok) = buttons.first_mut() { + ok.set_enabled(!waiting); + } + }) + .refusal(|| refused.as_ref().filter(|_| unchanged.get()).map(|(reason, _)| reason.clone())) + .show(ui, |ui, _| { + self.body(ui, &words, &units); + if let Some((_, result)) = &refused { + unchanged.set(self.matches(result)); + } + }); + if refused.is_some() && !unchanged.get() { + self.held.clear_refusal(); + } + match shown.output.result(|| self.result()) { + Some(DialogResult::Ok(result)) => self.settle(result).map(DialogResult::Ok), + other => other, + } + } + + fn confirm(&mut self, _: &egui::Context) -> Option { + if let Some(result) = self.held.finish() { + return Some(result); + } + let result = self.result(); + self.settle(result) + } + + fn held_state(&self) -> Option { + self.held.state() } } @@ -344,6 +405,7 @@ impl TabStopsDialog { let edits: RefCell> = RefCell::new(Vec::new()); let position_ids: RefCell> = RefCell::new(Vec::new()); let out = Table::::new(words.title.clone(), columns.clone()) + .empty(words.no_stops.clone()) .select(SelectMode::Single) .min_rows(1) .max_rows(6) diff --git a/crates/text/tests/it/paragraph.rs b/crates/text/tests/it/paragraph.rs new file mode 100644 index 000000000..0e7006d75 --- /dev/null +++ b/crates/text/tests/it/paragraph.rs @@ -0,0 +1,46 @@ +//! The Word Paragraph dialog's pages: a check box whose paragraphs differ stays mixed across page switches until clicked. + +use craft_behavior::Mixed; +use craft_text::ui::character::{AsianTypography, LineBreakOptions, ParagraphDialog, ParagraphFormat, ParagraphTab}; +use craft_ui::dialog::{DialogStack, StackDialog as _}; +use craft_ui::testing::{Fixture, trial}; +use std::cell::RefCell; +use std::rc::Rc; + +fn toggled(fixture: &Fixture, label: &str) -> Option> { + let target = fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown")); + fixture.tree().toggled_of(target.node) +} + +#[trial] +fn word_paragraph_tabs_leave_mixed_boxes_unset_until_clicked() { + let mut format = ParagraphFormat::default(); + format.breaks = Some(LineBreakOptions::default()); + format.asian = Some(AsianTypography::default()); + let dialog = Rc::new(RefCell::new(ParagraphDialog::new(format).word(true).held_ok().tab(ParagraphTab::LineAndPageBreaks))); + let shown = dialog.clone(); + let mut fixture = Fixture::new(move |ui| { + let _ = shown.borrow_mut().show(ui, &DialogStack::default()); + }); + fixture.idle(30); + assert!(matches!(toggled(&fixture, "Keep with next"), Some(Mixed::Mixed)), "a box whose paragraphs differ is shown mixed"); + + let asian = fixture.by_label("Asian Typography").expect("the Asian Typography tab is shown"); + fixture.click(&asian).idle(4); + assert!(matches!(toggled(&fixture, "Apply Asian line-breaking rules (kinsoku)"), Some(Mixed::Mixed)), "the other page's box is mixed too"); + let breaks = fixture.by_label("Line and Page Breaks").expect("the Line and Page Breaks tab is shown"); + fixture.click(&breaks).idle(4); + assert!(matches!(toggled(&fixture, "Keep with next"), Some(Mixed::Mixed)), "switching pages does not decide a mixed box"); + + let keep = fixture.by_label("Keep with next").expect("the box is shown"); + fixture.click(&keep).idle(4); + assert!(matches!(toggled(&fixture, "Keep with next"), Some(Mixed::Same(true))), "a click checks the box"); + + let ok = fixture.by_label("OK").expect("OK is shown"); + fixture.click(&ok).idle(4); + let answer = dialog.borrow_mut().take_ok().expect("OK filed its answer"); + let breaks = answer.format.breaks.expect("the page is answered"); + assert_eq!(breaks.keep_with_next, Some(true)); + assert_eq!(breaks.widow_control, None, "a box left alone stays unset"); + assert_eq!(answer.format.asian.expect("the page is answered").kinsoku, None); +} diff --git a/crates/text/tests/it/tabs.rs b/crates/text/tests/it/tabs.rs index 436f50834..bffa2b65b 100644 --- a/crates/text/tests/it/tabs.rs +++ b/crates/text/tests/it/tabs.rs @@ -1,8 +1,11 @@ -//! The Tabs dialog's focus: it opens on the default interval, and Set moves into the new stop's row. +//! The Tabs dialog: its focus (it opens on the default interval, Set moves into the new stop's row), staged edits, Set and +//! Clear, and a held OK. -use craft_text::ui::tabs_dialog::TabStopsDialog; -use craft_ui::dialog::{DialogStack, StackDialog as _}; +use craft_text::ui::ruler::{TabAlign, TabLeader, TabStop}; +use craft_text::ui::tabs_dialog::{TabStopsDialog, TabStopsResult}; +use craft_ui::dialog::{DialogResult, DialogStack, StackDialog as _}; use craft_ui::testing::{Fixture, trial}; +use egui::{Key, Modifiers}; use std::cell::RefCell; use std::rc::Rc; @@ -12,6 +15,35 @@ fn focused<'a>(fixture: &Fixture, labels: &[&'a str]) -> Option<&'a str> { labels.iter().copied().find(|label| fixture.by_label(label).is_some_and(|target| target.node == focused)) } +/// A fixture showing `dialog`, and where the result of a closing OK lands. +fn shown(dialog: TabStopsDialog) -> (Fixture, Rc>, Rc>>) { + let dialog = Rc::new(RefCell::new(dialog)); + let result = Rc::new(RefCell::new(None)); + let (shown, landed) = (dialog.clone(), result.clone()); + let mut fixture = Fixture::new(move |ui| { + if let Some(DialogResult::Ok(answer)) = shown.borrow_mut().show(ui, &DialogStack::default()) { + *landed.borrow_mut() = Some(answer); + } + }); + fixture.idle(30); + (fixture, dialog, result) +} + +fn press(fixture: &mut Fixture, label: &str) { + let target = fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown")); + fixture.click(&target).idle(4); +} + +fn stop(position: f32, align: TabAlign, leader: TabLeader) -> TabStop { + TabStop { position, align, leader } +} + +/// Types `text` into the first row's position field and leaves the field, which ends the edit. +fn retype_first_position(fixture: &mut Fixture, text: &str) { + press(fixture, "Tab stop position:"); + fixture.key(Key::A, Modifiers::COMMAND).type_text(text).key(Key::Tab, Modifiers::NONE).idle(4); +} + #[trial] fn the_dialog_opens_on_the_default_interval_and_set_moves_into_the_new_stop() { let dialog = Rc::new(RefCell::new(TabStopsDialog::new(Vec::new(), 36.0))); @@ -32,3 +64,67 @@ fn the_dialog_opens_on_the_default_interval_and_set_moves_into_the_new_stop() { let value = fixture.tree().value_of(key).unwrap_or_default(); assert!(value.contains("72"), "the focus is in the new row's field, at 72 pt: {value:?}"); } + +#[trial] +fn editing_a_stop_position_stages_a_clear_and_a_set_and_the_selection_follows_it() { + let stops = vec![stop(72.0, TabAlign::Right, TabLeader::Dot), stop(144.0, TabAlign::Left, TabLeader::None)]; + + let (mut fixture, _, result) = shown(TabStopsDialog::new(stops.clone(), 36.0)); + retype_first_position(&mut fixture, "108"); + press(&mut fixture, "OK"); + let moved = result.borrow().clone().expect("OK answered"); + assert_eq!( + moved.stops, + vec![stop(108.0, TabAlign::Right, TabLeader::Dot), stop(144.0, TabAlign::Left, TabLeader::None)], + "the moved stop keeps its alignment and leader" + ); + assert_eq!(moved.cleared, vec![72.0], "the old position is cleared"); + + let (mut fixture, _, result) = shown(TabStopsDialog::new(stops, 36.0)); + retype_first_position(&mut fixture, "144"); + press(&mut fixture, "OK"); + let merged = result.borrow().clone().expect("OK answered"); + assert_eq!(merged.stops, vec![stop(144.0, TabAlign::Right, TabLeader::Dot)], "two stops on one position merge, the edited one winning"); + assert_eq!(merged.cleared, vec![72.0]); +} + +#[trial] +fn set_adds_the_next_free_multiple_and_clear_keeps_the_position_cleared() { + let stops = vec![stop(72.0, TabAlign::Right, TabLeader::None), stop(144.0, TabAlign::Left, TabLeader::None)]; + let (mut fixture, _, result) = shown(TabStopsDialog::new(stops, 36.0)); + press(&mut fixture, "Set"); + press(&mut fixture, "Clear"); + press(&mut fixture, "Set"); + press(&mut fixture, "OK"); + let answer = result.borrow().clone().expect("OK answered"); + let positions: Vec = answer.stops.iter().map(|stop| stop.position).collect(); + assert_eq!(positions, vec![72.0, 144.0, 216.0], "Set steps past the last stop, and past a position that was cleared"); + assert_eq!(answer.cleared, vec![180.0], "Clear keeps the position to be cleared"); +} + +#[trial] +fn a_held_ok_stays_open_until_answered_and_a_refusal_shows_until_a_value_changes() { + let (mut fixture, dialog, result) = shown(TabStopsDialog::new(Vec::new(), 36.0).held_ok()); + press(&mut fixture, "OK"); + assert!(result.borrow().is_none(), "a held OK does not close the dialog"); + let ok = fixture.by_label("OK").expect("OK is shown"); + assert!(fixture.tree().is_disabled_key(ok.node), "OK waits disabled for the answer"); + assert!(dialog.borrow_mut().take_ok().is_some(), "the filed result reaches the app once"); + assert!(dialog.borrow_mut().take_ok().is_none()); + + dialog.borrow_mut().answer_ok(Err("Not allowed".into())); + fixture.idle(4); + assert!(fixture.by_label("Not allowed").is_some(), "the refusal is shown"); + let ok = fixture.by_label("OK").expect("OK is shown"); + assert!(!fixture.tree().is_disabled_key(ok.node), "a refusal enables OK again"); + + press(&mut fixture, "Set"); + assert!(fixture.by_label("Not allowed").is_none(), "an edit ends the refusal"); + + press(&mut fixture, "OK"); + assert!(dialog.borrow_mut().take_ok().is_some()); + dialog.borrow_mut().answer_ok(Ok(())); + fixture.idle(4); + let answer = result.borrow().clone().expect("the accepted answer closes the dialog"); + assert_eq!(answer.stops.len(), 1, "the dialog closes with the answer it filed"); +}