diff --git a/crates/pages/src/setup.rs b/crates/pages/src/setup.rs index 829d2e9fa..9dd14752f 100644 --- a/crates/pages/src/setup.rs +++ b/crates/pages/src/setup.rs @@ -232,12 +232,12 @@ pub enum GridKind { impl GridKind { /// Whether the characters-per-line count applies (`LinesAndChars` and `SnapToChars`). pub fn chars_enabled(self) -> bool { - todo!("dg.F18") + matches!(self, GridKind::LinesAndChars | GridKind::SnapToChars) } /// Whether the lines-per-page count applies (every kind but `None`). pub fn lines_enabled(self) -> bool { - todo!("dg.F18") + self != GridKind::None } } diff --git a/crates/pages/src/ui/setup.rs b/crates/pages/src/ui/setup.rs index 6b6895a0e..531895465 100644 --- a/crates/pages/src/ui/setup.rs +++ b/crates/pages/src/ui/setup.rs @@ -29,7 +29,7 @@ use craft_ui::text::NumberField; use egui::{Response, Ui}; use crate::setup::{ - MARGIN_PRESETS, MAX_PAGE_SIDE, MIN_PAGE_SIDE, MarginPreset, Orientation, PAPER_SIZES, PageSetup, PageVerticalAlign, PaperSize, paper_named, + DocumentGrid, GridKind, MARGIN_PRESETS, MAX_GRID_COUNT, MAX_PAGE_SIDE, MIN_PAGE_SIDE, MarginPreset, Orientation, PAPER_SIZES, PageSetup, PageVerticalAlign, PaperSize, paper_named, }; /// The margin and paper fields' scrub step, page points (WordCraft's 0.05 in). @@ -75,6 +75,13 @@ craft_ui::words! { section_direction: "pageSetupDialog.sectionDirection" = "Section direction"; left_to_right: "pageSetupDialog.leftToRight" = "Left-to-right"; right_to_left: "pageSetupDialog.rightToLeft" = "Right-to-left"; + grid: "pageSetupDialog.grid" = "Document grid"; + grid_none: "pageSetupDialog.gridNone" = "No grid"; + grid_lines: "pageSetupDialog.gridLines" = "Line grid only"; + grid_lines_and_chars: "pageSetupDialog.gridLinesAndChars" = "Line and character grid"; + grid_snap_to_chars: "pageSetupDialog.gridSnapToChars" = "Text snaps to character grid"; + chars_per_line: "pageSetupDialog.charsPerLine" = "Characters per line"; + lines_per_page: "pageSetupDialog.linesPerPage" = "Lines per page"; margins_dont_fit: "pageSetupDialog.marginsDontFit" = "The margins don't fit on a page this size; make the margins smaller first."; /// `{name}` is the preset's name and `{size}` its margin on every side. uniform_preset: template "pageSetupDialog.uniformPreset" = "{name} {size} all"; @@ -383,6 +390,77 @@ impl Rows<'_> { .unwrap_or(true) } + /// The Document grid section, shown while the setup has a grid: the kind, then the two counts the kind enables. + /// `false` while a count's text is not a number. + fn grid(&self, ui: &mut Ui, form: &mut FormCx<'_, '_>, setup: &mut PageSetup) -> bool { + let Some(grid) = setup.grid else { return true }; + let words = self.words; + section(ui, &words.grid, |ui| { + let after = SideLabel::new().layout(FieldLayout::After); + let group = RadioGroup::new(words.grid.clone(), Bind::given(grid.kind)).show(ui, |ui, cx| { + cx.labelled(ui, "none", words.grid_none.clone(), after.clone(), Radio::new(GridKind::None)); + cx.labelled(ui, "lines", words.grid_lines.clone(), after.clone(), Radio::new(GridKind::Lines)); + cx.labelled(ui, "linesAndChars", words.grid_lines_and_chars.clone(), after.clone(), Radio::new(GridKind::LinesAndChars)); + cx.labelled(ui, "snapToChars", words.grid_snap_to_chars.clone(), after.clone(), Radio::new(GridKind::SnapToChars)); + }); + if let (Some(kind), Some(grid)) = (group.output.value().copied(), setup.grid.as_mut()) { + grid.kind = kind; + } + let kind = setup.grid.map_or(grid.kind, |grid| grid.kind); + let chars = self.count( + ui, + form, + setup, + ("chars", words.chars_per_line.clone(), kind.chars_enabled()), + |grid| grid.chars_per_line, + |grid, count| grid.chars_per_line = count, + ); + let lines = self.count( + ui, + form, + setup, + ("lines", words.lines_per_page.clone(), kind.lines_enabled()), + |grid| grid.lines_per_page, + |grid, count| grid.lines_per_page = count, + ); + chars && lines + }) + .unwrap_or(true) + } + + /// One count of the grid, a whole number from 1 to [`MAX_GRID_COUNT`] that `enabled` lets the user edit; `key`, + /// `label` and `enabled` are given as one tuple. `false` while the field's text is not a number. + fn count( + &self, + ui: &mut Ui, + form: &mut FormCx<'_, '_>, + setup: &mut PageSetup, + (key, label, enabled): (&'static str, Label, bool), + get: fn(&DocumentGrid) -> u32, + set: fn(&mut DocumentGrid, u32), + ) -> bool { + let Some(grid) = setup.grid else { return true }; + let shown = f64::from(get(&grid)); + let codec = NumberCodec::new(self.units.reader(None), 0); + let field = Field::new(label.clone()) + .id_salt(key) + .show(ui, |ui, _| { + NumberField::new(label.clone(), Bind::given(Some(shown))) + .codec(codec.clone()) + .range(1.0..=f64::from(MAX_GRID_COUNT)) + .enabled(enabled) + .show(ui) + }) + .inner; + let Some(field) = field else { return true }; + apply(form, setup, &field.edit, |next, value| { + if let Some(grid) = next.grid.as_mut() { + set(grid, value.round().clamp(1.0, f64::from(MAX_GRID_COUNT)) as u32); + } + }); + !field.edit.unparsed + } + /// The Headers and footers section: vertical alignment, odd and even pages, first page. fn layout(&self, ui: &mut Ui, setup: &mut PageSetup) { let words = self.words; @@ -445,6 +523,8 @@ fn section(ui: &mut Ui, title: &Label, mut body: impl FnMut(&mut Ui) -> R) -> /// - Paper: a list of [`papers`](PageSetupDialog::papers) plus Custom size, and Width and Height /// ([`MIN_PAGE_SIDE`] to [`MAX_PAGE_SIDE`]); Custom size stays chosen while the numbers match a name; a typed size /// wider than tall turns the orientation ([`PageSetup::set_size`]). +/// - Document grid, while the setup has a [`grid`](PageSetup::grid): its kind and the characters per line and lines per +/// page the kind enables. /// - With [`layout`](PageSetupDialog::layout): Vertical alignment, Different Odd & Even Pages, Different First Page; /// with [`direction`](PageSetupDialog::direction): Section direction. /// - A length or count gesture previews in the setup and the cancel of the gesture restores the whole setup from @@ -476,7 +556,6 @@ pub struct PageSetupDialog<'a> { open: Option>, /// OK files the setup in the held answer and the dialog stays open until the app answers it (`FormDialog::held`). #[prop(into)] - #[allow(dead_code)] // P3(dialogs-w6): dg.F18 held: Option<&'a mut craft_ui::dialog::HeldAnswer>, } @@ -497,7 +576,7 @@ impl<'a> PageSetupDialog<'a> { /// Shows the dialog. pub fn show(self, ui: &mut Ui) -> FormOutput { - let PageSetupDialog { setup, papers, unit, document_setup, layout, direction, open, .. } = self; + let PageSetupDialog { setup, papers, unit, document_setup, layout, direction, open, held } = self; let env = Env::of(ui); let words = env.words::(); let rows = Rows { words: &words, units: env.units(), unit }; @@ -506,18 +585,22 @@ impl<'a> PageSetupDialog<'a> { if let Some(open) = open { dialog = dialog.opened(open); } + if let Some(held) = held { + dialog = dialog.held(held); + } dialog.show(ui, |ui, form, setup| { let margins = rows.margins(ui, form, setup, document_setup); rows.orientation(ui, setup); let pages = rows.pages(ui, form, setup, document_setup); let paper = rows.paper(ui, form, setup, papers); + let grid = rows.grid(ui, form, setup); if layout { rows.layout(ui, setup); } if direction { rows.direction(ui, setup); } - margins && pages && paper + margins && pages && paper && grid }) } } diff --git a/crates/pages/src/ui/setup/stories.rs b/crates/pages/src/ui/setup/stories.rs index 9f92b0ce5..4d60a34cf 100644 --- a/crates/pages/src/ui/setup/stories.rs +++ b/crates/pages/src/ui/setup/stories.rs @@ -2,9 +2,11 @@ use super::{PageLayoutMenus, PageSetupDialog}; use crate::setup::PageSetup; -use craft_ui::buttons::IconButton; -use craft_ui::contract::{Bind, Props as _, Show as _}; -use craft_ui::runtime::env::UnitKind; +use crate::setup::{DocumentGrid, GridKind}; +use craft_ui::buttons::{Button, IconButton}; +use craft_ui::contract::{Bind, Props as _, Show as _, clicked}; +use craft_ui::dialog::HeldAnswer; +use craft_ui::runtime::env::{Label, UnitKind}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -23,6 +25,41 @@ fn document_setup(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { StoryOutput::default() } +/// A setup with a line and character grid. +fn gridded() -> PageSetup { + PageSetup { grid: Some(DocumentGrid::new(GridKind::LinesAndChars, 40, 30)), ..PageSetup::default() } +} + +/// The dialog over a setup with a Document grid, opened by its button; the kind radios switch which counts apply. +#[story(PageSetupDialog<'static>, covers = [], drive = Drive::Never)] +fn page_setup_grid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut open = *data.value("open", false); + if clicked(&Button::new("Page Setup\u{2026}").show(ui)) { + open = true; + } + let setup = data.value("setup", gridded()); + PageSetupDialog::new(Bind::bound(setup)).opened(Bind::bound(&mut open)).show(ui); + *data.value("open", false) = open; + StoryOutput::default() +} + +/// The host refuses every OK, so the dialog stays open with the reason under its fields. +#[story(PageSetupDialog<'static>, covers = [], drive = Drive::Never)] +fn page_setup_refused(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut open = *data.value("open", false); + if clicked(&Button::new("Page Setup\u{2026}").show(ui)) { + open = true; + } + let state = data.note("refused", (gridded(), HeldAnswer::::new())); + let (setup, held) = (&mut state.0, &mut state.1); + PageSetupDialog::new(Bind::bound(setup)).opened(Bind::bound(&mut open)).held(&mut *held).show(ui); + if held.take().is_some() { + held.answer(Err(Label::from("This document cannot take a grid.".to_owned()))); + } + *data.value("open", false) = open; + StoryOutput::default() +} + #[story(PageLayoutMenus<'static>, covers = [Open], drive = Drive::Never)] fn margins_menu(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let setup = data.value("setup", PageSetup::default()).clone(); diff --git a/crates/pages/src/ui/table/edges.rs b/crates/pages/src/ui/table/edges.rs index d780300c6..fef96ea56 100644 --- a/crates/pages/src/ui/table/edges.rs +++ b/crates/pages/src/ui/table/edges.rs @@ -11,7 +11,8 @@ use craft_ui::primitives::{PaintShape, StrokeWidth}; use craft_ui::runtime::env::Label; use craft_ui::runtime::focus::{ActivateKeys, KeyUse}; use craft_ui::style::{ComponentStyle, Flags, FocusLook, Stateful, StyleColor, StyleCx, SurfaceKind, SurfaceLook}; -use egui::{CornerRadius, Pos2, Rect, Vec2, pos2}; +use craft_ui::style::DataColor; +use egui::{Color32, CornerRadius, Pos2, Rect, Vec2, pos2}; const EDGE: PartKey = PartKey::new("edge"); const SQUARE: PartKey = PartKey::new("square"); @@ -196,7 +197,6 @@ pub struct EdgePicker<'a> { paragraph: bool, /// How the picture is drawn: the proxy diagram, or a sample of the borders on text, a paragraph or a page. #[prop] - #[allow(dead_code)] // P3(dialogs-w6): dg.F19 look: EdgeLook, } @@ -364,7 +364,7 @@ impl Component for EdgePicker<'_> { let lines = edge_lines(rect, inset); cx.part(SQUARE, rect).sense(Sense::CLICK).pointer_only("each line is a part of its own: the arrows move between them and Space toggles"); let chosen = cx.value().copied().unwrap_or_default(); - for key in Self::visible(self.paragraph) { + for key in self.keys() { let part = cx.part(Self::part(key), Self::band(&lines, key, inset)).sense(Sense::CLICK | Sense::FOCUS).focusable(); if chosen.get(key) { part.flags(Flags::CHECKED); @@ -379,7 +379,7 @@ impl Component for EdgePicker<'_> { fn update(&mut self, cx: &mut Cx<'_, Self>) { let Some(¤t) = cx.value() else { return }; - let keys = Self::visible(self.paragraph); + let keys = self.keys(); let lines = edge_lines(cx.rect, cx.style.inset); // A click lands on a line's part or, off every line, on the square; the line it picks is the nearest. let click = @@ -406,19 +406,47 @@ impl Component for EdgePicker<'_> { fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { let words = cx.words::(); - let keys = Self::visible(self.paragraph); + let keys = self.keys(); let lines = edge_lines(cx.rect, cx.style.inset); for (at, &key) in keys.iter().enumerate() { let node = access.node(Self::part(key), Role::CHECK_BOX); - node.name = Name::Text(cx.env.resolve(Self::edge_label(&words, key, self.paragraph)).as_str().to_owned()); + node.name = Name::Text(cx.env.resolve(Self::edge_label(&words, key, self.paragraph_edges())).as_str().to_owned()); node.position = Some(SetPosition::new(at).of(keys.len())); node.bounds(Self::band(&lines, key, cx.style.inset)); } } fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + match self.look { + EdgeLook::Sample { area, fill } => self.paint_sample(ui, cx, area, fill), + _ => self.paint_proxy(ui, cx), + } + } + + fn finish(self, cx: Cx<'_, Self>) -> EditResponse { + cx.edit_response() + } +} + +impl EdgePicker<'_> { + /// Whether the lines are a paragraph's: the flag, or a paragraph sample. + fn paragraph_edges(&self) -> bool { + self.paragraph || matches!(self.look, EdgeLook::Sample { area: SampleArea::Paragraph, .. }) + } + + /// The lines this picker has, for its parts, hit bands, names and paint alike: a text or page sample has only the + /// four outer lines, so no line exists that is not drawn. + fn keys(&self) -> Vec { + match self.look { + EdgeLook::Sample { area: SampleArea::Text | SampleArea::Page, .. } => OUTER.to_vec(), + _ => Self::visible(self.paragraph_edges()), + } + } + + /// The six-line diagram. + fn paint_proxy(&self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let Some(&edges) = cx.value() else { return }; - let keys = Self::visible(self.paragraph); + let keys = self.keys(); let lines = edge_lines(cx.rect, cx.style.inset); let draw = ui.draw(); draw.fill(&PaintShape::Rect(cx.rect.shrink(cx.style.inset), CornerRadius::ZERO), cx.style.fill); @@ -433,7 +461,46 @@ impl Component for EdgePicker<'_> { } } - fn finish(self, cx: Cx<'_, Self>) -> EditResponse { - cx.edit_response() + /// The chosen borders on a sample of `area`: grey bars stand for the text, and the lines sit where the hit bands + /// are, so the pointer and the keys act on what is drawn. A text run and a page have no inside lines; the + /// paragraph keeps its Between. + fn paint_sample(&self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>, area: SampleArea, fill: Option) { + let Some(&edges) = cx.value() else { return }; + let keys = self.keys(); + let lines = edge_lines(cx.rect, cx.style.inset); + let sheet = cx.rect.shrink(cx.style.inset); + let draw = ui.draw(); + draw.fill(&PaintShape::Rect(sheet, CornerRadius::ZERO), cx.style.fill); + if let Some(fill) = fill { + draw.data_fill(&PaintShape::Rect(sheet, CornerRadius::ZERO), DataColor::new(Color32::from(fill))); + } + // An even count of bars leaves the middle, where the inside line runs, between two of them. + let (bars, across) = match area { + SampleArea::Text => (1_usize, 0.5_f32), + SampleArea::Paragraph => (2, 0.7), + SampleArea::Page => (4, 0.7), + }; + let slot = sheet.height() / (2 * bars + 1) as f32; + let width = sheet.width() * across; + let bar_color = cx.resolve(&cx.style.off); + for bar in 0..bars { + let top = sheet.top() + slot * (2 * bar + 1) as f32; + let left = sheet.center().x - width / 2.0; + let rect = Rect::from_min_size(pos2(left, top), Vec2::new(width, slot)); + draw.fill(&PaintShape::Rect(rect, CornerRadius::ZERO), bar_color); + } + let hovered = cx.hover_pos(SQUARE).and_then(|p| line_at(&lines, &keys, p, cx.style.inset)); + for key in keys { + let chosen = edges.get(key); + // A line not chosen shows only under the pointer, so the sample never looks bordered without a choice. + if !chosen && hovered != Some(key) { + continue; + } + let (a, b) = lines[key as usize]; + let (width, color) = + if chosen { (StrokeWidth::Thick, cx.resolve(&cx.style.on)) } else { (StrokeWidth::Thin, cx.resolve(&cx.style.off)) }; + let width = if hovered == Some(key) && chosen { StrokeWidth::Heavy } else { width }; + draw.stroke(&PaintShape::Path(vec![a, b]), width, color); + } } } diff --git a/crates/pages/src/ui/table/stories.rs b/crates/pages/src/ui/table/stories.rs index 9ebebdf3c..718b1f7d8 100644 --- a/crates/pages/src/ui/table/stories.rs +++ b/crates/pages/src/ui/table/stories.rs @@ -9,7 +9,7 @@ use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::Ui; use super::{ - BorderEdges, CellAlign, CellSelectionOverlay, EdgeKey, EdgePicker, RowHeight, TableGeometry, TableProperties, TableSizePicker, TableValues, + BorderEdges, CellAlign, CellSelectionOverlay, EdgeKey, EdgeLook, EdgePicker, RowHeight, SampleArea, TableGeometry, TableProperties, TableSizePicker, TableValues, TextDirection, }; @@ -75,6 +75,28 @@ fn edge_picker_paragraph(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { EdgePicker::new("Paragraph borders", Bind::bound(data.value("paragraph", mixed_edges()))).paragraph().show(ui).into() } +/// The borders drawn as a sample on a text run, a paragraph (with a fill) and a page. +#[story(EdgePicker<'static>, covers = [], drive = Drive::Never)] +fn edge_picker_sample(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let (mut text, mut paragraph, mut page) = *data.value("sample", (outer_edges(), mixed_edges(), outer_edges())); + let tint = craft_theme::Srgba { r: 1.0, g: 0.95, b: 0.7, a: 1.0 }; + let shown = Row::new() + .show(ui, |ui, _| { + let first = + EdgePicker::new("Text borders", Bind::bound(&mut text)).look(EdgeLook::Sample { area: SampleArea::Text, fill: None }).show(ui); + EdgePicker::new("Paragraph borders", Bind::bound(&mut paragraph)) + .paragraph() + .look(EdgeLook::Sample { area: SampleArea::Paragraph, fill: Some(tint) }) + .show(ui); + EdgePicker::new("Page borders", Bind::bound(&mut page)).look(EdgeLook::Sample { area: SampleArea::Page, fill: None }).show(ui); + StoryOutput::from(first) + }) + .inner + .unwrap_or_default(); + *data.value("sample", (outer_edges(), mixed_edges(), outer_edges())) = (text, paragraph, page); + shown +} + #[story(TableSizePicker, covers = [Default], drive = Drive::Never)] fn table_size_picker(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { TableSizePicker::new("Insert Table").hovered((3, 4)).show(ui).into() diff --git a/crates/pages/tests/it/setup.rs b/crates/pages/tests/it/setup.rs index 9980d1872..2560e143c 100644 --- a/crates/pages/tests/it/setup.rs +++ b/crates/pages/tests/it/setup.rs @@ -1,9 +1,13 @@ -//! The column bar: a divider drag moves the two columns it divides. +//! The column bar: a divider drag moves the two columns it divides. The Page Setup dialog's Document grid: the counts +//! follow the kind, and a refused OK shows its reason. -use craft_pages::ui::ColumnBar; +use craft_pages::ui::{ColumnBar, PageSetupDialog}; +use craft_pages::{DocumentGrid, GridKind, MAX_GRID_COUNT, PageSetup}; use craft_ui::contract::{Bind, Show as _}; +use craft_ui::dialog::HeldAnswer; +use craft_ui::runtime::env::Label; use craft_ui::testing::{Fixture, trial}; -use egui::Vec2; +use egui::{Key, Modifiers, Vec2}; use std::cell::RefCell; use std::rc::Rc; @@ -36,3 +40,45 @@ fn a_divider_moves_only_the_two_columns_it_divides() { assert!(widths[1] > EQUAL && widths[2] < EQUAL, "the divided pair shares the change: {widths:?}"); assert!(close(widths[3], EQUAL), "the column past the pair is untouched: {widths:?}"); } + +#[trial] +fn the_grid_counts_follow_the_grid_kind_and_a_refused_ok_shows_its_reason() { + let start = PageSetup { grid: Some(DocumentGrid::new(GridKind::None, 40, 30)), ..PageSetup::default() }; + let state = Rc::new(RefCell::new((start, HeldAnswer::::new()))); + let seen = Rc::clone(&state); + let mut fixture = Fixture::new(move |ui| { + let mut state = seen.borrow_mut(); + let (setup, held) = &mut *state; + PageSetupDialog::new(Bind::bound(setup)).opened(Bind::given(true)).held(held).show(ui); + }); + fixture.settle(); + let disabled = |fixture: &Fixture, label: &str| { + let field = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} field")); + fixture.tree().is_disabled_key(field.node) + }; + let pick = |fixture: &mut Fixture, label: &str| { + let radio = fixture.by_label(label).unwrap_or_else(|| panic!("the {label} radio")); + fixture.click(&radio).settle(); + }; + assert!(disabled(&fixture, "Characters per line") && disabled(&fixture, "Lines per page"), "no grid: both counts disabled"); + pick(&mut fixture, "Line grid only"); + assert!(disabled(&fixture, "Characters per line") && !disabled(&fixture, "Lines per page"), "lines only: just the lines count"); + pick(&mut fixture, "Line and character grid"); + assert!(!disabled(&fixture, "Characters per line") && !disabled(&fixture, "Lines per page"), "lines and characters: both counts"); + + let field = fixture.by_label("Characters per line").expect("the characters field"); + fixture.click(&field).settle(); + fixture.key(Key::A, Modifiers::COMMAND).type_text("5000"); + fixture.key(Key::Tab, Modifiers::NONE).settle(); + let ok = fixture.by_label("OK").expect("the OK button"); + fixture.click(&ok).settle(); + let filed = state.borrow_mut().1.take().expect("OK files the setup in the held answer"); + assert_eq!(filed.grid.map(|grid| grid.chars_per_line), Some(MAX_GRID_COUNT), "a count past the range is held to it"); + + let reason = "This document cannot take a grid."; + assert!(state.borrow_mut().1.answer(Err(Label::from(reason.to_owned()))), "the host's refusal reaches the filed answer"); + fixture.settle(); + assert!(fixture.by_label(reason).is_some(), "the refusal shows in the dialog"); + pick(&mut fixture, "No grid"); + assert!(fixture.by_label(reason).is_none(), "changing a value clears the refusal"); +}