From 8610a89005488e4f1d08aea83773b0871b9407bd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:27 -0500 Subject: [PATCH] pdf-forms-w11: net change of 2 commits - pdf-forms-w11: finished by an agent - pdf-forms-w11: review fixes (review-1) --- crates/ui-egui/src/tools/bulk_fields.rs | 566 ++++++++++++----- crates/ui-egui/src/tools/field_table_ui.rs | 707 +++++++++------------ 2 files changed, 705 insertions(+), 568 deletions(-) diff --git a/crates/ui-egui/src/tools/bulk_fields.rs b/crates/ui-egui/src/tools/bulk_fields.rs index 7acb2ff75b..d41962b89c 100644 --- a/crates/ui-egui/src/tools/bulk_fields.rs +++ b/crates/ui-egui/src/tools/bulk_fields.rs @@ -1,13 +1,34 @@ //! Shared Field Properties for Prepare a form. Each property is opt-in, and appearance //! changes are merged per field so a mixed selection keeps everything the user did not edit. -use pdfcraft_engine::{BorderStyle, CheckStyle, DocId, Edit, FieldFont, FieldLookPatch, FieldProps, FormFieldKind, field_flags}; +use std::borrow::Cow; -use crate::{prepare, theme, widgets}; +use craft::behavior::{Mixed, SelectionChange, Value, keyed}; +use craft::theme::Srgba; +use craft::theme::variant::Tone; +use craft::ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::dialog::{DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id}; +use craft::ui::display::Text; +use craft::ui::layout_components::Stack; +use craft::ui::notices::{Notice, NoticeLayout}; +use craft::ui::patterns::form_dialogs::FormDialog; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::overlay::CloseReason; +use craft::ui::runtime::requests::ColorRequest; +use craft::ui::sections::GroupBox; +use craft::ui::tabs::{Tab as TabItem, TabKind, TabStrip}; +use craft::ui::text::{NumberField, TextField}; +use egui::{Context, Ui}; +use pdfcraft_engine::{BorderStyle, CheckStyle, DocId, Edit, FieldFont, FieldLookPatch, FieldProps, FormFieldKind, field_flags}; +use serde_json::{Value as Json, json}; + +use crate::colours::{self, RecentColours}; +use crate::{PdfCraftApp, prepare}; /// One property shown by the dialog. `apply` is explicit: merely opening the dialog, or /// visiting a tab, must never turn mixed values into the first field's value. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub struct Change { pub value: T, pub mixed: bool, @@ -27,7 +48,7 @@ impl Change { } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Tab { General, Appearance, @@ -35,7 +56,7 @@ pub enum Tab { } /// A dialog is bound to its source document, not whichever tab happens to be active later. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub struct Draft { pub doc: DocId, pub names: Vec, @@ -60,13 +81,49 @@ pub struct Draft { pub check_style: Change, /// A flag, its label, whether the UI wording is inverted, and its proposed value. pub flags: Vec<(u32, &'static str, bool, Change)>, - pub error: Option, text_fields: bool, choice_fields: bool, check_fields: bool, text_appearance: bool, } +/// A property no field has been compared for yet: off, so it applies nothing. +fn unset(value: T) -> Change { + Change { value, mixed: false, apply: false } +} + +/// The empty draft the form dialog's value type needs; a real one comes from [`Draft::new`]. +impl Default for Draft { + fn default() -> Self { + Draft { + doc: DocId(0), + names: Vec::new(), + tab: Tab::General, + tooltip: unset(String::new()), + read_only: unset(false), + required: unset(false), + locked: unset(false), + font_size: unset(0.0), + font: unset(FieldFont::Helvetica), + font_label: String::new(), + text: unset([0.0; 3]), + border: unset(None), + fill: unset(None), + width: unset(1.0), + style: unset(BorderStyle::Solid), + align: unset(0), + multiline: unset(false), + max_length: unset(0), + check_style: unset(CheckStyle::Check), + flags: Vec::new(), + text_fields: false, + choice_fields: false, + check_fields: false, + text_appearance: false, + } + } +} + impl Draft { /// The draft for editing `names` together, or why they can't be (a message for `tl!`). pub fn new(doc: &pdfcraft_engine::Document, names: Vec) -> Result { @@ -147,7 +204,6 @@ impl Draft { max_length: Change::from_values(fields.iter().map(|f| f.max_len.unwrap_or(0)))?, check_style: Change::from_values(fields.iter().map(|f| doc.field_check_style(&f.name).unwrap_or(CheckStyle::Check)))?, flags, - error: None, text_fields, choice_fields, check_fields, @@ -202,178 +258,362 @@ impl Draft { } } -fn row(ui: &mut egui::Ui, label: &str, c: &mut Change, edit: impl FnOnce(&mut egui::Ui, &mut T)) { - ui.add(widgets::checkbox(&mut c.apply, tl!(label))); - // Colour swatches contain their own grid; give every property's editor a separate - // namespace so border and fill controls do not share widget identities. - ui.push_id(label, |ui| ui.add_enabled_ui(c.apply, |ui| edit(ui, &mut c.value))); - ui.label(if c.mixed { tl!("Mixed") } else { "" }); - ui.end_row(); +/// The shared field properties window, held as an open dialog of `app.dialogs`. OK files the draft with the +/// app, which applies it as one edit and either accepts it (the window closes) or refuses it with a reason shown in +/// the window beside everything typed. +pub struct SharedFieldPropsDialog { + draft: Draft, + /// The filed draft keeps beside a refusal the values it refused, so the reason shows only until they change. + held: HeldAnswer, + recent: RecentColours, + /// The "Other colour..." request a row made this pass, for [`finish`] to open. + pending_colour: Option, } -impl crate::PdfCraftApp { - pub(crate) fn apply_bulk_field_props(&mut self) -> bool { - let result = self.bulk_field_props.as_ref().ok_or("The field properties dialog is no longer open.".to_string()).and_then(|d| { - if self.active_ids().map(|(_, id)| id) != Some(d.doc) { - return Err("The document changed while you were editing field properties.".into()); - } - self.session.get(d.doc).ok_or("The document is no longer open.".to_string()).and_then(|doc| d.edits(doc)) - }); - let error = match result { - Ok(edits) if edits.is_empty() => return true, - Ok(edits) => { - if self.apply_edit(Edit::Batch { label: "Change field properties".into(), edits }) { - return true; +impl SharedFieldPropsDialog { + /// The dialog for editing `names` together, or why they can't be (a message for `tl!`). + pub fn new(doc: &pdfcraft_engine::Document, names: Vec) -> Result { + // PLAN: assumed `RecentColours: Default` (pdf-comments-w10); `finish` replaces it with the app's handle each pass. + Ok(SharedFieldPropsDialog { draft: Draft::new(doc, names)?, held: HeldAnswer::new(), recent: RecentColours::default(), pending_colour: None }) + } + + /// Gives the row that asked with `key` the colour the picker answered. + pub(crate) fn set_colour(&mut self, key: &str, colour: [f64; 3]) { + let d = &mut self.draft; + match key { + TEXT_KEY => (d.text.value, d.text.mixed) = (colour, false), + BORDER_KEY => (d.border.value, d.border.mixed) = (Some(colour), false), + FILL_KEY => (d.fill.value, d.fill.mixed) = (Some(colour), false), + _ => {} + } + } +} + +/// The keys of the colour rows, which the colour pickers answer by. +const TEXT_KEY: &str = "bulk.props.text"; +const BORDER_KEY: &str = "bulk.props.border"; +const FILL_KEY: &str = "bulk.props.fill"; + +impl StackDialog for SharedFieldPropsDialog { + type Result = (); + + fn id(&self) -> DialogId { + dialog_id("shared-field-props") + } + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + let measuring = craft::ui::runtime::measure::active(ui.ctx()); + let finish = self.held.is_accepted(); + let SharedFieldPropsDialog { draft, held, recent, pending_colour } = self; + let refusal = held.refusal().filter(|(_, refused)| **refused == *draft).map(|(reason, _)| reason.clone()); + let waiting = held.is_waiting(); + let shown = FormDialog::new(tl!("Shared Field Properties").to_owned(), Bind::bound(&mut *draft)) + .accept_stays_open(true) + .collection_body(true) + .ok_enabled(!waiting) + .show(ui, |ui, cx, values| { + // A measuring run closes nothing: the real run of the pass makes the close. + if finish && !measuring { + cx.request_close_as(CloseReason::Activated); } - self.toast.as_ref().map(|(message, _)| message.clone()).unwrap_or_else(|| "The field properties could not be changed.".into()) + body(ui, values, recent, pending_colour, refusal.as_ref()); + true + }); + if held.refusal().is_some_and(|(_, refused)| *refused != *draft) { + held.clear_refusal(); + } + // The first footer button is OK; a pass without the press files nothing, so a second pass of a frame files once. + if shown.picked == Some(0) && !waiting { + held.file(draft.clone()); + } + match shown.closed { + Some(CloseReason::Activated) if finish => Some(held.finish().map_or(DialogResult::Cancel, |_| DialogResult::Ok(()))), + Some(_) => Some(DialogResult::Cancel), + None => None, + } + } + + fn held_state(&self) -> Option { + self.held.state() + } + + /// Files the draft as OK does and answers none until the app accepted it; then it answers. + fn confirm(&mut self, _: &Context) -> Option<()> { + if self.held.is_accepted() { + return self.held.finish().map(|_| ()); + } + if !self.held.is_waiting() { + self.held.file(self.draft.clone()); + } + None + } + + /// Each property as `{ value, mixed, apply }`, by the name of its row. + fn json_fields(&self) -> Option { + let d = &self.draft; + fn field(c: &Change, value: impl FnOnce(&T) -> Json) -> Json { + json!({ "value": value(&c.value), "mixed": c.mixed, "apply": c.apply }) + } + let mut map = serde_json::Map::new(); + map.insert("tab".into(), json!(format!("{:?}", d.tab))); + map.insert("fields".into(), json!(d.names)); + map.insert("tooltip".into(), field(&d.tooltip, |v| json!(v))); + map.insert("read_only".into(), field(&d.read_only, |v| json!(v))); + map.insert("required".into(), field(&d.required, |v| json!(v))); + map.insert("locked".into(), field(&d.locked, |v| json!(v))); + map.insert("font_size".into(), field(&d.font_size, |v| json!(v))); + map.insert("font".into(), field(&d.font, |v| json!(v.label()))); + map.insert("text".into(), field(&d.text, |v| json!(v))); + map.insert("border".into(), field(&d.border, |v| json!(v))); + map.insert("fill".into(), field(&d.fill, |v| json!(v))); + map.insert("width".into(), field(&d.width, |v| json!(v))); + map.insert("style".into(), field(&d.style, |v| json!(v.label()))); + map.insert("align".into(), field(&d.align, |v| json!(v))); + map.insert("multiline".into(), field(&d.multiline, |v| json!(v))); + map.insert("max_length".into(), field(&d.max_length, |v| json!(v))); + map.insert("check_style".into(), field(&d.check_style, |v| json!(v.label()))); + for (_, label, _, change) in &d.flags { + map.insert((*label).to_owned(), field(change, |v| json!(v))); + } + Some(Json::Object(map)) + } +} + +/// Applies a filed draft to the document the dialog was opened on, once per pass from the dialogs' results: refreshes the +/// recent colours, opens a colour picker a row asked for, and answers the held OK. A refusal keeps the dialog open with +/// everything typed. +pub(crate) fn finish(app: &mut PdfCraftApp) { + let recent = app.recent_colours.clone(); + let Some(dialog) = app.dialogs.get_mut::() else { return }; + dialog.recent = recent; + let request = dialog.pending_colour.take(); + let filed = dialog.held.take(); + if let Some(request) = request { + let key = request.key.clone(); + app.open_colour_picker(crate::colour_picker::PickerHost::App, request, move |app: &mut PdfCraftApp, colour: Srgba| { + if let Some(dialog) = app.dialogs.get_mut::() { + dialog.set_colour(&key, colours::to_rgb(colour)); } - Err(error) => error, + }); + } + let Some(draft) = filed else { return }; + let answer = apply(app, &draft); + if let Some(dialog) = app.dialogs.get_mut::() { + dialog.held.answer(answer); + } +} + +/// The draft's chosen changes as one edit; an empty draft changes nothing and is accepted. +fn apply(app: &mut PdfCraftApp, draft: &Draft) -> Result<(), Label> { + if app.active_ids().map(|(_, id)| id) != Some(draft.doc) { + return Err(tl!("The document changed while you were editing field properties.").to_owned().into()); + } + let Some(doc) = app.session.get(draft.doc) else { return Err(tl!("The document is no longer open.").to_owned().into()) }; + let edits = draft.edits(doc).map_err(Label::from)?; + if edits.is_empty() { + return Ok(()); + } + // `apply_edit` posts its own reason as a notice; the dialog's refusal is this fixed text. + if app.apply_edit(Edit::Batch { label: "Change field properties".into(), edits }) { + Ok(()) + } else { + Err(tl!("The field properties could not be changed.").to_owned().into()) + } +} + +/// One property: a group box whose check box is `apply`, enclosing the control, which binds the value as a `Mixed`. +/// An edit makes a mixed value concrete. `unknown` shows the control as mixed while the row is not applied, for a value the +/// control cannot show. +fn row( + ui: &mut Ui, + label: &str, + c: &mut Change, + unknown: bool, + control: impl FnOnce(&mut Ui, &mut Mixed), +) { + let Change { value, mixed, apply } = c; + let hidden = unknown && !*apply; + GroupBox::apply(tl!(label).to_owned(), Bind::bound(apply)).show(ui, |ui, _| { + let mut shown = if *mixed || hidden { Mixed::Mixed } else { Mixed::Same(value.clone()) }; + control(ui, &mut shown); + if let Mixed::Same(edited) = shown { + *value = edited; + *mixed = false; + } + }); +} + +/// A Yes/No choice. +fn yes_no(ui: &mut Ui, label: &str, c: &mut Change) { + let entries = [Entry::new(true, tl!("Yes").to_owned()), Entry::new(false, tl!("No").to_owned())]; + row(ui, label, c, false, |ui, shown| { + Select::new(tl!(label).to_owned(), Bind::bound_mixed(shown), &entries).show(ui); + }); +} + +/// A choice among `entries`. +fn choose(ui: &mut Ui, label: &str, c: &mut Change, entries: &[Entry]) { + row(ui, label, c, false, |ui, shown| { + Select::new(tl!(label).to_owned(), Bind::bound_mixed(shown), entries).show(ui); + }); +} + +/// A number within `range`, converted to and from the property's own type. +fn number( + ui: &mut Ui, + label: &str, + c: &mut Change, + range: std::ops::RangeInclusive, + unit: Option<&'static str>, + to: fn(&T) -> f64, + from: fn(f64) -> T, +) { + row(ui, label, c, false, |ui, shown| { + let mut typed = match shown { + Mixed::Same(v) => Mixed::Same(Some(to(v))), + _ => Mixed::Mixed, }; - if let Some(draft) = self.bulk_field_props.as_mut() { - draft.error = Some(error); + let mut field = NumberField::new(tl!(label).to_owned(), Bind::bound_mixed(&mut typed)).range(range); + if let Some(unit) = unit { + field = field.unit(unit); } - false - } -} - -fn bool_row(ui: &mut egui::Ui, label: &str, c: &mut Change) { - row(ui, label, c, |ui, value| { - craft_ui::ComboBox::from_id_salt(label).selected_text(tl!(if *value { "Yes" } else { "No" })).show_ui(ui, |ui| { - ui.selectable_value(value, true, tl!("Yes")); - ui.selectable_value(value, false, tl!("No")); - }); - }); -} - -fn color(ui: &mut egui::Ui, value: &mut Option<[f64; 3]>) { - ui.horizontal(|ui| { - let mut none = value.is_none(); - if ui.add(widgets::checkbox(&mut none, tl!("No color"))).changed() { - *value = if none { None } else { Some([0.0; 3]) }; - } - if let Some(c) = crate::comments::swatch_grid(ui, *value) { - *value = Some(c); + field.show(ui); + if let Mixed::Same(Some(v)) = typed { + *shown = Mixed::Same(from(v)); } }); } -/// Check a property to apply its value to every selected field. No unchecked value is used. -pub(crate) fn body(ui: &mut egui::Ui, d: &mut Draft, t: &theme::Tokens) -> (bool, bool) { - ui.set_width(600.0); - ui.label(egui::RichText::new(tl!("Shared Field Properties")).font(theme::semibold(18.0))); - ui.label(crate::i18n::fmt(tl!("{n} fields selected"), &[("n", &d.names.len().to_string())])); - ui.label( - egui::RichText::new(tl!("Only checked properties will change. Mixed means the selected fields have different values.")) - .small() - .color(t.text_muted), - ); - ui.add_space(8.0); - ui.horizontal(|ui| { - for (tab, label) in [(Tab::General, "General"), (Tab::Appearance, "Appearance"), (Tab::Options, "Options")] { - if tab == Tab::Options && !(d.text_fields || d.choice_fields || d.check_fields) { - continue; - } - if widgets::mode_tab(ui, tl!(label), d.tab == tab).clicked() { - d.tab = tab; - } +/// The colour of the text, a palette whose "Other colour..." asks the app's picker. +fn text_colour(ui: &mut Ui, label: &str, c: &mut Change<[f64; 3]>, recent: &RecentColours, request: &mut Option) { + let Change { value, mixed, apply } = c; + GroupBox::apply(tl!(label).to_owned(), Bind::bound(apply)).show(ui, |ui, _| { + let current = (!*mixed).then_some(*value); + let pick = colours::palette(ui, tl!(label), current, TEXT_KEY, recent); + if let Some(picked) = pick.picked { + *value = picked; + *mixed = false; + } + if pick.request.is_some() { + *request = pick.request; } }); - ui.separator(); - egui::ScrollArea::vertical().max_height(430.0).auto_shrink([false, true]).show(ui, |ui| { - egui::Grid::new("bulk-field-properties").num_columns(3).spacing([16.0, 10.0]).show(ui, |ui| match d.tab { +} + +/// A colour that may be none: `choice` is the row's border or fill chooser. +fn optional_colour( + ui: &mut Ui, + label: &str, + c: &mut Change>, + choice: impl FnOnce(&mut Ui, &str, Option<[f64; 3]>) -> Option>, +) { + let Change { value, mixed, apply } = c; + GroupBox::apply(tl!(label).to_owned(), Bind::bound(apply)).show(ui, |ui, _| { + let current = if *mixed { None } else { *value }; + if let Some(chosen) = choice(ui, tl!(label), current) { + *value = chosen; + *mixed = false; + } + }); +} + +/// A note under the rows. +fn note(ui: &mut Ui, text: &str) { + Text::new(tl!(text).to_owned()).show(ui); +} + +/// The tabs and the rows of the open tab. Check a property to apply its value to every selected field; no unchecked +/// value is used. +fn body(ui: &mut Ui, d: &mut Draft, recent: &RecentColours, request: &mut Option, refusal: Option<&Label>) { + Stack::new().show(ui, |ui, _| { + Text::new(crate::i18n::fmt(tl!("{n} fields selected"), &[("n", &d.names.len().to_string())])).show(ui); + note(ui, "Only checked properties will change. Mixed means the selected fields have different values."); + tabs(ui, d); + match d.tab { Tab::General => { - row(ui, "Tooltip:", &mut d.tooltip, |ui, v| { - ui.add(egui::TextEdit::singleline(v).desired_width(280.0)).accessible_name(tl!("Tooltip")); + let c = &mut d.tooltip; + row(ui, "Tooltip:", c, false, |ui, shown| { + TextField::new(tl!("Tooltip").to_owned(), Bind::bound_mixed(shown)).show(ui); }); - bool_row(ui, "Read Only", &mut d.read_only); - bool_row(ui, "Required", &mut d.required); - bool_row(ui, "Locked", &mut d.locked); + yes_no(ui, "Read Only", &mut d.read_only); + yes_no(ui, "Required", &mut d.required); + yes_no(ui, "Locked", &mut d.locked); + note(ui, "To change locked fields, also set Locked to No."); } - Tab::Appearance => { - if d.text_appearance { - row(ui, "Font Size:", &mut d.font_size, |ui, v| { - ui.add(egui::DragValue::new(v).range(0.0..=100.0).speed(0.25).suffix(" pt")); - }); - let font_label = if d.font.apply { d.font.value.label().to_string() } else { d.font_label.clone() }; - row(ui, "Font:", &mut d.font, |ui, v| { - craft_ui::ComboBox::from_id_salt("bulk-font").selected_text(tl!(&font_label)).show_ui(ui, |ui| { - for font in FieldFont::ALL { - ui.selectable_value(v, font, font.label()); - } - }); - }); - row(ui, "Text Color:", &mut d.text, |ui, v| { - if let Some(c) = crate::comments::swatch_grid(ui, Some(*v)) { - *v = c; - } - }); - } - row(ui, "Border Color:", &mut d.border, color); - row(ui, "Fill Color:", &mut d.fill, color); - row(ui, "Line Thickness:", &mut d.width, |ui, v| { - ui.add(egui::DragValue::new(v).range(0.0..=12.0).speed(0.25).suffix(" pt")); - }); - row(ui, "Line Style:", &mut d.style, |ui, v| { - craft_ui::ComboBox::from_id_salt("bulk-style").selected_text(tl!(v.label())).show_ui(ui, |ui| { - for style in BorderStyle::ALL { - ui.selectable_value(v, style, tl!(style.label())); - } - }); - }); - } - Tab::Options => { - if d.text_fields || d.choice_fields { - row(ui, "Alignment:", &mut d.align, |ui, v| { - let label = match *v { - 1 => "Center", - 2 => "Right", - _ => "Left", - }; - craft_ui::ComboBox::from_id_salt("bulk-align").selected_text(tl!(label)).show_ui(ui, |ui| { - for (value, label) in [(0, "Left"), (1, "Center"), (2, "Right")] { - ui.selectable_value(v, value, tl!(label)); - } - }); - }); - } - if d.text_fields { - bool_row(ui, "Multi-line", &mut d.multiline); - row(ui, "Character limit:", &mut d.max_length, |ui, v| { - ui.add(egui::DragValue::new(v).range(0..=1_000_000)); - }); - } - if d.check_fields { - row(ui, "Button Style:", &mut d.check_style, |ui, v| { - craft_ui::ComboBox::from_id_salt("bulk-check-style").selected_text(tl!(v.label())).show_ui(ui, |ui| { - for style in CheckStyle::ALL { - ui.selectable_value(v, style, tl!(style.label())); - } - }); - }); - } - for (_, label, _, change) in &mut d.flags { - bool_row(ui, label, change); - } - } - }); - ui.add_space(8.0); - if d.tab == Tab::Appearance && d.text_appearance { - ui.label(egui::RichText::new(tl!("Font size 0 uses automatic sizing.")).small().color(t.text_muted)); - } else if d.tab == Tab::Options && d.text_fields { - ui.label(egui::RichText::new(tl!("Character limit 0 means no limit. A comb of characters needs a limit.")).small().color(t.text_muted)); - } else if d.tab == Tab::General { - ui.label(egui::RichText::new(tl!("To change locked fields, also set Locked to No.")).small().color(t.text_muted)); + Tab::Appearance => appearance(ui, d, recent, request), + Tab::Options => options(ui, d), + } + if let Some(reason) = refusal { + Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui); } }); - if let Some(error) = &d.error { - ui.add_space(8.0); - ui.label(egui::RichText::new(tl!(error)).color(t.text)); - } - ui.separator(); - let (mut apply, mut cancel) = (false, false); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - apply = widgets::pill_button(ui, tl!("OK"), true).clicked(); - cancel = widgets::pill_button(ui, tl!("Cancel"), false).clicked(); +} + +/// The strip of tabs; Options only when every selected field has some. +fn tabs(ui: &mut Ui, d: &mut Draft) { + let options = d.text_fields || d.choice_fields || d.check_fields; + let items: Vec<(Tab, String)> = [(Tab::General, "General"), (Tab::Appearance, "Appearance"), (Tab::Options, "Options")] + .into_iter() + .filter(|(tab, _)| *tab != Tab::Options || options) + .map(|(tab, label)| (tab, tl!(label).to_owned())) + .collect(); + let source = keyed(&items[..], |item: &(Tab, String)| item.0).with_text(|item| Cow::Borrowed(item.1.as_str())); + let strip = TabStrip::new(tl!("Shared Field Properties").to_owned()).kind(TabKind::Text).shown(d.tab).natural_height(true); + let out = strip.show_items(ui, &source, &mut |key, _| { + TabItem::new(items.iter().find(|item| item.0 == *key).map_or_else(String::new, |item| item.1.clone())) }); - (apply, cancel) + for event in out.response.events { + if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event + && let Some(chosen) = keys.last() + { + d.tab = *chosen; + } + } +} + +/// The Appearance tab: font and text colour for fields that show text, then the border and the line. +fn appearance(ui: &mut Ui, d: &mut Draft, recent: &RecentColours, request: &mut Option) { + if d.text_appearance { + number(ui, "Font Size:", &mut d.font_size, 0.0..=100.0, Some("pt"), |v| *v, |v| v); + let fonts: Vec> = FieldFont::ALL.into_iter().map(|font| Entry::new(font, font.label().to_owned())).collect(); + // A custom font, or fonts that differ, show their name as the placeholder until the row is applied. + let shown_label = d.font.value.label() != d.font_label; + let (font, placeholder) = (&mut d.font, d.font_label.clone()); + row(ui, "Font:", font, shown_label, |ui, shown| { + Select::new(tl!("Font:").to_owned(), Bind::bound_mixed(shown), &fonts).placeholder(placeholder).show(ui); + }); + text_colour(ui, "Text Color:", &mut d.text, recent, request); + } + // PLAN: `border_choice` and `fill_choice` return only the choice (`Option>`), so their "Other colour..." + // cannot ask for the picker; the owner (pdf-comments-w10) adds the request, then these rows park it as `text_colour` does. + optional_colour(ui, "Border Color:", &mut d.border, |ui, label, current| colours::border_choice(ui, label, current, BORDER_KEY, recent)); + optional_colour(ui, "Fill Color:", &mut d.fill, |ui, label, current| colours::fill_choice(ui, label, current, FILL_KEY, recent)); + number(ui, "Line Thickness:", &mut d.width, 0.0..=12.0, Some("pt"), |v| *v, |v| v); + let styles: Vec> = BorderStyle::ALL.into_iter().map(|style| Entry::new(style, tl!(style.label()).to_owned())).collect(); + choose(ui, "Line Style:", &mut d.style, &styles); + if d.text_appearance { + note(ui, "Font size 0 uses automatic sizing."); + } +} + +/// The Options tab: what applies to the kind of field selected. +fn options(ui: &mut Ui, d: &mut Draft) { + if d.text_fields || d.choice_fields { + let aligns: Vec> = [(0, "Left"), (1, "Center"), (2, "Right")].into_iter().map(|(v, label)| Entry::new(v, tl!(label).to_owned())).collect(); + choose(ui, "Alignment:", &mut d.align, &aligns); + } + if d.text_fields { + yes_no(ui, "Multi-line", &mut d.multiline); + number(ui, "Character limit:", &mut d.max_length, 0.0..=1_000_000.0, None, |v| *v as f64, |v| v.round().max(0.0) as usize); + } + if d.check_fields { + let styles: Vec> = CheckStyle::ALL.into_iter().map(|style| Entry::new(style, tl!(style.label()).to_owned())).collect(); + choose(ui, "Button Style:", &mut d.check_style, &styles); + } + for (_, label, _, change) in &mut d.flags { + yes_no(ui, label, change); + } + if d.text_fields { + note(ui, "Character limit 0 means no limit. A comb of characters needs a limit."); + } } diff --git a/crates/ui-egui/src/tools/field_table_ui.rs b/crates/ui-egui/src/tools/field_table_ui.rs index 6dacf67a65..ed6c033944 100644 --- a/crates/ui-egui/src/tools/field_table_ui.rs +++ b/crates/ui-egui/src/tools/field_table_ui.rs @@ -7,22 +7,34 @@ //! prepared or changes in any way (a page rotated, moved or deleted, an edit undone), and adds the //! table there. -use std::ops::RangeInclusive; use std::sync::Arc; -use egui::{Align, Color32, CornerRadius, Layout, Rect, RichText, Sense, Stroke, pos2, vec2}; +use craft::behavior::{Input, Metrics}; +use craft::pages::ui::ColumnBar; +use craft::theme::variant::Tone; +use craft::ui::buttons::Button; +use craft::ui::contract::{ + Access, Bind, Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Scroll, Show as _, ShowContainer as _, clicked, +}; +use craft::ui::dialog::{DialogHost, DialogId, DialogResult, DialogStack, HeldAnswer, HeldOk, StackDialog, dialog_id}; +use craft::ui::display::Text; +use craft::ui::form::{Field, FieldGroup}; +use craft::ui::layout_components::Stack; +use craft::ui::notices::{Notice, NoticeLayout}; +use craft::ui::patterns::form_dialogs::FormDialog; +use craft::ui::primitives::{Draw, HAlign, PaintShape, StrokeWidth, TextRun}; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::overlay::CloseReason; +use craft::ui::style::{ComponentStyle, StyleColor, StyleCx}; +use craft::ui::text::{NumberField, TextField}; +use egui::{Context, CornerRadius, Rect, Response, Ui}; use pdfcraft_engine::field_table::{self, Cell, FieldTable, MAX_COLUMNS, MAX_FIRST_ROW, MAX_ROWS, TableError}; use pdfcraft_engine::{DocId, Edit, FormField}; use pdfcraft_render::PageInfo; +use serde_json::{Value as Json, json}; use crate::canvas::PageXform; -use crate::{Dialog, PdfCraftApp, i18n, theme, widgets}; - -const SELECT_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6); -const ERROR_RED: Color32 = Color32::from_rgb(0xD1, 0x3B, 0x3B); -/// A divider can't be dragged to leave a column less than this share of the table, or less than a -/// quarter of what the two columns it divides have between them when that is smaller. -const MIN_SHARE: f64 = 0.04; +use crate::{PdfCraftApp, i18n}; /// The table being set up in the window, and where it goes. #[derive(Clone, Debug)] @@ -38,8 +50,6 @@ pub struct FieldTableDraft { generation: u64, /// The table as last laid out, kept until the table changes. laid: Option>, - /// A field in the window had the keyboard last frame, so Escape leaves the field. - typing: bool, } /// Two drafts are the same table in the same place; what is kept for the next frame isn't part of it. @@ -49,6 +59,14 @@ impl PartialEq for FieldTableDraft { } } +/// The empty draft the form dialog's value type needs; a real one comes from [`FieldTableDraft::new`]. +impl Default for FieldTableDraft { + fn default() -> Self { + let base = "Table1".to_owned(); + FieldTableDraft { doc: DocId(0), page: 0, table: FieldTable::new([0.0, 0.0, 1.0, 1.0], &base), base, generation: 0, laid: None } + } +} + /// A table laid out and checked once, for every frame it stays the same: the cells the page and the /// window show, and the edit Add fields applies. Up to 100 × 50 cells, so not every frame. #[derive(Debug)] @@ -64,10 +82,11 @@ pub(crate) struct Preview { laid: Arc, } -/// How the window was left this frame. -enum Choice { - Add, - Cancel, +impl Preview { + /// The page the table is on, 0-based: the one page that shows it. + pub(crate) fn page(&self) -> usize { + self.page + } } impl FieldTableDraft { @@ -75,7 +94,7 @@ impl FieldTableDraft { /// the first base `form` leaves free. pub(crate) fn new(doc: DocId, page: usize, rect: [f64; 4], form: &[FormField], generation: u64) -> Self { let base = field_table::free_base(form.iter().map(|f| f.name.as_str())); - FieldTableDraft { doc, page, table: FieldTable::new(rect, &base), base, generation, laid: None, typing: false } + FieldTableDraft { doc, page, table: FieldTable::new(rect, &base), base, generation, laid: None } } /// The table laid out on its page (`info`, in a form whose fields are `form`), worked out again @@ -96,35 +115,6 @@ impl FieldTableDraft { Preview { page: self.page, laid: self.laid(info, form) } } - /// Each column's share of the table's width, together 1. - fn shares(&self) -> Vec { - let total: f64 = self.table.columns.iter().map(|c| c.width).sum(); - let n = self.table.columns.len().max(1) as f64; - self.table.columns.iter().map(|c| if total > 0.0 && total.is_finite() { c.width / total } else { 1.0 / n }).collect() - } - - /// Move the divider after column `i` (0-based) by `delta`, a share of the table's width. The - /// two columns it divides keep [`MIN_SHARE`] each, or a quarter of what they have between them - /// when that is less, so narrow columns can still be resized; the other columns keep theirs. - fn move_divider(&mut self, i: usize, delta: f64) { - let total: f64 = self.table.columns.iter().map(|c| c.width).sum(); - let (Some(a), Some(b)) = (self.table.columns.get(i).map(|c| c.width), self.table.columns.get(i + 1).map(|c| c.width)) else { return }; - if !(total > 0.0 && total.is_finite() && delta.is_finite()) { - return; - } - let pair = (a + b) / total; - // At most half the pair, so the bounds never cross; `max` then `min` all the same, never - // `clamp`, which panics if they do. - let least = MIN_SHARE.min(pair / 4.0); - let left = (a / total + delta).max(least).min(pair - least); - if let Some(c) = self.table.columns.get_mut(i) { - c.width = left * total; - } - if let Some(c) = self.table.columns.get_mut(i + 1) { - c.width = (pair - left) * total; - } - } - /// Give every column the same width: their widths are shares, so the same number does it. fn distribute_evenly(&mut self) { for c in &mut self.table.columns { @@ -133,152 +123,154 @@ impl FieldTableDraft { } } -/// Show the window while [`Dialog::FieldTable`] is open, and add the table when asked to. -pub(crate) fn show(app: &mut PdfCraftApp, ctx: &egui::Context) { +/// The text field table window, held as an open dialog of `app.dialogs`. It keeps the page's size and the form as they +/// were when it opened, which is all the table needs of the document: any edit closes the window. +pub struct FieldTableDialog { + draft: FieldTableDraft, + info: PageInfo, + form: Vec, + /// The filed draft keeps beside a refusal the table it refused, so the reason shows only until the table changes. + held: HeldAnswer, +} + +impl StackDialog for FieldTableDialog { + type Result = (); + + fn id(&self) -> DialogId { + dialog_id("field-table") + } + + fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option> { + let measuring = craft::ui::runtime::measure::active(ui.ctx()); + let finish = self.held.is_accepted(); + let FieldTableDialog { draft, info, form, held } = self; + let waiting = held.is_waiting(); + let refusal = held.refusal().filter(|(_, refused)| **refused == *draft).map(|(reason, _)| reason.clone()); + // The layout of a table that did not change this pass is kept in the draft, so the body asks for it again for free. + draft.laid(info, form); + let shown = FormDialog::new(tl!("Text Field Table").to_owned(), Bind::bound(&mut *draft)) + .ok_label(tl!("Add fields").to_owned()) + .enter_confirms(false) + .accept_stays_open(true) + .ok_enabled(!waiting) + .shaped(|dialog| dialog.modeless()) + .show(ui, |ui, cx, values| { + // A measuring run closes nothing: the real run of the pass makes the close. + if finish && !measuring { + cx.request_close_as(CloseReason::Activated); + } + body(ui, values, info, form, refusal.as_ref()) + }); + if held.refusal().is_some_and(|(_, refused)| *refused != *draft) { + held.clear_refusal(); + } + // The first footer button is Add fields; a pass without the press files nothing, so a second pass of a frame files once. + if shown.picked == Some(0) && !waiting { + held.file(draft.clone()); + } + match shown.closed { + Some(CloseReason::Activated) if finish => Some(held.finish().map_or(DialogResult::Cancel, |_| DialogResult::Ok(()))), + Some(_) => Some(DialogResult::Cancel), + None => None, + } + } + + fn held_state(&self) -> Option { + self.held.state() + } + + /// Files the table as Add fields does and answers none until the app accepted it; then it answers. + fn confirm(&mut self, _: &Context) -> Option<()> { + if self.held.is_accepted() { + return self.held.finish().map(|_| ()); + } + if !self.held.is_waiting() { + let FieldTableDialog { draft, info, form, held } = self; + if draft.laid(info, form).edit.is_ok() { + held.file(draft.clone()); + } + } + None + } + + /// The table's rows, columns, spacings, first row number, column widths and name patterns, and why it can't be added + /// while it can't. + fn json_fields(&self) -> Option { + let t = &self.draft.table; + let reason = field_table::edit(t, self.draft.page, &self.info, &self.form).err().map(|e| e.said(&i18n::words)); + let mut map = serde_json::Map::new(); + map.insert("rows".into(), json!(t.rows)); + map.insert("columns".into(), json!(t.columns.len())); + map.insert("row_gap".into(), json!(t.row_gap)); + map.insert("column_gap".into(), json!(t.column_gap)); + map.insert("first".into(), json!(t.first_row)); + map.insert("widths".into(), json!(t.columns.iter().map(|c| c.width).collect::>())); + map.insert("patterns".into(), json!(t.columns.iter().map(|c| c.pattern.as_str()).collect::>())); + if let Some(reason) = reason { + map.insert("reason".into(), json!(reason)); + } + Some(Json::Object(map)) + } +} + +/// Opens the window for a table filling `rect` (view space) on `page` of `doc`, at edit `generation`, over a form whose +/// fields are `form`. Nothing opens when the page is not there. +pub(crate) fn open(app: &mut PdfCraftApp, doc: DocId, page: usize, rect: [f64; 4], form: &[FormField], generation: u64) { + let Some(info) = app.session.get(doc).and_then(|d| d.info.pages.get(page)).cloned() else { return }; + let draft = FieldTableDraft::new(doc, page, rect, form, generation); + crate::dialogs::host::open(app, FieldTableDialog { draft, info, form: form.to_vec(), held: HeldAnswer::new() }); +} + +/// Closes the window when its page or document is no longer what it was opened on, and adds the table when asked to; once per +/// pass from the dialogs' results. +pub(crate) fn pass(app: &mut PdfCraftApp, ctx: &Context) { + let Some(dialog) = app.dialogs.get::() else { return }; + let (doc, page, generation) = (dialog.draft.doc, dialog.draft.page, dialog.draft.generation); // The window belongs to one page of one document, while that document is being prepared. - let active = app.active_ids().map(|(_, id)| id); - let preparing = app.is_preparing(); - let belongs = app.field_table_draft.as_ref().is_some_and(|d| { - active == Some(d.doc) - && preparing - && app - .session - .get(d.doc) - .is_some_and(|doc| doc.edit_generation() == d.generation && d.page < doc.info.pages.len() && doc.allows_modification()) - }); + let belongs = app.active_ids().map(|(_, id)| id) == Some(doc) + && app.is_preparing() + && app + .session + .get(doc) + .is_some_and(|d| d.edit_generation() == generation && page < d.info.pages.len() && d.allows_modification()); if !belongs { - close(app); + app.dialogs.cancel::(ctx); return; } - // Both there, as `belongs` says; the fields are borrowed apart, so the window can change the - // table while it reads the document. - let Some(draft) = app.field_table_draft.as_mut() else { return }; - let Some((info, form)) = app.session.get(draft.doc).and_then(|doc| Some((doc.info.pages.get(draft.page)?, &doc.form))) else { return }; - let t = theme::Tokens::get(ctx); - let mut open = true; - let mut choice = None; - let mut laid = None; - egui::Window::new(tl!("Text Field Table")) - .id(egui::Id::unique("field_table_window")) - .open(&mut open) - .collapsible(false) - .resizable(false) - .order(egui::Order::Foreground) - .min_width(440.0) - .max_width(440.0) - .default_pos(egui::pos2(120.0, 100.0)) - .show(ctx, |ui| { - widgets::begin_dialog(ui); - let (c, l) = body(ui, draft, info, form, &t); - choice = c; - laid = Some(l); - }); - // Escape closes it, as it closes a modal dialog, unless a field had the keyboard: then Escape - // only leaves the field, and what was set up stays. Enter is left to the field being typed in. - let escape = !draft.typing && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); - draft.typing = ctx.egui_wants_keyboard_input(); - match choice { - _ if !open || escape => close(app), - Some(Choice::Cancel) => close(app), - // Added, the window closes; refused, it stays as it is, with the notice saying why. - Some(Choice::Add) => { - if let Some(Ok(edit)) = laid.as_deref().map(|l| l.edit.clone()) - && app.apply_edit(edit) - { - close(app); - } - } - None => {} + let Some(FieldTableDialog { draft, info, form, held }) = app.dialogs.get_mut::() else { return }; + if held.take().is_none() { + return; + } + let edit = draft.laid(info, form).edit.as_ref().ok().cloned(); + // Added, the window closes; refused, it stays as it is, with the notice saying why. + let added = edit.is_some_and(|edit| app.apply_edit(edit)); + if let Some(dialog) = app.dialogs.get_mut::() { + dialog.held.answer(if added { Ok(()) } else { Err(tl!("The field table could not be added.").to_owned().into()) }); } } -/// Drop the table being set up, and the dialog with it if it is still the open one. -fn close(app: &mut PdfCraftApp) { - app.field_table_draft = None; - if app.dialog == Some(Dialog::FieldTable) { - app.dialog = None; - } +/// What the page shows of the table being set up in the window of `doc`, if it is open. +pub(crate) fn preview(dialogs: &mut DialogHost, doc: DocId) -> Option { + let dialog = dialogs.get_mut::().filter(|d| d.draft.doc == doc)?; + Some(dialog.draft.preview(&dialog.info, &dialog.form)) } -/// The window's controls, the names the table will have, and why it can't be added if it can't. -/// Returns what was chosen and the table as it now stands, laid out and checked. -fn body(ui: &mut egui::Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormField], t: &theme::Tokens) -> (Option, Arc) { - let columns = d.table.columns.len(); - egui::Grid::new("field_table_grid").num_columns(2).spacing([14.0, 8.0]).min_col_width(120.0).show(ui, |ui| { - ui.label(tl!("Rows")); - stepper(ui, &mut d.table.rows, 1..=MAX_ROWS, 1.0, ""); - ui.end_row(); - ui.label(tl!("Columns")); - let mut n = columns; - if stepper(ui, &mut n, 1..=MAX_COLUMNS, 1.0, "") { - d.table.set_columns(n, &d.base); - } - ui.end_row(); - ui.label(tl!("Row spacing")); - stepper(ui, &mut d.table.row_gap, 0.0..=100.0, 1.0, " pt"); - ui.end_row(); - ui.label(tl!("Column spacing")); - ui.add_enabled_ui(columns > 1, |ui| stepper(ui, &mut d.table.column_gap, 0.0..=100.0, 1.0, " pt")); - ui.end_row(); - ui.label(tl!("First row number")); - ui.add(egui::DragValue::new(&mut d.table.first_row).range(0..=MAX_FIRST_ROW)); - ui.end_row(); - }); - - ui.add_space(8.0); - ui.separator(); - ui.add_space(6.0); - ui.horizontal(|ui| { - ui.label(RichText::new(tl!("Column widths")).strong()); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - ui.add_enabled_ui(d.table.columns.len() > 1, |ui| { - if widgets::pill_button(ui, tl!("Distribute evenly"), false).clicked() { - d.distribute_evenly(); - } - }); - }); - }); - ui.add_space(4.0); - column_bar(ui, d, t); - - ui.add_space(8.0); - ui.label(RichText::new(tl!("Field names")).strong()); - // How the names are worked out. Its tokens are the same in every language. - let hint = tl!("N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last."); - ui.add(egui::Label::new(RichText::new(hint).color(t.text_muted).size(11.0)).wrap()); - ui.add_space(4.0); - // The widths shown don't depend on the names being typed below. - let layout = d.laid(info, form); - let shares = d.shares(); - let scrolls = d.table.columns.len() > 3; - let mut column_fields = |ui: &mut egui::Ui| { - for (c, column) in d.table.columns.iter_mut().enumerate() { - let width = layout.cells.as_ref().ok().and_then(|cells| cells.get(c)).map(|cell| cell.rect[2] - cell.rect[0]); - let share = shares.get(c).copied().unwrap_or_default(); - let mut column_label_response = None; - ui.horizontal(|ui| { - let label = ui.label(RichText::new(column_label(c)).strong()); - column_label_response = Some(label.id); - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - let size = width.map_or_else(|| "—".to_owned(), |w| format!("{w:.1} pt · {:.0}%", share * 100.0)); - ui.label(RichText::new(size).color(t.text_muted).size(11.0)); - }); - }); - let full = ui.available_width(); - let pattern = ui.add(widgets::line(&mut column.pattern).desired_width(full).id_salt(("field table column", c))); - if let Some(label) = column_label_response { - pattern.labelled_by(label); +/// The window's controls, the names the table will have, and why it can't be added if it can't. Returns whether it can. +fn body(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormField], refusal: Option<&Label>) -> bool { + Stack::new().show(ui, |ui, _| { + FieldGroup::new(tl!("Text Field Table").to_owned()).show(ui, |ui, _| { + whole(ui, "Rows", &mut d.table.rows, 1, MAX_ROWS); + let mut columns = d.table.columns.len(); + if whole(ui, "Columns", &mut columns, 1, MAX_COLUMNS) { + d.table.set_columns(columns, &d.base); } - ui.add_space(4.0); - } - }; - if scrolls { - egui::ScrollArea::vertical().max_height(180.0).show(ui, column_fields); - } else { - column_fields(ui); - } - - ui.add_space(8.0); + points(ui, "Row spacing", &mut d.table.row_gap, true); + points(ui, "Column spacing", &mut d.table.column_gap, d.table.columns.len() > 1); + whole(ui, "First row number", &mut d.table.first_row, 0, MAX_FIRST_ROW); + }); + widths(ui, d); + names(ui, d, info, form); + }); // The names, and the edit Add fields applies, from the table as it now stands. let laid = d.laid(info, form); if let Ok(cells) = &laid.cells { @@ -289,26 +281,76 @@ fn body(ui: &mut egui::Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[For [first, second] => format!("{first}, {second}"), [first, second, .., last] => format!("{first}, {second} … {last}"), }; - ui.horizontal(|ui| { - ui.label(RichText::new(i18n::trn(i18n::current(), names.len() as u64, "{n} field", "{n} fields")).color(t.text_muted)); - ui.add(egui::Label::new(RichText::new(shown).font(theme::medium(12.0))).truncate()); - }); + let count = i18n::trn(i18n::current(), names.len() as u64, "{n} field", "{n} fields"); + Text::new(format!("{count}: {shown}")).show(ui); } if let Err(e) = &laid.edit { - ui.add(egui::Label::new(RichText::new(e.said(&i18n::words)).color(ERROR_RED).size(11.0)).wrap()); + Notice::new(Tone::Bad, e.said(&i18n::words)).layout(NoticeLayout::Inline).show(ui); } + if let Some(reason) = refusal { + Notice::new(Tone::Bad, reason.clone()).layout(NoticeLayout::Inline).show(ui); + } + laid.edit.is_ok() +} - ui.add_space(14.0); - let mut choice = None; - ui.with_layout(Layout::right_to_left(Align::Center), |ui| { - if ui.add_enabled_ui(laid.edit.is_ok(), |ui| widgets::pill_button(ui, tl!("Add fields"), true)).inner.clicked() { - choice = Some(Choice::Add); +/// A whole number field held to `least..=most`. Whether the number changed. +fn whole(ui: &mut Ui, label: &str, value: &mut usize, least: usize, most: usize) -> bool { + let mut typed = Some(*value as f64); + Field::new(tl!(label).to_owned()).show(ui, |ui, _| { + NumberField::new(tl!(label).to_owned(), Bind::bound(&mut typed)).range(least as f64..=most as f64).show(ui); + }); + // An emptied field keeps the number; `max` then `min` rather than `clamp`, which panics if the bounds cross. + let next = typed.map_or(*value, |v| (v.round().max(0.0) as usize).max(least).min(most)); + std::mem::replace(value, next) != next +} + +/// A length in points from 0 to 100, shown only while `enabled`. +fn points(ui: &mut Ui, label: &str, value: &mut f64, enabled: bool) { + let mut typed = Some(*value); + Field::new(tl!(label).to_owned()).enabled(enabled).show(ui, |ui, _| { + NumberField::new(tl!(label).to_owned(), Bind::bound(&mut typed)).range(0.0..=100.0).unit("pt").show(ui); + }); + if let Some(v) = typed { + *value = v; + } +} + +/// The columns as a bar with a divider between each two, and the button giving them one width. +fn widths(ui: &mut Ui, d: &mut FieldTableDraft) { + let mut shares: Vec = d.table.columns.iter().map(|c| c.width).collect(); + let names: Vec = (0..shares.len()).map(column_label).collect(); + Text::new(tl!("Column widths").to_owned()).show(ui); + ColumnBar::new(tl!("Column widths").to_owned(), Bind::bound(&mut shares)).names(&names).show(ui); + if shares.len() == d.table.columns.len() { + for (column, share) in d.table.columns.iter_mut().zip(shares) { + column.width = share; } - if widgets::pill_button(ui, tl!("Cancel"), false).clicked() { - choice = Some(Choice::Cancel); + } + let more = d.table.columns.len() > 1; + if clicked(&Button::new(tl!("Distribute evenly").to_owned()).enabled(more).show(ui)) { + d.distribute_evenly(); + } +} + +/// How each column names its cells, with the width it has. +fn names(ui: &mut Ui, d: &mut FieldTableDraft, info: &PageInfo, form: &[FormField]) { + Text::new(tl!("Field names").to_owned()).show(ui); + // How the names are worked out. Its tokens are the same in every language. + Text::new(tl!("N or {row} is the row number, {col} the column number, {seq} the cell number. With none of them, the row number goes last.").to_owned()) + .show(ui); + // The widths shown don't depend on the names being typed below. + let layout = d.laid(info, form); + let total: f64 = d.table.columns.iter().map(|c| c.width).sum(); + Stack::new().scroll(Scroll::vertical()).show(ui, |ui, _| { + for (c, column) in d.table.columns.iter_mut().enumerate() { + let width = layout.cells.as_ref().ok().and_then(|cells| cells.get(c)).map(|cell| cell.rect[2] - cell.rect[0]); + let share = if total > 0.0 && total.is_finite() { column.width / total } else { 0.0 }; + let size = width.map_or_else(|| "—".to_owned(), |w| format!("{w:.1} pt · {:.0}%", share * 100.0)); + Field::new(format!("{} ({size})", column_label(c))).id_salt(("field table column", c)).show(ui, |ui, _| { + TextField::new(column_label(c), Bind::bound(&mut column.pattern)).show(ui); + }); } }); - (choice, laid) } /// "Column 2" for the column at 0-based `index`. @@ -316,144 +358,101 @@ fn column_label(index: usize) -> String { i18n::fmt(tl!("Column {n}"), &[("n", &index.saturating_add(1).to_string())]) } -/// A number with minus and plus buttons either side, held to `range`, moving by `step`. Whether it -/// changed. -fn stepper(ui: &mut egui::Ui, value: &mut N, range: RangeInclusive, step: f64, suffix: &str) -> bool { - let before = *value; - let (low, high) = (range.start().to_f64(), range.end().to_f64()); - ui.horizontal(|ui| { - if ui.button("-").clicked() { - *value = N::from_f64((value.to_f64() - step).max(low)); - } - ui.add(egui::DragValue::new(value).range(range).speed(step / 2.0).suffix(suffix)); - if ui.button("+").clicked() { - *value = N::from_f64((value.to_f64() + step).min(high)); - } - }); - *value != before +/// The look of the table preview on the page: the cells and the reason a table can't be laid out. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub(crate) struct TablePreviewStyle { + #[style(metrics)] + metrics: Metrics, + /// A cell's outline and name: the selection role. + cell: StyleColor, + /// The outline of a table that can't be laid out, and the reason. + bad: StyleColor, } -/// The columns as a bar with a divider between each two, dragged (or moved with the arrow keys once -/// focused) to share the width differently. -fn column_bar(ui: &mut egui::Ui, d: &mut FieldTableDraft, t: &theme::Tokens) { - let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width().max(100.0), 28.0), Sense::hover()); - let edges = |shares: &[f64]| -> Vec { - let mut x = bar.left(); - shares - .iter() - .map(|s| { - x += *s as f32 * bar.width(); - x - }) - .collect() - }; - let n = d.table.columns.len(); - let ends = edges(&d.shares()); - let active = column_dividers(ui, d, bar, &ends); +/// The table being set up, on its page: each cell with its name, or the table's outline with the reason it can't be laid +/// out. Only the cells in view are drawn, and only those with room for it get their name: a table can have 5,000 cells. +#[derive(craft::ui::contract::Component, craft::ui::contract::Props)] +#[component(canvas_control)] +pub(crate) struct TablePreview<'a> { + #[common] + common: Common, + preview: &'a Preview, + xf: PageXform, +} - let painter = ui.painter_at(bar); - // Input may have resized a pair; paint the shares after handling it. - let shares = d.shares(); - let mut left = bar.left(); - for (c, (&right, share)) in edges(&shares).iter().zip(&shares).enumerate() { - // The last column ends at the bar's edge, whatever rounding says. - let right = if c + 1 == n { bar.right() } else { right.min(bar.right()) }; - let column = Rect::from_min_max(pos2(left, bar.top()), pos2(right, bar.bottom())); - painter.rect_filled(column, CornerRadius::ZERO, SELECT_BLUE.gamma_multiply(if c % 2 == 0 { 0.11 } else { 0.055 })); - if column.width() > 32.0 { - painter.text(column.center(), egui::Align2::CENTER_CENTER, format!("{:.0}%", share * 100.0), theme::medium(11.0), t.text); - } - left = right; - } - painter.rect_stroke(bar, CornerRadius::same(3), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - for (i, &x) in edges(&shares).iter().enumerate().take(n.saturating_sub(1)) { - let stroke = if active == Some(i) { Stroke::new(3.0, SELECT_BLUE) } else { Stroke::new(1.5, t.border) }; - painter.line_segment([pos2(x, bar.top() + 1.0), pos2(x, bar.bottom() - 1.0)], stroke); +impl<'a> TablePreview<'a> { + /// The preview named `label`, on the page `xf` places on screen. + pub(crate) fn new(label: impl Into