diff --git a/crates/ui-egui/src/panels/all_tools_ui.rs b/crates/ui-egui/src/panels/all_tools_ui.rs index 917bdb0515..aafa9dadd8 100644 --- a/crates/ui-egui/src/panels/all_tools_ui.rs +++ b/crates/ui-egui/src/panels/all_tools_ui.rs @@ -2,134 +2,57 @@ //! field, filling the workspace instead of the sidebar. The sidebar's expand button opens it; //! its collapse button, Esc or choosing a tool closes it again. -use egui::{Align2, Color32, CornerRadius, Rect, Sense, Stroke, vec2}; +use std::hash::{Hash, Hasher}; + +use craft::behavior::{IconId, Selection}; +use craft::i18n::matcher::Matcher; +use craft::keymap::CommandRef; +use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::primitives::IconSpec; +use craft::ui::sections::{HeaderCommand, Panel}; +use craft::ui::style::DataColor; +use craft::ui::text::TextField; +use craft::ui::tile_grid::{BadgeKind, BadgeSlot, Tile, TileBadge, TileGrid, TileGroup}; +use egui::Color32; use pdfcraft_engine::catalog::{self, Availability, TOOL_CATEGORIES, ToolGroup}; -use crate::theme::{self, Tokens}; -use crate::{PdfCraftApp, icons, widgets}; +use super::tools::Rows; +use crate::PdfCraftApp; -const TILE: egui::Vec2 = vec2(148.0, 118.0); /// Item names a tile lists when the search found the tool by them. const MATCHES_SHOWN: usize = 2; -/// Whether `query` (already trimmed and lower-cased) is in `label` or its translation. -/// Translations and queries stay in logical order. For right-to-left labels, also accept -/// multiword queries in a different word order, as in the command palette. -fn label_hit(label: &str, translated: &str, query: &str, rtl: bool) -> bool { - let translated = translated.to_lowercase(); - label.to_lowercase().contains(query) - || translated.contains(query) - || (rtl && query.contains(char::is_whitespace) && query.split_whitespace().all(|word| translated.contains(word))) -} - -/// Whether `group` matches `query` (already trimmed and lower-cased), in English or the UI -/// language. `None` is no match; otherwise the items that matched, empty when the tool's own -/// name did. An entry with a menu (Watermark: Add, Update, Remove) also matches by its commands' +/// Whether `group` matches the query `matcher` holds, in English or the UI language. `None` is no +/// match; otherwise the items that matched, empty when the tool's own name did (or the query is +/// empty). An entry with a menu (Watermark: Add, Update, Remove) also matches by its commands' /// names, so "remove watermark" finds it. -fn matches(query: &str, group: &ToolGroup) -> Option> { - let rtl = crate::i18n::current().rtl(); - let hit = |label: &str| label_hit(label, tl!(label), query, rtl); - if query.is_empty() || hit(group.label) { +fn matches(matcher: &Matcher, group: &ToolGroup) -> Option> { + let hit = |label: &str| matcher.score(label).is_some() || matcher.score(tl!(label)).is_some(); + if hit(group.label) { return Some(Vec::new()); } let action_hit = |id: &&str| { - pdfcraft_engine::commands::command(id).is_some_and(|spec| label_hit(spec.label, &crate::i18n::menu_label(spec.id, spec.label), query, rtl)) + pdfcraft_engine::commands::command(id) + .is_some_and(|spec| matcher.score(spec.label).is_some() || matcher.score(&crate::i18n::menu_label(spec.id, spec.label)).is_some()) }; let items: Vec<_> = group.sections.iter().flat_map(|s| s.items.iter()).filter(|i| hit(i.label) || i.actions.iter().any(action_hit)).map(|i| i.label).collect(); (!items.is_empty()).then_some(items) } -/// Draw the view over the workspace: the title with Collapse, the search field, and each -/// category's tiles that match the search. Choosing a tile opens that tool's panel. -pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); - // A dialog, prompt or the command palette over the view owns Escape. - if !app.modal_open() && !app.palette_open && ui.input(|i| i.key_pressed(egui::Key::Escape)) { - app.all_tools_full = false; - return; - } - let mut chosen = None; - egui::Frame::NONE.fill(t.panel).show(ui, |ui| { - ui.set_min_size(ui.available_size()); - egui::Frame::NONE.inner_margin(egui::Margin { left: 36, right: 28, top: 20, bottom: 12 }).show(ui, |ui| { - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("All tools")).font(theme::semibold(22.0)).color(t.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icons::button(ui, "minimize-2", 28.0, false, tl!("Collapse all tools")).clicked() { - app.all_tools_full = false; - } - }); - }); - ui.add_space(10.0); - let field = ui.add( - widgets::line(&mut app.all_tools_query).hint_text(tl!("Search tools and commands…")).desired_width(ui.available_width().min(520.0)), - ); - // Typing goes straight to the search, as in Acrobat's tools view. - if !ui.memory(|m| m.focused().is_some()) { - field.request_focus(); - } - }); - ui.separator(); - let query = app.all_tools_query.trim().to_lowercase(); - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - egui::Frame::NONE.inner_margin(egui::Margin { left: 36, right: 28, top: 8, bottom: 28 }).show(ui, |ui| { - ui.set_width(ui.available_width()); - let mut any = false; - for category in TOOL_CATEGORIES { - let found: Vec<_> = - category.groups.iter().filter_map(|id| catalog::group(id)).filter_map(|g| matches(&query, g).map(|m| (g, m))).collect(); - if found.is_empty() { - continue; - } - any = true; - ui.add_space(12.0); - ui.label(egui::RichText::new(tl!(category.label)).font(theme::semibold(16.0)).color(t.text)); - ui.add_space(10.0); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(14.0, 14.0); - for (g, items) in found { - if tile(ui, &t, g, &items).clicked() { - chosen = Some(g.id); - } - } - }); - ui.add_space(8.0); - } - if !any { - ui.add_space(24.0); - ui.label(egui::RichText::new(tl!("No tools match your search.")).color(t.text_muted)); - } - }); - }); - }); - if let Some(id) = chosen { - app.left_open = true; - app.select_tool(id); - } +/// Identifies the set of tiles a query shows, so the grid's lead starts over when it changes. +fn query_stamp(query: &str) -> u64 { + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + query.hash(&mut hasher); + hasher.finish() } /// One tool's tile: its icon and name, then the `items` the search found it by or, when there are -/// none, its availability (a planned tool is greyed out with its milestone). A name or note cut -/// short shows in full on hover. -fn tile(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup, items: &[&'static str]) -> egui::Response { - let (rect, resp) = ui.allocate_exact_size(TILE, Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(g.label))); - let press = theme::Press::track(ui, &resp); - crate::home::card_lift(ui, t, rect, press); - ui.painter().rect(rect, CornerRadius::same(10), press.fill(t.card, t.hover, t.pressed), Stroke::new(1.0, t.divider), egui::StrokeKind::Inside); - let body = rect.translate(press.offset()); - let ready = g.availability == Availability::Ready; - let hue = Color32::from_rgb(g.hue[0], g.hue[1], g.hue[2]); - icons::paint(ui, Rect::from_center_size(body.center_top() + vec2(0.0, 34.0), vec2(32.0, 32.0)), g.icon, 30.0, hue); - let mut job = - egui::text::LayoutJob::simple(tl!(g.label).to_owned(), theme::medium(13.0), if ready { t.text } else { t.text_muted }, body.width() - 16.0); - job.halign = egui::Align::Center; - job.wrap.max_rows = 2; - let title = ui.fonts_mut(|f| f.layout_job(job)); - let mut elided = title.elided; - let title_h = title.size().y; - ui.painter().galley(body.center_top() + vec2(0.0, 60.0), title, t.text); +/// none, its availability (a planned tool is dimmed with its milestone). +fn tile(g: &'static ToolGroup, items: &[&'static str]) -> Tile<'static> { + let mut tile = Tile::new(tl!(g.label).to_owned()) + .icon(IconSpec::svg(IconId::new(g.icon))) + .hue(DataColor::new(Color32::from_rgb(g.hue[0], g.hue[1], g.hue[2]))); // What found the tool, or else whether it works today. let note = if items.is_empty() { match g.availability { @@ -141,60 +64,117 @@ fn tile(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup, items: &[&'static str]) -> items.iter().take(MATCHES_SHOWN).map(|l| tl!(l)).collect::>().join(" · ") }; if !note.is_empty() { - let color = if items.is_empty() { t.text_faint } else { t.accent_text }; - let mut job = egui::text::LayoutJob::simple_singleline(note.clone(), theme::regular(11.0), color); - job.halign = egui::Align::Center; - job.wrap = egui::text::TextWrapping { max_width: body.width() - 16.0, max_rows: 1, break_anywhere: true, ..Default::default() }; - let galley = ui.fonts_mut(|f| f.layout_job(job)); - elided |= galley.elided; - ui.painter().galley(body.center_top() + vec2(0.0, 64.0 + title_h), galley, color); + tile = tile.detail(note); } - if let Some(b) = g.badge.filter(|_| g.availability == Availability::Ready) { - let font = theme::semibold(9.5); - let w = widgets::text_width(ui, tl!(b), &font); - let r = Rect::from_min_size(body.right_top() + vec2(-w - 18.0, 8.0), vec2(w + 10.0, 16.0)); - ui.painter().rect_filled(r, CornerRadius::same(4), t.badge_new); - ui.painter().text(r.center(), Align2::CENTER_CENTER, tl!(b), font, Color32::WHITE); + if g.availability != Availability::Ready { + return tile.dimmed(); + } + match g.badge { + Some(b) => tile.badge(TileBadge::new(BadgeSlot::EndTop, BadgeKind::Text(tl!(b).to_owned().into()), craft::theme::variant::Tone::Accent, None)), + None => tile, + } +} + +/// Draw the view over the workspace: the title with Collapse, the search field, and each +/// category's tiles that match the search. Choosing a tile opens that tool's panel. +pub fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { + // A dialog, prompt or the command palette over the view owns Escape. + if !app.modal_open() && !app.palette_open && ui.input(|i| i.key_pressed(egui::Key::Escape)) { + app.all_tools_full = false; + return; + } + let mut chosen = None; + Panel::new(tl!("All tools").to_owned()) + .titled() + .commands([HeaderCommand::new(IconId::new("minimize-2"), CommandRef::new("tools.collapse"))]) + .show(ui, |ui, _| { + // PLAN: framework gap F-6 (a one-shot focus request): the search field took focus when the view opened and nothing else had it. + TextField::search(tl!("Search tools and commands…").to_owned(), Bind::bound(&mut app.all_tools_query)).show(ui); + let query = app.all_tools_query.trim().to_owned(); + let matcher = Matcher::new(&craft::i18n::Folder::new(crate::i18n::current().code()), &query); + + let mut shown: Vec<(&'static ToolGroup, Vec<&'static str>)> = Vec::new(); + let mut spans = Vec::new(); + for category in TOOL_CATEGORIES { + let start = shown.len(); + shown.extend(category.groups.iter().filter_map(|id| catalog::group(id)).filter_map(|g| matches(&matcher, g).map(|m| (g, m)))); + if shown.len() > start { + spans.push((start, shown.len() - start, tl!(category.label).to_owned())); + } + } + // The header rows are keyed after the tiles, whose keys are their positions. + let groups: Vec> = + spans.into_iter().enumerate().map(|(at, (start, count, title))| TileGroup::new(shown.len() + at, start, count, title)).collect(); + let grid = TileGrid::::new(tl!("All tools").to_owned()) + .select(SelectMode::Single) + .activate(ActivateOn::Click) + .card() + .groups(&groups) + .selection(Bind::given(Selection::default())) + .rows_stamp(query_stamp(&query)) + .empty(tl!("No tools match your search.").to_owned()) + .show_items(ui, &Rows(shown.len()), &mut |at, _| match shown.get(*at) { + Some((g, items)) => tile(g, items), + None => Tile::new(String::new()), + }); + for event in &grid.response.events { + if let CollectionEvent::Activate(at) = event + && let Some((g, _)) = shown.get(*at) + { + chosen = Some(g.id); + } + } + }); + if let Some(id) = chosen { + app.left_open = true; + app.select_tool(id); } - let resp = if elided { resp.on_hover_text(format!("{}\n{note}", tl!(g.label))) } else { resp }; - theme::hand(resp) } #[cfg(test)] mod tests { use super::*; + use craft::i18n::Folder; fn group(id: &str) -> &'static ToolGroup { catalog::group(id).expect("catalogue group") } + fn find(query: &str, group: &ToolGroup) -> Option> { + matches(&Matcher::new(&Folder::new(crate::i18n::current().code()), query), group) + } + #[test] fn search_matches_tool_names_and_their_items() { - assert_eq!(matches("", group("organize")), Some(Vec::new()), "an empty query shows everything"); - assert_eq!(matches("organize", group("organize")), Some(Vec::new()), "the tool's own name"); - let rotate = matches("rotate", group("organize")).expect("Organize pages lists Rotate"); + assert_eq!(find("", group("organize")), Some(Vec::new()), "an empty query shows everything"); + assert_eq!(find("organize", group("organize")), Some(Vec::new()), "the tool's own name"); + let rotate = find("rotate", group("organize")).expect("Organize pages lists Rotate"); assert!(!rotate.is_empty() && rotate.iter().all(|l| l.to_lowercase().contains("rotate")), "{rotate:?}"); - assert_eq!(matches("no such tool anywhere", group("organize")), None); + assert_eq!(find("no such tool anywhere", group("organize")), None); } #[test] fn search_finds_an_entry_by_its_menus_commands() { - let found = matches("remove watermark", group("edit")).expect("Watermark's menu has Remove watermark"); + let found = find("remove watermark", group("edit")).expect("Watermark's menu has Remove watermark"); assert!(found.contains(&"Watermark"), "{found:?}"); } #[test] - fn right_to_left_labels_match_a_query_typed_in_logical_order() { + fn a_tool_is_found_by_its_english_name_in_another_language() { if !crate::i18n::needs_catalogs() { return; } - let arabic = crate::i18n::Lang::from_code("ar").expect("Arabic is registered"); - let translated = crate::i18n::tr(arabic, "Organize pages"); - assert_eq!(translated, "تنظيم الصفحات", "the catalogue keeps logical text"); - assert!(label_hit("Organize pages", translated, "تنظيم الصفحات", true)); - assert!(label_hit("Organize pages", translated, "الصفحات", true), "one word"); - assert!(label_hit("Organize pages", translated, "الصفحات تنظيم", true), "RTL word-order fallback"); - assert!(!label_hit("Organize pages", translated, "تنظيم الملفات", true), "every word must be there"); - assert!(!label_hit("Organize pages", translated, "الصفحات تنظيم", false), "left-to-right labels stay exact"); + let french = crate::i18n::Lang::from_code("fr").expect("French is registered"); + let before = crate::i18n::current(); + crate::i18n::set_current(french); + let organize = group("organize"); + let translated = crate::i18n::tr(french, organize.label); + let by_english = find(organize.label, organize); + let by_translation = find(translated, organize); + let unrelated = find("zzzz", organize); + crate::i18n::set_current(before); + assert_eq!(by_english, Some(Vec::new()), "the English name still finds the tool"); + assert_eq!(by_translation, Some(Vec::new()), "and so does its translation"); + assert_eq!(unrelated, None); } } diff --git a/crates/ui-egui/src/panels/organize_panel.rs b/crates/ui-egui/src/panels/organize_panel.rs index 77f1b250d5..af7f0db28f 100644 --- a/crates/ui-egui/src/panels/organize_panel.rs +++ b/crates/ui-egui/src/panels/organize_panel.rs @@ -8,12 +8,18 @@ //! The page actions queue on the view (`pending_edit`, `pending_action`) exactly as the grid's //! toolbar did, so they run, refuse and undo the same way. -use egui::{Align2, CornerRadius, Rect, Sense, Stroke, vec2}; +use craft::behavior::{IconId, Selection}; +use craft::pages::ui::PageRangeField; +use craft::ui::buttons::IconButton; +use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::layout_components::Row; +use craft::ui::list::{List, ListRow, RowInk}; +use craft::ui::primitives::IconSpec; use pdfcraft_engine::Edit; +use super::tools::{Rows, caption_row}; use crate::canvas::ViewAction; -use crate::theme::{self, Tokens}; -use crate::{LeftPanel, PdfCraftApp, icons, widgets}; +use crate::{LeftPanel, PdfCraftApp}; /// Whether the left panel is Organize pages: the tool is chosen, or the active view shows the grid. pub(crate) fn showing(app: &PdfCraftApp) -> bool { @@ -39,215 +45,138 @@ enum Act { Command(&'static str), } -pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) { +/// One line of the panel's list. +enum Line { + Heading(&'static str), + Row { + icon: &'static str, + label: &'static str, + act: Option, + /// Whether the row works now: needs page assembly allowed. + enabled: bool, + /// Not in PdfCraft yet: shown dimmed, as Acrobat lists it, and says it is planned when hovered. + later: bool, + /// Starts a group: room above it. + space: bool, + }, +} + +/// The menu of the page range field: pages by kind. +fn page_menu(info: &pdfcraft_render::DocInfo, n: usize) -> Vec>> { + use pdfcraft_engine::{PageOrientation as O, PageParity as P, filter_pages}; + let all: Vec = (0..n).collect(); + let mut entries: Vec>> = [ + ("All pages", P::Both, O::Both), + ("Even pages", P::Even, O::Both), + ("Odd pages", P::Odd, O::Both), + ("Landscape pages", P::Both, O::Landscape), + ("Portrait pages", P::Both, O::Portrait), + ] + .into_iter() + .map(|(label, parity, orient)| Entry::new(filter_pages(info, &all, parity, orient), tl!(label).to_owned())) + .collect(); + entries.push(Entry::new(Vec::new(), tl!("None").to_owned())); + entries +} + +/// The Organize pages body. Its Back (`tools.all`) and Close belong to the dock's group header. +// PLAN: the panel's own Close (it also closed the page grid and went back to the workspace's panel) is now the +// dock's Close; pdf-chrome-w13's group header owns closing the grid with it. +pub(crate) fn panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { let Some((index, id)) = app.active_ids() else { return }; let Some(doc) = app.session.get(id) else { return }; let info = &doc.info; let editable = doc.allows_assembly(); let n = info.pages.len(); let mut act: Option = None; - let mut back = false; - let mut close = false; let Some(view) = app.views.get_mut(index) else { return }; - ui.horizontal(|ui| { - if icons::button(ui, "chevron-left", 26.0, false, tl!("Back to all tools")).clicked() { - back = true; - } - let title = tl!("Organize pages"); - let title_width = (ui.available_width() - 26.0 - ui.spacing().item_spacing.x).max(1.0); - ui.add_sized([title_width, 26.0], egui::Label::new(egui::RichText::new(title).font(theme::semibold(15.5)).color(t.text)).truncate()) - .on_hover_text(title); - if icons::button(ui, "x", 26.0, false, tl!("Close panel")).clicked() { - close = true; - } - }); - ui.add_space(4.0); - ui.separator(); - ui.add_space(6.0); - - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - ui.add_space(2.0); - widgets::section_title(ui, tl!("Pages selected")); - let current = view.current; - let picked = view.organize_range.show(ui, &view.selected, n, current, |ui| { - use pdfcraft_engine::{PageOrientation as O, PageParity as P, filter_pages}; - let all: Vec = (0..n).collect(); - let mut chosen = None; - for (label, parity, orient) in [ - ("All pages", P::Both, O::Both), - ("Even pages", P::Even, O::Both), - ("Odd pages", P::Odd, O::Both), - ("Landscape pages", P::Both, O::Landscape), - ("Portrait pages", P::Both, O::Portrait), - ] { - if ui.button(tl!(label)).clicked() { - chosen = Some(filter_pages(info, &all, parity, orient)); - } - } - if ui.button(tl!("None")).clicked() { - chosen = Some(Vec::new()); - } - chosen - }); - if let Some(pages) = picked { - view.select_pages(&pages); - } - - let targets = view.target_pages(); - let last = targets.last().copied().unwrap_or(0); - widgets::section_title(ui, tl!("Page options")); - ui.add_enabled_ui(editable, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 6.0; - if icons::button(ui, "rotate-ccw", 34.0, false, tl!("Rotate counterclockwise")).clicked() { - act = Some(Act::Edit(Box::new(Edit::RotatePages { pages: targets.clone(), degrees: -90 }))); - } - if icons::button(ui, "rotate-cw", 34.0, false, tl!("Rotate clockwise")).clicked() { - act = Some(Act::Edit(Box::new(Edit::RotatePages { pages: targets.clone(), degrees: 90 }))); - } - // A document keeps at least one page. - let can_delete = targets.len() < n; - if ui.add_enabled_ui(can_delete, |ui| icons::button(ui, "trash-2", 34.0, false, tl!("Delete pages (Delete)"))).inner.clicked() { - act = Some(Act::Edit(Box::new(Edit::DeletePages { pages: targets.clone() }))); - } - if icons::button(ui, "file-output", 34.0, false, tl!("Extract pages to a new document")).clicked() { - act = Some(Act::View(ViewAction::Extract)); - } - }); - ui.add_space(2.0); - // Insert ▸: a blank page, pages from a file, or copies of the selected pages. - let insert = row(ui, t, "file-plus-2", tl!("Insert"), Availability::Ready, true); - egui::Popup::menu(&insert).align(egui::RectAlign::RIGHT_START).gap(6.0).show(|ui| { - if ui.button(tl!("Insert a blank page after the selection")).clicked() { - let crop = info.pages.get(last).map_or([0.0, 0.0, 612.0, 792.0], |p| p.crop); - let (w, h) = ((crop[2] - crop[0]).abs().max(1.0) as f64, (crop[3] - crop[1]).abs().max(1.0) as f64); - act = Some(Act::Edit(Box::new(Edit::InsertBlankPage { at: last.saturating_add(1), width: w, height: h }))); - } - if ui.button(tl!("Insert pages from a file…")).clicked() { - act = Some(Act::View(ViewAction::InsertFromFile)); - } - if ui.button(tl!("Duplicate pages")).clicked() { - act = Some(Act::Command("page.duplicate")); - } - }); - if row(ui, t, "replace", tl!("Replace"), Availability::Ready, false).clicked() { - act = Some(Act::View(ViewAction::ReplacePages)); - } - if row(ui, t, "scissors", tl!("Split"), Availability::Ready, false).clicked() { - act = Some(Act::View(ViewAction::Split)); - } - }); - if row(ui, t, "hash", tl!("Bates numbering"), Availability::Ready, false).clicked() { - act = Some(Act::Command("edit.bates")); - } - divider(ui, t); - for (icon, label, availability, command) in [ - ("square-dashed-mouse-pointer", "Set page boxes", Availability::Ready, Some("page.boxes")), - ("crop", "Crop pages", Availability::Ready, Some("page.crop")), - ("presentation", "Page transitions", Availability::Later, Some("page.transitions")), - ("file-text", "Page templates", Availability::Later, None), - ("printer", "Print pages", Availability::Ready, Some("print.dialog")), - ] { - if row(ui, t, icon, tl!(label), availability, false).clicked() - && let Some(command) = command - { - act = Some(Act::Command(command)); - } - } - divider(ui, t); - if row(ui, t, "tag", tl!("Page labels"), Availability::Ready, false).clicked() { - act = Some(Act::Command("page.number")); - } - if row(ui, t, "info", tl!("Page properties"), Availability::Ready, false).clicked() { - act = Some(Act::Command("page.properties")); - } - }); - - if close { - view.organize = false; - app.left = workspace_panel(app.mode); - } else if back { - view.organize = false; - app.left = LeftPanel::AllTools; + caption_row(ui, tl!("Pages selected"), true); + let current = view.current; + let selected: Vec = view.selected.iter().copied().collect(); + let entries = page_menu(info, n); + let picked = PageRangeField::new(tl!("Pages selected").to_owned(), &selected, n, current).menu(&entries).show(ui).picked; + if let Some(pages) = picked { + view.select_pages(&pages); } + + let targets = view.target_pages(); + let last = targets.last().copied().unwrap_or(0); + caption_row(ui, tl!("Page options"), true); + // A document keeps at least one page. + let can_delete = editable && targets.len() < n; + Row::new().show(ui, |ui, _| { + let buttons = [ + ("rotate-ccw", "Rotate counterclockwise", editable), + ("rotate-cw", "Rotate clockwise", editable), + ("trash-2", "Delete pages (Delete)", can_delete), + ("file-output", "Extract pages to a new document", editable), + ]; + for (at, (icon, label, enabled)) in buttons.into_iter().enumerate() { + if !IconButton::new(IconId::new(icon)).label(tl!(label).to_owned()).enabled(enabled).show(ui).clicked() { + continue; + } + act = Some(match at { + 0 => Act::Edit(Box::new(Edit::RotatePages { pages: targets.clone(), degrees: -90 })), + 1 => Act::Edit(Box::new(Edit::RotatePages { pages: targets.clone(), degrees: 90 })), + 2 => Act::Edit(Box::new(Edit::DeletePages { pages: targets.clone() })), + _ => Act::View(ViewAction::Extract), + }); + } + }); + + // Insert: a blank page, pages from a file, or copies of the selected pages. + let crop = info.pages.get(last).map_or([0.0, 0.0, 612.0, 792.0], |p| p.crop); + let (w, h) = ((crop[2] - crop[0]).abs().max(1.0) as f64, (crop[3] - crop[1]).abs().max(1.0) as f64); + let row = |icon, label, act, enabled, later, space| Line::Row { icon, label, act, enabled, later, space }; + let mut lines = vec![ + Line::Heading("Insert"), + row( + "file-plus-2", + "Insert a blank page after the selection", + Some(Act::Edit(Box::new(Edit::InsertBlankPage { at: last.saturating_add(1), width: w, height: h }))), + editable, + false, + false, + ), + row("file-plus-2", "Insert pages from a file…", Some(Act::View(ViewAction::InsertFromFile)), editable, false, false), + row("copy", "Duplicate pages", Some(Act::Command("page.duplicate")), editable, false, false), + row("replace", "Replace", Some(Act::View(ViewAction::ReplacePages)), editable, false, true), + row("scissors", "Split", Some(Act::View(ViewAction::Split)), editable, false, false), + row("hash", "Bates numbering", Some(Act::Command("edit.bates")), true, false, false), + row("square-dashed-mouse-pointer", "Set page boxes", Some(Act::Command("page.boxes")), true, false, true), + row("crop", "Crop pages", Some(Act::Command("page.crop")), true, false, false), + row("presentation", "Page transitions", Some(Act::Command("page.transitions")), true, true, false), + row("file-text", "Page templates", None, true, true, false), + row("printer", "Print pages", Some(Act::Command("print.dialog")), true, false, false), + row("tag", "Page labels", Some(Act::Command("page.number")), true, false, true), + row("info", "Page properties", Some(Act::Command("page.properties")), true, false, false), + ]; + let out = List::::new(tl!("Page actions").to_owned()) + .select(SelectMode::Single) + .activate(ActivateOn::Click) + .selection(Bind::given(Selection::default())) + .show_items(ui, &Rows(lines.len()), &mut |at, _| match lines.get(*at) { + Some(Line::Heading(title)) => ListRow::new(tl!(title).to_owned()).heading().ink(RowInk::Dimmed), + Some(Line::Row { icon, label, enabled, later, space, .. }) => { + let row = ListRow::new(tl!(label).to_owned()).icon(IconSpec::svg(IconId::new(icon))).enabled(*enabled).space_above(*space); + if *later { row.ink(RowInk::Dimmed).tooltip(tl!("Planned").to_owned()) } else { row } + } + None => ListRow::spacer(), + }); + for event in out.events { + if let CollectionEvent::Activate(at) = event + && let Some(Line::Row { act: slot, enabled: true, later: false, .. }) = lines.get_mut(at) + && let Some(done) = slot.take() + { + act = Some(done); + } + } + match act { Some(Act::Edit(edit)) => view.pending_edit = Some(*edit), Some(Act::View(action)) => view.pending_action = Some(action), Some(Act::Command(command)) => app.run_command(command), None => {} } - // Leaving the workspace needs the whole app, so it waits until the view is done with: leaving - // Edit puts Edit text down and applies a paragraph still open on the page. - if back && !close { - app.enter_mode(crate::Mode::AllTools); - } -} - -/// Page Properties ▸ Tab Order for the pages it opened on: Use Row Order, Use Column Order, Use -/// Document Structure and Unspecified, then OK and Cancel. OK is off until a choice is made. -/// Returns (OK, Cancel). -pub(crate) fn page_props_body(ui: &mut egui::Ui, d: &mut crate::PagePropsDraft) -> (bool, bool) { - use pdfcraft_engine::TabOrder; - ui.label(egui::RichText::new(tl!("Page Properties")).font(theme::semibold(18.0))); - widgets::section_title(ui, tl!("Tab Order")); - for (order, label) in [ - (TabOrder::Row, tl!("Use Row Order")), - (TabOrder::Column, tl!("Use Column Order")), - (TabOrder::Structure, tl!("Use Document Structure")), - (TabOrder::Annotations, tl!("Unspecified")), - ] { - widgets::radio_value(ui, &mut d.tab_order, Some(order), label); - } - let (mut ok, mut cancel) = (false, false); - ui.add_space(12.0); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ok = ui.add_enabled_ui(d.tab_order.is_some(), |ui| widgets::pill_button(ui, tl!("OK"), true)).inner.clicked(); - cancel = widgets::pill_button(ui, tl!("Cancel"), false).clicked(); - }); - (ok, cancel) -} - -/// Whether a row works in this build. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Availability { - Ready, - /// Not in PdfCraft yet: shown muted, as Acrobat lists it, and says it is planned when hovered. - Later, -} - -/// One row of the panel: a monochrome icon and the label, as Acrobat draws them, with a corner -/// mark when it opens a menu. -fn row(ui: &mut egui::Ui, t: &Tokens, icon: &str, label: &str, availability: Availability, menu: bool) -> egui::Response { - let ready = availability == Availability::Ready && ui.is_enabled(); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), if ready { Sense::click() } else { Sense::hover() }); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, ready, label)); - let press = theme::Press::track(ui, &resp); - if ready { - press.wash(ui, rect, 6, false); - } - let body = rect.translate(press.offset()); - let fg = if ready { t.text } else { t.text_faint }; - let icon_rect = Rect::from_min_size(body.min + vec2(6.0, 8.0), vec2(18.0, 18.0)); - icons::paint(ui, icon_rect, icon, 17.0, fg); - let font = theme::regular(13.5); - let width = crate::widgets::text_width(ui, label, &font); - ui.painter().text(body.left_center() + vec2(34.0, 0.0), Align2::LEFT_CENTER, label, font, fg); - if menu { - // The small corner triangle Acrobat puts after a label that opens a menu. - let tip = body.left_center() + vec2(34.0 + width + 6.0, 6.0); - let tri = vec![tip, tip + vec2(-5.0, 0.0), tip + vec2(0.0, -5.0)]; - ui.painter().add(egui::Shape::convex_polygon(tri, fg, Stroke::NONE)); - } - match availability { - Availability::Ready => theme::hand(resp), - Availability::Later => resp.on_hover_text(tl!("Planned")), - } -} - -fn divider(ui: &mut egui::Ui, t: &Tokens) { - ui.add_space(6.0); - let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 1.0), Sense::hover()); - ui.painter().rect_filled(r, CornerRadius::ZERO, t.divider); - ui.add_space(6.0); } diff --git a/crates/ui-egui/src/panels/page_selection_ui.rs b/crates/ui-egui/src/panels/page_selection_ui.rs deleted file mode 100644 index deb811768e..0000000000 --- a/crates/ui-egui/src/panels/page_selection_ui.rs +++ /dev/null @@ -1,157 +0,0 @@ -//! The Organize Pages selection, as an editable list of physical page numbers. -use std::collections::BTreeSet; - -use pdfcraft_engine::print::PrintError; - -#[derive(Default)] -pub(crate) struct PageSelectionInput { - text: String, - selection: BTreeSet, - error: Option, -} - -/// Blank clears the explicit selection. Repeated/reversed ranges become a sorted set. -/// Bound both the input and expansion work, including repeated overlapping ranges. -pub(crate) fn parse(text: &str, count: usize) -> Result, PrintError> { - if text.len() > 16_384 { - return Err(PrintError::NotAPage(text.chars().take(80).collect())); - } - if text.trim().is_empty() { - return Ok(Vec::new()); - } - let mut pages = BTreeSet::new(); - let mut budget = 1_000_000usize; - let number = |token: &str| { - let t = token.trim(); - let n = - if t.bytes().all(|b| b.is_ascii_digit()) { t.parse::().ok() } else { None }.ok_or_else(|| PrintError::NotAPage(token.into()))?; - if n == 0 || n > count { Err(PrintError::OutOfRange(n, count)) } else { Ok(n - 1) } - }; - for part in text.split([',', ';']).map(str::trim) { - let (a, b) = if let Some((a, b)) = part.split_once('-') { - (number(a)?, number(b)?) - } else { - let p = number(part)?; - (p, p) - }; - let (a, b) = (a.min(b), a.max(b)); - let size = b.saturating_sub(a).saturating_add(1); - budget = budget.checked_sub(size).ok_or_else(|| PrintError::NotAPage(part.into()))?; - pages.extend(a..=b); - } - Ok(pages.into_iter().collect()) -} - -fn formatted(pages: &BTreeSet) -> String { - let mut parts = Vec::new(); - let mut it = pages.iter().copied().peekable(); - while let Some(first) = it.next() { - let mut last = first; - while it.peek().is_some_and(|p| last.checked_add(1) == Some(*p)) { - if let Some(next) = it.next() { - last = next; - } - } - let first = first.saturating_add(1); - let last = last.saturating_add(1); - parts.push(if first == last { first.to_string() } else { format!("{first}-{last}") }); - } - parts.join(", ") -} - -impl PageSelectionInput { - /// The field, as Acrobat's Pages selected: typed pages apply on Enter or when the field loses - /// focus, and the chevron opens `menu` (pages by kind), whose choice is returned the same way. - /// With nothing selected it shows the current page (0-based `current`), which actions apply to. - pub(crate) fn show( - &mut self, - ui: &mut egui::Ui, - selected: &BTreeSet, - count: usize, - current: usize, - menu: impl FnOnce(&mut egui::Ui) -> Option>, - ) -> Option> { - if self.selection != *selected { - self.selection.clone_from(selected); - self.text = formatted(selected); - self.error = None; - } - let mut commit = false; - let id = ui.make_persistent_id("organize-page-range"); - // Egui can surrender focus before this frame's widgets run on Escape. - let cancel = ui.is_enabled() - && ui.memory(|m| m.has_focus(id) || m.had_focus_last_frame(id)) - && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)); - if cancel { - self.text = formatted(selected); - self.error = None; - ui.memory_mut(|m| m.surrender_focus(id)); - } - let mut chosen = None; - ui.horizontal(|ui| { - let label = tl!("Selected pages"); - let width = (ui.available_width() - 32.0).max(40.0); - let field = ui.add( - egui::TextEdit::singleline(&mut self.text) - .id(id) - .desired_width(width) - .char_limit(16_384) - .hint_text(current.saturating_add(1).to_string()), - ); - field.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, ui.is_enabled(), label)); - commit = ui.is_enabled() && !cancel && field.lost_focus(); - let pick = crate::icons::button(ui, "chevron-down", 26.0, false, tl!("Select pages")); - chosen = egui::Popup::menu(&pick).show(menu).and_then(|r| r.inner); - }); - if let Some(pages) = chosen { - self.selection = pages.iter().copied().collect(); - self.text = formatted(&self.selection); - self.error = None; - return Some(pages); - } - if cancel { - self.text = formatted(selected); - self.error = None; - } else if commit { - match parse(&self.text, count) { - Ok(pages) => { - self.selection = pages.iter().copied().collect(); - self.text = formatted(&self.selection); - self.error = None; - return Some(pages); - } - Err(e) => self.error = Some(e.said(&|s| crate::i18n::t(s).to_string())), - } - } - if let Some(error) = &self.error { - ui.label(error); - } - None - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn plus_sign_is_not_a_page_number() { - for text in ["+3", "+2-4", "2-+4"] { - assert!(matches!(parse(text, 100), Err(PrintError::NotAPage(_))), "{text}"); - } - } - - #[test] - fn selection_ranges_are_sorted_unique_and_bounded() { - let pages = parse("1,12,16-18,89,92,93,97,99", 100).unwrap(); - assert_eq!(pages, [0, 11, 15, 16, 17, 88, 91, 92, 96, 98]); - assert_eq!(formatted(&pages.into_iter().collect()), "1, 12, 16-18, 89, 92-93, 97, 99"); - assert_eq!(parse("3-1,2", 3).unwrap(), [0, 1, 2]); - assert!(parse(" ", 0).unwrap().is_empty()); - for text in ["0", "101", "1,", "x", "1--3", "18446744073709551616", "1-100000000"] { - assert!(parse(text, 100).is_err(), "{text}"); - } - assert!(parse(&"1,".repeat(10_000), 100).is_err()); - assert!(parse("1-1000000,1-1000000", 1_000_000).is_err()); - } -} diff --git a/crates/ui-egui/src/panels/tools.rs b/crates/ui-egui/src/panels/tools.rs index 24b46cb663..f3ea6e9ac0 100644 --- a/crates/ui-egui/src/panels/tools.rs +++ b/crates/ui-egui/src/panels/tools.rs @@ -1,333 +1,260 @@ +use craft::behavior::{DisplayOrder, IconId, ItemSource, Selection}; +use craft::ui::buttons::Button; +use craft::ui::choice::{Checkbox, Segmented}; +use craft::ui::contract::{ActivateOn, Bind, CollectionEvent, Entry, Props as _, SelectMode, Show as _, ShowCollection as _}; +use craft::ui::list::{HueTarget, List, ListRow, RowEvent, RowInk, TrailingFace, TrailingPart}; +use craft::ui::primitives::IconSpec; +use craft::ui::style::DataColor; +use egui::Color32; + use super::edit::{actions_menu, edit_panel, stamp_palette}; -use super::{ - Align2, Availability, Color32, CornerRadius, LeftPanel, PdfCraftApp, Rect, Sense, Stroke, TOOL_GROUPS, Tokens, ToolGroup, catalog, icons, theme, - vec2, widgets, -}; +use super::{Availability, LeftPanel, PdfCraftApp, TOOL_GROUPS, ToolGroup, ToolItem, catalog}; const COLLAPSED_TOOLS: usize = 14; -fn hue(g: &ToolGroup) -> Color32 { - Color32::from_rgb(g.hue[0], g.hue[1], g.hue[2]) +/// The pin part of a tool row. +const PIN: TrailingPart = TrailingPart::new(0); + +/// A display order over `0..len`, keyed by position: the source of a list or grid whose rows the caller builds from +/// its own vector. +pub(super) struct Rows(pub(super) usize); + +impl DisplayOrder for Rows { + fn len(&self) -> usize { + self.0 + } + + fn key(&self, at: usize) -> usize { + at + } + + fn index_of(&self, key: &usize) -> Option { + (*key < self.0).then_some(*key) + } + + fn text(&self, _: usize) -> Option> { + None + } +} + +impl ItemSource for Rows {} + +/// The colour a tool's data gives its icon. +pub(super) fn data_hue(g: &ToolGroup) -> DataColor { + DataColor::new(Color32::from_rgb(g.hue[0], g.hue[1], g.hue[2])) +} + +/// One line of text in the body: a section heading, or a quiet note. +pub(super) fn caption_row(ui: &mut egui::Ui, text: &str, heading: bool) { + let label = text.to_owned(); + List::::new(label.clone()).selection(Bind::given(Selection::default())).show_items(ui, &Rows(1), &mut |_, _| { + let row = ListRow::new(label.clone()); + if heading { row.heading().ink(RowInk::Dimmed) } else { row.ink(RowInk::Muted) } + }); } pub fn left_panel(app: &mut PdfCraftApp, ui: &mut egui::Ui) { - let t = Tokens::get(ui.ctx()); // Organize closed another way (the grid's Close, or a page opened from it) closes the tool too, // as its panel's Close does, back to the workspace's own panel. if app.left == LeftPanel::Tool("organize") && app.active.and_then(|i| app.views.get(i)).is_some_and(|v| !v.organize) { app.left = crate::organize_panel::workspace_panel(app.mode); } - egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin { left: 14, right: 14, top: 12, bottom: 10 }).stroke(Stroke::new(1.0, t.divider)).show( - ui, - |ui| match app.left { - // Organize pages has its own panel whenever the grid shows (with a document open). - _ if app.active.is_some() && crate::organize_panel::showing(app) => crate::organize_panel::panel(app, ui, &t), - LeftPanel::AllTools => all_tools(app, ui, &t), - LeftPanel::Tool(id) => match catalog::group(id) { - Some(g) => tool_detail(app, ui, &t, g), - None => app.left = LeftPanel::AllTools, - }, - LeftPanel::CalculationOrder => crate::calc_order_ui::panel(app, ui, &t), + match app.left { + // Organize pages has its own panel whenever the grid shows (with a document open). + _ if app.active.is_some() && crate::organize_panel::showing(app) => crate::organize_panel::panel(app, ui), + LeftPanel::AllTools => all_tools(app, ui), + LeftPanel::Tool(id) => match catalog::group(id) { + Some(g) => tool_detail(app, ui, g), + None => app.left = LeftPanel::AllTools, }, - ); -} - -/// A panel's title row: a leading button (`lead`: its icon and tooltip) when given, the title -/// and Close. Returns whether the leading button and Close were clicked. -pub(crate) fn panel_header(ui: &mut egui::Ui, t: &Tokens, title: &str, lead: Option<(&str, &str)>) -> (bool, bool) { - let mut go_back = false; - let mut close = false; - ui.horizontal(|ui| { - if let Some((icon, tip)) = lead - && icons::button(ui, icon, 26.0, false, tip).clicked() - { - go_back = true; - } - // Reserve space for Close before laying out the translated title. Long tool names - // must never expand the fixed-width sidebar or push the Close control off-screen. - let title_width = (ui.available_width() - 26.0 - ui.spacing().item_spacing.x).max(1.0); - ui.add_sized([title_width, 26.0], egui::Label::new(egui::RichText::new(tl!(title)).font(theme::semibold(15.5)).color(t.text)).truncate()) - .on_hover_text(tl!(title)); - if icons::button(ui, "x", 26.0, false, tl!("Close panel")).clicked() { - close = true; - } - }); - ui.add_space(4.0); - ui.separator(); - ui.add_space(6.0); - (go_back, close) -} - -/// Width kept free at the right of a scrolling list for the floating scrollbar. -const SCROLLBAR_GUTTER: f32 = 18.0; - -/// The scrollbar floats over the right edge: keeps the rows of the scroll area `ui` is in (and -/// their rounded hover wash) clear of it. -pub(super) fn clear_of_scrollbar(ui: &mut egui::Ui) { - ui.set_max_width((ui.available_width() - SCROLLBAR_GUTTER).max(0.0)); -} - -/// The All tools sidebar: Expand (the full view) and Close, then the tool list, the first few -/// tools until View more shows them all. -fn all_tools(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens) { - // Labels distinct from the Combine grid's Expand and Collapse, which can show beside them. - let (expand, close) = panel_header(ui, t, "All tools", Some(("maximize-2", tl!("Expand all tools")))); - if expand { - app.expand_all_tools(); + LeftPanel::CalculationOrder => crate::calc_order_ui::panel(app, ui), } - if close { - app.left_open = false; - } - egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { - clear_of_scrollbar(ui); - ui.add_space(2.0); - let shown = if app.all_tools_expanded { TOOL_GROUPS.len() } else { COLLAPSED_TOOLS.min(TOOL_GROUPS.len()) }; - for g in &TOOL_GROUPS[..shown] { - let (resp, pin_clicked) = tool_row(ui, t, g, app.is_tool_pinned(g.id)); - if pin_clicked { - app.toggle_pin_tool(g.id); - } else if resp.clicked() { - app.select_tool(g.id); - } - } - ui.add_space(4.0); - let more = if app.all_tools_expanded { "View less" } else { "View more" }; - if ui - .add( - egui::Label::new(egui::RichText::new(tl!(more)).color(t.accent_text).font(theme::medium(13.0))) - .selectable(false) - .sense(Sense::click()), - ) - .on_hover_cursor(egui::CursorIcon::PointingHand) - .clicked() - { - app.all_tools_expanded = !app.all_tools_expanded; - } - }); } -/// Draw a one-line row label without painting into the status chip or beyond the sidebar. -/// Accessibility retains the complete name through the row's WidgetInfo. -pub(super) fn row_label(ui: &mut egui::Ui, text: &str, font: egui::FontId, color: Color32, left_center: egui::Pos2, max_width: f32) -> bool { - let mut job = egui::text::LayoutJob::simple_singleline(text.to_owned(), font, color); - job.wrap = egui::text::TextWrapping { max_width: max_width.max(1.0), max_rows: 1, break_anywhere: true, ..Default::default() }; - let galley = ui.fonts_mut(|f| f.layout_job(job)); - let elided = galley.elided; - ui.painter().galley(left_center - vec2(0.0, galley.size().y / 2.0), galley, color); - elided -} - -/// Draw one tool-group row with its icon, label, badge and availability hint. -fn tool_row(ui: &mut egui::Ui, t: &Tokens, g: &ToolGroup, is_pinned: bool) -> (egui::Response, bool) { - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(g.label))); - let press = theme::Press::track(ui, &resp); - press.wash(ui, rect, 6, false); - let body = rect.translate(press.offset()); - icons::paint(ui, Rect::from_min_size(body.min + vec2(6.0, 7.0), vec2(20.0, 20.0)), g.icon, 19.0, hue(g)); - - let pin_rect = Rect::from_center_size(body.right_center() - vec2(14.0, 0.0), vec2(22.0, 22.0)); - let pin_resp = ui.interact(pin_rect, ui.scope_id().with(("pin_toggle_row", g.id)), Sense::click()); - let pin_hovered = pin_resp.hovered(); - let mut pin_clicked = false; - - let pin_space = 26.0; - let badge_or_hint_reserved = match (g.badge, g.availability) { - (Some(b), _) => ui.fonts_mut(|f| f.layout_no_wrap(tl!(b).to_owned(), theme::semibold(9.5), Color32::WHITE).size().x) + 18.0, - (None, Availability::Planned(m)) if resp.hovered() => { - let hint = format!("{} · {m}", tl!("Planned")); - ui.fonts_mut(|f| f.layout_no_wrap(hint, theme::medium(10.5), t.text_faint).size().x) + 10.0 - } - _ => 0.0, - }; - let right_reserved = pin_space + badge_or_hint_reserved + 8.0; - let clipped = - row_label(ui, tl!(g.label), theme::regular(13.5), t.text, body.left_center() + vec2(36.0, 0.0), rect.width() - 36.0 - right_reserved); - match (g.badge, g.availability) { - (Some(b), _) => { - let font = theme::semibold(9.5); - let badge = tl!(b); - let w = ui.fonts_mut(|f| f.layout_no_wrap(badge.to_string(), font.clone(), Color32::WHITE).size().x); - let r = Rect::from_center_size(body.right_center() - vec2(pin_space + w / 2.0 + 4.0, 0.0), vec2(w + 10.0, 16.0)); - ui.painter().rect_filled(r, CornerRadius::same(4), t.badge_new); - ui.painter().text(r.center(), Align2::CENTER_CENTER, badge, font, Color32::WHITE); - } - // Planned tools: a quiet milestone hint instead of a chip, so the list stays calm. - (None, Availability::Planned(m)) if resp.hovered() => { - ui.painter().text( - body.right_center() - vec2(pin_space + 4.0, 0.0), - Align2::RIGHT_CENTER, - format!("{} · {m}", tl!("Planned")), - theme::medium(10.5), - t.text_faint, - ); - } - _ => {} +/// One tool-group row: its icon, label, badge and the pin part. +fn tool_row(g: &'static ToolGroup, pinned: bool) -> ListRow<'static> { + let mut row = ListRow::new(tl!(g.label).to_owned()).icon(IconSpec::svg(IconId::new(g.icon))); + row = row.hue(data_hue(g), HueTarget::Icon); + if let Some(b) = g.badge { + row = row.trailing_named(tl!(b).to_owned(), tl!(b).to_owned()); } - - let row_hovered = ui.rect_contains_pointer(rect) || resp.hovered(); - if is_pinned || row_hovered || pin_hovered { - if pin_hovered { - ui.painter().rect_filled(pin_rect, CornerRadius::same(4), t.pressed); - } - let pin_tint = if is_pinned { - t.accent_text - } else if pin_hovered { - t.text - } else { - t.text_faint - }; - icons::paint(ui, pin_rect.shrink(3.0), "pin", 15.0, pin_tint); - let tip = if is_pinned { tl!("Unpin from Home") } else { tl!("Pin to Home") }; - pin_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tip)); - if theme::hand(pin_resp).on_hover_text(tip).clicked() { - pin_clicked = true; - } - } - + let pin_name = if pinned { tl!("Unpin from Home") } else { tl!("Pin to Home") }.to_owned(); + let face = TrailingFace::Icon(IconSpec::svg(IconId::new("pin"))); + row = if pinned { row.trailing_part(PIN, face, pin_name) } else { row.trailing_part_revealed(PIN, face, pin_name) }; let tip = match g.availability { Availability::Ready => tl!("Available").to_string(), Availability::Planned(m) => format!("{} {m} — {}", tl!("Planned for milestone"), tl!("open to see what it will include")), Availability::Provider => tl!("Optional: needs an AI provider you configure").into(), }; - let tip = if clipped { format!("{} — {tip}", tl!(g.label)) } else { tip }; - (theme::hand(resp).on_hover_text(tip), pin_clicked) + row.tooltip(tip) } -/// Draw the detail view for one tool group, dispatching its commands and tool-specific panels. -fn tool_detail(app: &mut PdfCraftApp, ui: &mut egui::Ui, t: &Tokens, g: &'static ToolGroup) { +/// The All tools sidebar body: the tool list, the first few tools until View more shows them all. Its Expand and +/// Close belong to the dock's group header. +fn all_tools(app: &mut PdfCraftApp, ui: &mut egui::Ui) { + let shown = if app.all_tools_expanded { TOOL_GROUPS.len() } else { COLLAPSED_TOOLS.min(TOOL_GROUPS.len()) }; + let pins: Vec = TOOL_GROUPS[..shown].iter().map(|g| app.is_tool_pinned(g.id)).collect(); + let out = List::::new(tl!("All tools").to_owned()) + .select(SelectMode::Single) + .activate(ActivateOn::Click) + .selection(Bind::given(Selection::default())) + .show_items(ui, &Rows(shown), &mut |at, _| match (TOOL_GROUPS.get(*at), pins.get(*at)) { + (Some(g), Some(pinned)) => tool_row(g, *pinned), + _ => ListRow::spacer(), + }); + for event in out.events { + match event { + CollectionEvent::Activate(at) => { + if let Some(g) = TOOL_GROUPS.get(at) { + app.select_tool(g.id); + } + } + CollectionEvent::Item(at, RowEvent::Trailing { part, .. }) if part == PIN => { + if let Some(g) = TOOL_GROUPS.get(at) { + app.toggle_pin_tool(g.id); + } + } + _ => {} + } + } + let more = if app.all_tools_expanded { "View less" } else { "View more" }; + if Button::new(tl!(more).to_owned()).show(ui).clicked() { + app.all_tools_expanded = !app.all_tools_expanded; + } +} + +/// A line of a tool's detail list. +#[derive(Clone, Copy)] +enum Line { + Heading(&'static str), + Item(&'static ToolItem), +} + +/// One item row: its icon, label and the availability chip. +fn item_row(g: &'static ToolGroup, item: &'static ToolItem) -> ListRow<'static> { + let ready = item.availability == Availability::Ready; + let chip = match item.availability { + Availability::Ready => tl!("Ready"), + Availability::Planned(m) => m, + Availability::Provider => "AI", + }; + let row = ListRow::new(tl!(item.label).to_owned()).icon(IconSpec::svg(IconId::new(item.icon))).trailing(tl!(chip).to_owned()); + if ready { + row.hue(data_hue(g), HueTarget::Icon).tooltip(format!("{} — {}", tl!(item.label), item.command)) + } else { + row.ink(RowInk::Dimmed).tooltip(tl!("Planned").to_owned()) + } +} + +/// The detail view for one tool group, dispatching its commands and tool-specific panels. Its Back and Close belong +/// to the dock's group header. +fn tool_detail(app: &mut PdfCraftApp, ui: &mut egui::Ui, g: &'static ToolGroup) { if g.id == "edit" { - edit_panel(app, ui, t, g); + edit_panel(app, ui, g); return; } - let (back, close) = panel_header(ui, t, g.label, Some(("chevron-left", tl!("Back to all tools")))); - if back { - app.left = LeftPanel::AllTools; - app.enter_mode(crate::Mode::AllTools); - } - if close { - app.left_open = false; - } if let Availability::Planned(m) = g.availability { - egui::Frame::NONE.fill(t.accent_soft).corner_radius(CornerRadius::same(8)).inner_margin(egui::Margin::same(10)).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label( - egui::RichText::new(format!("{} {m}. {}", tl!("Coming in milestone"), tl!("Items marked Ready work today."))) - .color(t.text) - .font(theme::regular(12.0)), - ); - }); + caption_row(ui, &format!("{} {m}. {}", tl!("Coming in milestone"), tl!("Items marked Ready work today.")), false); } if g.id == "measure" { - crate::measure_ui::panel(app, ui, t); + crate::measure_ui::panel(app, ui); return; } // Add a stamp: the palette. if g.id == "stamp" { - stamp_palette(app, ui, t); + stamp_palette(app, ui); return; } // Prepare a form: Preview fills the form as a reader would; Edit goes back. if g.id == "form" { if let Some(view) = app.active.and_then(|i| app.views.get_mut(i)) { - ui.add(widgets::checkbox(&mut view.prepare.show_tab_numbers, tl!("Show tab numbers"))); - ui.add_space(4.0); + Checkbox::new(Bind::bound(&mut view.prepare.show_tab_numbers)).label(tl!("Show tab numbers").to_owned()).show(ui); } - ui.horizontal(|ui| { - let label = if app.form_preview { "Edit fields" } else { "Preview" }; - if widgets::pill_button(ui, tl!(label), app.form_preview).on_hover_text(tl!("Try the form as people filling it in will see it")).clicked() - { - app.form_preview = !app.form_preview; - if app.form_preview { - app.quick_tool = crate::QuickTool::Select; - } + let entries = [Entry::new(false, tl!("Edit fields").to_owned()), Entry::new(true, tl!("Preview").to_owned())]; + let landed = Segmented::new(tl!("Form mode").to_owned(), Bind::given(app.form_preview), &entries) + .tooltip(tl!("Try the form as people filling it in will see it").to_owned()) + .show(ui) + .events + .landed() + .cloned(); + if let Some(preview) = landed { + app.form_preview = preview; + if preview { + app.quick_tool = crate::QuickTool::Select; } - }); - ui.add_space(6.0); + } } let mut run = None; // Redact a PDF has Acrobat's footer: Clear all / Redact all. let footer = g.id == "redact"; let marks = if footer { app.active_ids().and_then(|(_, id)| app.session.get(id)).map_or(0, |d| d.redaction_marks()) } else { 0 }; - let list_h = if footer { (ui.available_height() - 52.0).max(80.0) } else { ui.available_height() }; - egui::ScrollArea::vertical().auto_shrink([false, false]).max_height(list_h).show(ui, |ui| { - clear_of_scrollbar(ui); - ui.add_space(2.0); - for s in g.sections { - widgets::section_title(ui, tl!(s.title)); - for item in s.items { - if g.id == "fill_sign" && (item.command.starts_with("sign.fill.signature") || item.command.starts_with("sign.fill.initials")) { - continue; - } - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 34.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(item.label))); - let ready = item.availability == Availability::Ready; - let press = theme::Press::track(ui, &resp); - press.wash(ui, rect, 6, false); - let body = rect.translate(press.offset()); - let fg = if ready { t.text } else { t.text_muted }; - icons::paint( - ui, - Rect::from_min_size(body.min + vec2(6.0, 8.0), vec2(18.0, 18.0)), - item.icon, - 17.0, - if ready { hue(g) } else { t.text_faint }, - ); - let (chip, fill, cfg) = match item.availability { - Availability::Ready => (tl!("Ready"), Color32::from_rgb(0xDD, 0xF3, 0xE4), Color32::from_rgb(0x1E, 0x7B, 0x43)), - Availability::Planned(m) => (m, t.pressed, t.text_muted), - Availability::Provider => ("AI", t.pressed, t.text_muted), - }; - let font = theme::semibold(9.5); - let chip_label = tl!(chip).to_string(); - let w = crate::widgets::text_width(ui, &chip_label, &font); - let r = Rect::from_center_size(body.right_center() - vec2(w / 2.0 + 10.0, 0.0), vec2(w + 10.0, 16.0)); - row_label(ui, tl!(item.label), theme::regular(13.0), fg, body.left_center() + vec2(34.0, 0.0), r.left() - body.left() - 42.0); - ui.painter().rect_filled(r, CornerRadius::same(4), fill); - ui.painter().text(r.center(), Align2::CENTER_CENTER, chip_label, font, cfg); - let resp = theme::hand(resp).on_hover_text(format!("{} — {}", tl!(item.label), item.command)); - // An entry with further commands opens a menu; its caret goes before the chip. - if item.actions.is_empty() { - if resp.clicked() { - run = Some(item.command); - } - } else if let Some(cmd) = actions_menu(app, ui, &resp, item, r.left_center() - vec2(10.0, 0.0), fg) { - run = Some(cmd); - } + + let mut lines = Vec::new(); + for s in g.sections { + lines.push(Line::Heading(s.title)); + for item in s.items { + if g.id == "fill_sign" && (item.command.starts_with("sign.fill.signature") || item.command.starts_with("sign.fill.initials")) { + continue; } + lines.push(Line::Item(item)); } - if g.id == "fill_sign" { - widgets::section_title(ui, tl!("Sign yourself")); - if let Some(cmd) = crate::fill_sign::signature_entries(ui, app, t) { - run = Some(cmd); - } - // Where the signing happens, not only in Preferences, and once: not also in the Sign - // menu over the page, where it was easy to miss (#2149). - ui.add(widgets::checkbox(&mut app.flatten_fill_sign_on_save, tl!("Lock into the page when saving"))); - } - }); - if footer { - ui.add_space(8.0); - ui.horizontal(|ui| { - if marks > 0 { - ui.label( - egui::RichText::new(if marks == 1 { - crate::i18n::fmt(tl!("1 mark"), &[]) - } else { - crate::i18n::fmt(tl!("{n} marks"), &[("n", &marks.to_string())]) - }) - .color(t.text_muted), - ); - } - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.add_enabled_ui(marks > 0, |ui| widgets::pill_button(ui, tl!("Redact all"), true)).inner.clicked() { - run = Some("redact.apply"); - } - if ui.add_enabled_ui(marks > 0, |ui| widgets::pill_button(ui, tl!("Clear all"), false)).inner.clicked() { - run = Some("redact.clear"); - } - }); + } + let out = List::::new(tl!(g.label).to_owned()) + .select(SelectMode::Single) + .activate(ActivateOn::Click) + .selection(Bind::given(Selection::default())) + .show_items(ui, &Rows(lines.len()), &mut |at, _| match lines.get(*at) { + Some(Line::Heading(title)) => ListRow::new(tl!(title).to_owned()).heading().ink(RowInk::Dimmed), + Some(Line::Item(item)) => item_row(g, item), + None => ListRow::spacer(), }); + let opener = out.response.clone(); + let mut menu = None; + for event in out.events { + if let CollectionEvent::Activate(at) = event + && let Some(Line::Item(item)) = lines.get(at) + { + if item.actions.is_empty() { + run = Some(item.command); + } else { + menu = Some(*item); + } + } + } + // An entry with further commands opens a menu from its row. + // PLAN: assumed actions_menu(app, ui, opener: &Response, item: &'static ToolItem) -> Option<&'static str> (pdf-edit-w6); it keeps its own open state. + if let Some(item) = menu + && let Some(cmd) = actions_menu(app, ui, &opener, item) + { + run = Some(cmd); + } + if g.id == "fill_sign" { + caption_row(ui, tl!("Sign yourself"), true); + if let Some(cmd) = crate::fill_sign::signature_entries(ui, app) { + run = Some(cmd); + } + // Where the signing happens, not only in Preferences, and once: not also in the Sign + // menu over the page, where it was easy to miss (#2149). + Checkbox::new(Bind::bound(&mut app.flatten_fill_sign_on_save)).label(tl!("Lock into the page when saving").to_owned()).show(ui); + } + if footer { + if marks > 0 { + caption_row( + ui, + &if marks == 1 { + crate::i18n::fmt(tl!("1 mark"), &[]) + } else { + crate::i18n::fmt(tl!("{n} marks"), &[("n", &marks.to_string())]) + }, + false, + ); + } + if Button::new(tl!("Clear all").to_owned()).enabled(marks > 0).show(ui).clicked() { + run = Some("redact.clear"); + } + if Button::new(tl!("Redact all").to_owned()).enabled(marks > 0).show(ui).clicked() { + run = Some("redact.apply"); + } } if let Some(cmd) = run { app.run_command(cmd);