From 003ffd4dff45e798e8e6f4a979c9e6da5d01db94 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:25 -0500 Subject: [PATCH] pdf-chrome-w18: net change of 3 commits - pdf-chrome-w18: written from its sheet - pdf-chrome-w18: repair 1 - pdf-chrome-w18: review fixes (review-1) --- crates/ui-egui/src/hotbar.rs | 1409 +++++++++------------------------- 1 file changed, 352 insertions(+), 1057 deletions(-) diff --git a/crates/ui-egui/src/hotbar.rs b/crates/ui-egui/src/hotbar.rs index e0730de201..fb667cadb7 100644 --- a/crates/ui-egui/src/hotbar.rs +++ b/crates/ui-egui/src/hotbar.rs @@ -1,120 +1,57 @@ -//! A movable, persistent set of shortcuts to the shared command registry and core document tools. -use egui::{Color32, CornerRadius, Rect, Sense, Stroke, vec2}; -use pdfcraft_engine::Edit; +//! The toolbar: a tool rail in the dock, with a searchable drawer that edits which commands sit on it. +use craft::behavior::DockSide; +use craft::keymap::CommandRef; +use craft::theme::Srgba; +use craft::ui::choice::Swatch; +use craft::ui::contract::{Bind, Entry, Show}; +use craft::ui::docking::PanelSpec; +use craft::ui::pickers::Select; +use craft::ui::rails::{ + DrawerGroup, DrawerKind, LastUsed, RailTool, SlotId, ToolRail, ToolSlot, ToolbarDrawer, apply_toolbar_edit, +}; +use craft::ui::text::NumberField; +use pdfcraft_engine::{Edit, Rgb}; use pdfcraft_engine::commands::{COMMANDS, command}; use serde::{Deserialize, Serialize}; -use crate::{PdfCraftApp, QuickTool, comments, icons, theme, theme::Tokens}; +use crate::fill_sign::{FILL_TOOLS, FillTool}; +use crate::{Mode, PdfCraftApp, QuickTool, comments}; -/// Persistent state and UI state for the customizable document hotbar. -#[derive(Clone, Debug, Serialize, Deserialize)] +/// The tool ids of the tools that are not registry commands; the rail's current tool and its slots are keyed by +/// command id. +const TOOL_SELECT: &str = "view.select_tool"; +const TOOL_HAND: &str = "view.hand_tool"; +const TOOL_CROP: &str = "page.crop"; +const TOOL_EDIT_TEXT: &str = "edit.edit_text"; + +const SLOT_POINTER: SlotId = 0; +const SLOT_CROP: SlotId = 1; +/// The first comment group's slot; group `g` is `SLOT_COMMENT + g`. +const SLOT_COMMENT: SlotId = 10; +const SLOT_EDIT_TEXT: SlotId = 20; +const SLOT_FILL: SlotId = 30; +/// The first user slot; the user's `i`-th command is `SLOT_USER + i`. +const SLOT_USER: SlotId = 100; + +/// Persistent state and UI state for the toolbar. +#[derive(Clone, Debug, Default, Serialize, Deserialize)] #[serde(default)] pub(crate) struct Hotbar { + /// The commands the user put on the toolbar, in order. pub tools: Vec, - /// Position as a fraction of the available travel, so resizing keeps the bar visible. - pub position: [f32; 2], - pub vertical: bool, - pub button_size: f32, - pub dock: Option, - pub full_side: bool, - #[serde(default)] - pub placed: bool, + /// The tool each slot showed last. #[serde(skip)] - search: String, + last_used: LastUsed, + /// Whether the drawer that edits the toolbar is open. #[serde(skip)] - picker_open: bool, - /// Where the Hotbar tools window stays while the Toolbar size slider is being adjusted. - #[serde(skip)] - picker_drag_pos: Option, - /// The Toolbar size slider is being adjusted with the keyboard (until it loses focus). - #[serde(skip)] - keyboard_sizing: bool, - /// The pass the Hotbar tools window was last drawn on. - #[serde(skip)] - picker_shown: Option, + drawer_open: bool, } impl Hotbar { - /// The Hotbar tools window is over the pages: open, and drawn on the last pass. Read mode, full - /// screen, Organize and a document that hides the toolbars don't draw the hotbar, and a window - /// they hide holds no keys. - pub(crate) fn picker_over_pages(&self, ctx: &egui::Context) -> bool { - self.picker_open && self.picker_shown.is_some_and(|pass| pass.saturating_add(1) >= ctx.cumulative_pass_nr()) - } - - /// Closes the Hotbar tools window when the hotbar is `hidden` on this pass (Read mode or full - /// screen, which a native menu's click may have turned on just now), or the last pass didn't - /// draw it (Organize, or a document that hides the toolbars). Left open, it would hold the keys of the pass that hides it, and come - /// back over the pages on the pass that shows the hotbar again, after that pass's page keys - /// had been read without it. - pub(crate) fn close_hidden_picker(&mut self, ctx: &egui::Context, hidden: bool) { - if self.picker_open && (hidden || !self.picker_over_pages(ctx)) { - self.close_picker(); - } - } - - /// Closes the Hotbar tools window. - pub(crate) fn close_picker(&mut self) { - self.picker_open = false; - self.picker_shown = None; - // Closed on a pass that doesn't draw the hotbar, `show` can't end a size adjustment: the - // next opening would start at the held position. - self.picker_drag_pos = None; - self.keyboard_sizing = false; - } -} - -impl Default for Hotbar { - /// Create a default vertical floating hotbar positioned in the document margin. - fn default() -> Self { - Self { - tools: Vec::new(), - position: [0.0, 0.0], - vertical: true, - button_size: 32.0, - dock: None, - full_side: false, - placed: false, - search: String::new(), - picker_open: false, - picker_drag_pos: None, - keyboard_sizing: false, - picker_shown: None, - } - } -} - -impl Hotbar { - /// Clamp button size and normalized position coordinates, drop unknown docked sides, - /// and deduplicate/filter tool command identifiers against the command registry. + /// Drops tool ids the command registry no longer has, and duplicates. pub fn normalize(&mut self) { - self.button_size = if self.button_size.is_finite() { self.button_size.clamp(24.0, 64.0) } else { 32.0 }; - if self.dock.as_deref().is_some_and(|side| !matches!(side, "left" | "right" | "top" | "bottom")) { - self.dock = None; - } let mut seen = std::collections::HashSet::new(); self.tools.retain(|id| command(id).is_some() && seen.insert(id.clone())); - for coordinate in &mut self.position { - *coordinate = if coordinate.is_finite() { coordinate.clamp(0.0, 1.0) } else { 0.5 }; - } - if self.dock.is_some() || self.position != [0.0, 0.0] { - self.placed = true; - } - } - - /// Adopt preferences saved before the hotbar absorbed the quick-action bar (#5890), which have - /// no `placed` key. A bar left at that release's default (floating, horizontal, top centre) - /// moves to the new default in the left margin; any other spot is one the user chose, so it - /// is kept, including the top-left corner. - pub fn adopt_legacy(&mut self) { - if self.dock.is_none() && !self.vertical && self.position == [0.5, 0.0] { - self.position = [0.0, 0.0]; - self.vertical = true; - self.full_side = false; - self.placed = false; - } else { - self.placed = true; - } } /// Parse and validate a comma-separated list of command identifiers for the hotbar. @@ -127,236 +64,171 @@ impl Hotbar { self.normalize(); Ok(()) } - - /// Dock the hotbar to `"left"`, `"right"`, `"top"`, or `"bottom"`, or undock with `"float"`. - pub fn place(&mut self, side: &str) -> Result<(), String> { - if side == "float" { - self.dock = None; - self.placed = true; - return Ok(()); - } - let (position, vertical) = match side { - "left" => ([0.0, 0.5], true), - "right" => ([1.0, 0.5], true), - "top" => ([0.5, 0.0], false), - "bottom" => ([0.5, 1.0], false), - _ => return Err("hotbar-side must be float, left, right, top or bottom".into()), - }; - self.dock = Some(side.to_owned()); - self.position = position; - self.vertical = vertical; - self.placed = true; - Ok(()) - } } -/// Render the hotbar settings gear button and open the tool picker when clicked. -fn settings_button(ui: &mut egui::Ui, cell: f32, picker_open: &mut bool) -> bool { - let settings = ui - .push_id("hotbar-settings", |ui| { - icons::labeled_button(ui, "settings", cell, false, tl!("Hotbar settings"), tl!("Hotbar settings / add tools")) - }) - .inner; - if settings.clicked() { - *picker_open = true; - true - } else { - false - } -} - -/// Determine where flyout popup menus should open from a toolbar button based on docking and layout. -fn popup_align_for(dock: Option<&str>, vertical: bool) -> egui::RectAlign { - match dock { - Some("right") => egui::RectAlign::LEFT_START, - Some("bottom") => egui::RectAlign::TOP_START, - Some("top") => egui::RectAlign::BOTTOM_START, - _ => { - if vertical { - egui::RectAlign::RIGHT_START - } else { - egui::RectAlign::BOTTOM_START - } - } - } -} - -/// Whether `spec` matches the hotbar picker search query across the translated label, canonical -/// English label, or command identifier (case-insensitively). -fn matches_search(spec: &pdfcraft_engine::commands::CommandSpec, query: &str) -> bool { - let search = query.to_lowercase(); - tl!(spec.label).to_lowercase().contains(&search) || spec.label.to_lowercase().contains(&search) || spec.id.to_lowercase().contains(&search) -} - -/// Render the configured custom tool shortcut buttons and their removal context menus. -fn tool_buttons(ui: &mut egui::Ui, app: &PdfCraftApp, tools: &[String], cell: f32, run: &mut Option<&'static str>, remove: &mut Option) { - for (index, id) in tools.iter().enumerate() { - let Some(spec) = command(id) else { continue }; - let active = crate::comments::CommentTool::from_command(id).is_some_and(|tool| app.quick_tool == crate::QuickTool::Comment(tool)); - let button = ui.add_enabled_ui(app.command_enabled(spec), |ui| icons::button(ui, spec.icon, cell, active, tl!(spec.label))).inner; - if button.clicked() { - *run = Some(spec.id); - } - button.context_menu(|ui| { - if ui.button(tl!("Remove from hotbar")).clicked() { - *remove = Some(index); - ui.close(); - } - }); - } -} - -/// Render core quick tools: Select, Hand, Comment groups, Edit text, and Fill & Sign. -fn core_tool_buttons(ui: &mut egui::Ui, app: &mut PdfCraftApp, cell: f32, popup_align: egui::RectAlign, t: &Tokens) { - if icons::button(ui, "mouse-pointer-2", cell, app.quick_tool == QuickTool::Select, tl!("Select (V)")).clicked() { - app.quick_tool = QuickTool::Select; - } - if icons::button(ui, "hand", cell, app.quick_tool == QuickTool::Hand, tl!("Hand (H)")).clicked() { - app.quick_tool = QuickTool::Hand; - } - let may_crop = command("page.crop").is_some_and(|spec| app.command_enabled(spec)); - ui.add_enabled_ui(may_crop, |ui| { - if icons::button(ui, "crop", cell, app.quick_tool == QuickTool::Crop, tl!("Crop pages")).clicked() { - app.execute("page.crop"); - } - }); - // Comment ▸, Highlight ▸, Draw ▸ (Acrobat's comment toolbar groups). Clicking a - // group selects its last-used tool; clicking it again opens the flyout. - for g in 0..comments::GROUPS.len() { - let current = app.comment_prefs.group_tool[g]; - let active = matches!(app.quick_tool, QuickTool::Comment(t) if t.group() == g); - let resp = icons::button(ui, current.icon(), cell, active, tl!(current.label())); - if comments::GROUPS[g].len() == 1 { - if resp.clicked() { - app.execute(current.command()); - } - continue; - } - // A small corner triangle marks the flyout. - let r = resp.rect; - let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)]; - ui.painter().add(egui::Shape::convex_polygon(tri.to_vec(), if active { t.accent } else { t.text_faint }, Stroke::NONE)); - let open = (resp.clicked() && active) || resp.secondary_clicked(); - if resp.clicked() && !active { - app.execute(current.command()); - } - egui::Popup::menu(&resp).open_memory(open.then_some(egui::SetOpenCommand::Toggle)).align(popup_align).gap(6.0).show(|ui| { - for tool in comments::GROUPS[g] { - let on = app.quick_tool == QuickTool::Comment(*tool); - let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click()); - let press = theme::Press::track(ui, &click); - press.wash(ui, row, 4, on); - let body = row.translate(press.offset()); - icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text); - let reserve = if on { 28.0 } else { 8.0 }; - crate::widgets::paint_left( - ui, - body.left_center() + vec2(34.0, 0.0), - tl!(tool.label()), - theme::regular(13.0), - t.text, - (row.width() - 34.0 - reserve).max(0.0), - ); - if on { - icons::paint(ui, Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)), "check", 14.0, t.accent); - } - let click = theme::hand(click); - let info = tl!(tool.label()).to_string(); - click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone())); - if click.clicked() { - app.execute(tool.command()); - ui.close(); - } - } - }); - } - // Edit text & images, while the Edit workspace is open (Acrobat's Edit toolbar) - // or the tool is in use. - if app.mode == crate::Mode::Edit || app.quick_tool == QuickTool::EditText { - let on = app.quick_tool == QuickTool::EditText; - if icons::button(ui, "text-cursor-input", cell, on, tl!("Edit text & images")).clicked() { - if on { - app.put_down_edit_text(); - } else { - app.quick_tool = QuickTool::EditText; - } - } - } - // Fill & Sign ▸ (text, marks, date, signature). - let current_fill = match app.quick_tool { - QuickTool::Fill(f) => Some(f), +/// Reads a `hotbar` object saved before the toolbar became a dock panel: its tool list (filtered as `normalize` +/// does) and the side it was docked to. Position, size, full-side and placement are dropped. The old physical +/// `"left"` maps to `Start`, as `DockSide`'s own aliases do, so a right-to-left window docks it on the right. +pub(crate) fn migrate_legacy(value: &serde_json::Value) -> (Vec, Option) { + let mut bar = Hotbar { + tools: value + .get("tools") + .and_then(|tools| tools.as_array()) + .map(|tools| tools.iter().filter_map(|id| id.as_str().map(str::to_owned)).collect()) + .unwrap_or_default(), + ..Hotbar::default() + }; + bar.normalize(); + let side = match value.get("dock").and_then(|dock| dock.as_str()) { + Some("left") => Some(DockSide::Start), + Some("right") => Some(DockSide::End), + Some("top") => Some(DockSide::Top), + Some("bottom") => Some(DockSide::Bottom), _ => None, }; - let shown = current_fill.unwrap_or(app.fill_tool); - let tip = match shown { - crate::fill_sign::FillTool::Signature | crate::fill_sign::FillTool::Initials if current_fill.is_none() => { - let initials = shown == crate::fill_sign::FillTool::Initials; - let saved = if initials { app.initials.is_some() } else { app.signature.is_some() }; - crate::i18n::fmt( - tl!(if saved { "Place saved {what}" } else { "Add {what}" }), - &[("what", tl!(if initials { "initials" } else { "signature" }))], - ) - } - _ => tl!(shown.label()).to_string(), - }; - let tip = format!("{}: {tip}", tl!("Fill & Sign")); - let resp = icons::button(ui, shown.icon(), cell, current_fill.is_some(), &tip); - let r = resp.rect; - let tri = [r.right_bottom() + vec2(-4.0, -4.0), r.right_bottom() + vec2(-9.0, -4.0), r.right_bottom() + vec2(-4.0, -9.0)]; - ui.painter().add(egui::Shape::convex_polygon(tri.to_vec(), if current_fill.is_some() { t.accent } else { t.text_faint }, Stroke::NONE)); - if resp.clicked() && current_fill.is_none() { - app.execute(shown.command()); - } - let open = (resp.clicked() && current_fill.is_some()) || resp.secondary_clicked(); - egui::Popup::menu(&resp).open_memory(open.then_some(egui::SetOpenCommand::Toggle)).align(popup_align).gap(6.0).show(|ui| { - for tool in crate::fill_sign::FILL_TOOLS { - if matches!(tool, crate::fill_sign::FillTool::Signature | crate::fill_sign::FillTool::Initials) { - continue; - } - let on = current_fill == Some(tool); - let (row, click) = ui.allocate_exact_size(vec2(180.0, 28.0), Sense::click()); - let press = theme::Press::track(ui, &click); - press.wash(ui, row, 4, on); - let body = row.translate(press.offset()); - icons::paint(ui, Rect::from_min_size(body.min + vec2(8.0, 6.0), vec2(16.0, 16.0)), tool.icon(), 16.0, t.text); - let reserve = if on { 28.0 } else { 8.0 }; - crate::widgets::paint_left( - ui, - body.left_center() + vec2(34.0, 0.0), - tl!(tool.label()), - theme::regular(13.0), - t.text, - (row.width() - 34.0 - reserve).max(0.0), - ); - if on { - icons::paint(ui, Rect::from_min_size(body.right_top() + vec2(-24.0, 7.0), vec2(14.0, 14.0)), "check", 14.0, t.accent); - } - let click = theme::hand(click); - let info = tl!(tool.label()).to_string(); - click.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, info.clone())); - if click.clicked() { - app.execute(tool.command()); - ui.close(); - } - } - ui.separator(); - if let Some(command) = crate::fill_sign::signature_entries(ui, app, t) { - app.execute(command); - ui.close(); - } - }); + (bar.tools, side) } -fn controls_divider(ui: &mut egui::Ui, t: &Tokens, vertical: bool) { - let (r, _) = if vertical { - ui.allocate_exact_size(vec2(crate::canvas::bars::QUICK_BAR_WIDTH, 9.0), Sense::hover()) - } else { - ui.allocate_exact_size(vec2(9.0, crate::canvas::bars::QUICK_BAR_WIDTH), Sense::hover()) +fn rail_tool(id: &str) -> RailTool { + RailTool::new(id.to_owned(), CommandRef::new(id)) +} + +/// The id of the rail tool the app's current tool stands for; empty when the rail has none for it. +fn current_tool(app: &PdfCraftApp) -> String { + match app.quick_tool { + QuickTool::Select => TOOL_SELECT.to_owned(), + QuickTool::Hand => TOOL_HAND.to_owned(), + QuickTool::Crop => TOOL_CROP.to_owned(), + QuickTool::EditText => TOOL_EDIT_TEXT.to_owned(), + QuickTool::Comment(tool) => tool.command().to_owned(), + QuickTool::Fill(tool) => tool.command().to_owned(), + _ => String::new(), + } +} + +/// The built-in slots, then one slot for each of `user` commands. +fn slots_with(app: &PdfCraftApp, user: &[String]) -> Vec> { + let mut slots = vec![ + ToolSlot::new(SLOT_POINTER, vec![rail_tool(TOOL_SELECT), rail_tool(TOOL_HAND)]), + ToolSlot::ending_group(SLOT_CROP, vec![rail_tool(TOOL_CROP)]), + ]; + let groups = comments::GROUPS.len(); + for (g, tools) in comments::GROUPS.iter().enumerate() { + let tools = tools.iter().map(|tool| rail_tool(tool.command())).collect(); + let id = SLOT_COMMENT + g as SlotId; + slots.push(if g + 1 == groups { ToolSlot::ending_group(id, tools) } else { ToolSlot::new(id, tools) }); + } + if app.mode == Mode::Edit || app.quick_tool == QuickTool::EditText { + slots.push(ToolSlot::new(SLOT_EDIT_TEXT, vec![rail_tool(TOOL_EDIT_TEXT)])); + } + slots.push(ToolSlot::ending_group(SLOT_FILL, FILL_TOOLS.iter().map(|tool| rail_tool(tool.command())).collect())); + for (i, id) in user.iter().enumerate() { + slots.push(ToolSlot::new(SLOT_USER + i as SlotId, vec![rail_tool(id)])); + } + slots +} + +/// The toolbar's slots: the built-in tools and the user's commands. +pub(crate) fn slots(app: &PdfCraftApp) -> Vec> { + slots_with(app, &app.hotbar.tools) +} + +/// The registry's commands grouped by family (the id up to its first dot) for the drawer. +fn drawer_groups() -> Vec> { + let mut families: Vec<(&str, Vec>)> = Vec::new(); + for spec in COMMANDS { + let family = spec.id.split('.').next().unwrap_or(spec.id); + match families.iter_mut().find(|(name, _)| *name == family) { + Some((_, tools)) => tools.push(rail_tool(spec.id)), + None => families.push((family, vec![rail_tool(spec.id)])), + } + } + families + .into_iter() + .map(|(family, tools)| { + let mut name = family.to_owned(); + if let Some(first) = name.get_mut(..1) { + first.make_ascii_uppercase(); + } + DrawerGroup::new(name, tools) + }) + .collect() +} + +/// The toolbar's dock panel: its column is whole tool columns wide, and its tab shows the marker of the command that +/// toggles panels. +pub(crate) fn panel_spec(app: &PdfCraftApp, ctx: &egui::Context) -> PanelSpec { + // PLAN: assumed the toolbar's `PanelId` serialises as "toolbar" in `view.panel {panel}` (pdf-chrome-w13). + PanelSpec::new(tl!("Toolbar").to_string()) + .grid(ToolRail::::dock_grid(ctx, slots(app).len())) + .command(CommandRef::with_params("view.panel", serde_json::json!({ "panel": "toolbar" }))) +} + +// Every conversion between the engine's `f64` colour and the framework's goes through these two. +fn to_srgba(color: Rgb) -> Srgba { + Srgba::rgb(color[0] as f32, color[1] as f32, color[2] as f32) +} + +fn from_srgba(color: Srgba) -> Rgb { + let [r, g, b] = color.to_rgb_array(); + [f64::from(r), f64::from(g), f64::from(b)] +} + +/// Opens the colour picker in the main window, the window the rail's footer lives in, and runs `then` with the answer. +fn open_picker(app: &mut PdfCraftApp, request: craft::ui::contract::ColorRequest, then: impl FnOnce(&mut PdfCraftApp, Srgba) + 'static) { + // PLAN: assumed `PdfCraftApp::main_dialog_host(&self) -> DialogHost` and + // `open_colour_picker(&mut self, DialogHost, ColorRequest, impl FnOnce(&mut PdfCraftApp, Srgba) + 'static)` (pdf-comments-w10, q180). + let host = app.main_dialog_host(); + app.open_colour_picker(host, request, then); +} + +/// Shows the toolbar's rail in the width `ui` has left, with the active tool's controls under it, and applies what +/// the user did: a drawer pick runs its command, a drawer edit changes the tool list. +pub(crate) fn show_rail(app: &mut PdfCraftApp, ui: &mut egui::Ui) { + app.hotbar.normalize(); + let toolbar = slots(app); + let current = current_tool(app); + let last_used = app.hotbar.last_used.clone(); + let editing = app.hotbar.drawer_open; + let mut rail = ToolRail::new(tl!("Toolbar").to_string(), &toolbar, ¤t, &last_used).edit_toolbar(tl!("Edit toolbar").to_string()); + if editing { + rail = rail.editing(); + } + let output = rail.show_rail(ui, |ui, _footer| footer_controls(ui, app)); + if let Some(next) = output.last_used { + app.hotbar.last_used = next; + } + if output.edit_toolbar.as_ref().is_some_and(|opener| opener.clicked()) { + app.hotbar.drawer_open = true; + } + if !app.hotbar.drawer_open { + return; + } + let Some(opener) = output.edit_toolbar.as_ref() else { + app.hotbar.drawer_open = false; + return; }; - if vertical { - ui.painter().hline(r.x_range().shrink(6.0), r.center().y, Stroke::new(1.0, t.divider)); - } else { - ui.painter().vline(r.center().x, r.y_range().shrink(6.0), Stroke::new(1.0, t.divider)); + let groups = drawer_groups(); + let drawer = ToolbarDrawer::new(output.response.rect, &groups, &toolbar, output.dropped) + .kind(DrawerKind::Searchable) + .opened_by(opener) + .show(ui); + let defaults = slots_with(app, &[]); + let mut edited: Option>> = None; + for edit in &drawer.edits { + let base = edited.as_deref().unwrap_or(&toolbar); + edited = Some(apply_toolbar_edit(base, edit, &defaults)); + } + if let Some(edited) = edited { + // Built-in slots are not the user's list; only commands the registry has are kept. + app.hotbar.tools = edited.iter().flat_map(|slot| slot.tools.iter()).map(|tool| tool.id.clone()).collect(); + app.hotbar.normalize(); + } + if let Some(id) = drawer.select { + app.execute(&id); + } + if drawer.closed { + app.hotbar.drawer_open = false; } } @@ -371,14 +243,59 @@ fn selected_fill_text(app: &PdfCraftApp) -> Option<(usize, usize)> { .then_some((page, annotation)) } -/// Fill & Sign's Border controls for typed text: its width, colour and shape, for the selected -/// text (`picked`), or for new text when none is selected. The label shows in a vertical bar, as the -/// font size's does. -fn fill_text_border_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, picked: Option<(usize, usize)>, vertical: bool) { - // The selected text's own border (Comment Properties may have changed it - // since): the controls below show it and change only it. Without one they - // set what new text gets until PdfCraft quits; Make Current Properties - // Default on typed text keeps it. +/// The controls of the active tool under the rail's slots. +fn footer_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp) { + match app.quick_tool { + QuickTool::Fill(FillTool::Text | FillTool::Date) => fill_text_controls(ui, app), + QuickTool::Comment(tool) => comment_controls(ui, app, tool), + _ => {} + } +} + +/// Fill & Sign's text controls: its colour, font size and border, for the selected text, or for new text when none +/// is selected. +fn fill_text_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp) { + let picked = selected_fill_text(app); + let well = Swatch::new(tl!("Text colour").to_string(), to_srgba(app.fill_text_color)).picker("hotbar.fill-text-colour").well().show(ui); + if let Some(request) = well.pick_color { + open_picker(app, request, move |app: &mut PdfCraftApp, picked_colour: Srgba| { + let color = from_srgba(picked_colour); + app.fill_text_color = color; + if let Some((page, index)) = selected_fill_text(app) { + app.apply_edit(Edit::StyleAnnotation { page, index, color: Some(color), opacity: None, width: None, endings: None }); + } + }); + } + + let (min, max) = (f64::from(crate::fill_sign::MIN_TEXT_SIZE), f64::from(crate::fill_sign::MAX_TEXT_SIZE)); + let mut size = Some(app.fill_text_size); + let field = NumberField::new(tl!("Font size").to_string(), Bind::bound(&mut size)).range(min..=max).popup_slider(min..=max).unit("pt").show(ui); + // #1274: the size also applies to the Fill & Sign text that is selected, once per committed change (a typed + // value, or the end of a drag), so a drag adds one undo step and not one per frame. + let committed = field.edit.events.committed().is_some(); + if let Some(value) = size { + app.fill_text_size = value; + } + let size = app.fill_text_size; + if committed + && let Some((page, index)) = picked + && app + .active_ids() + .and_then(|(_, id)| app.session.get(id)?.comment_props(page, index)?.font_size) + .is_none_or(|stored| format!("{stored:.3}") != format!("{size:.3}")) + { + app.apply_edit(Edit::FontSizeAnnotation { page, index, size }); + } + + fill_text_border_controls(ui, app, picked); +} + +/// Fill & Sign's Border controls for typed text: its width, colour and shape, for the selected text (`picked`), or +/// for new text when none is selected. +fn fill_text_border_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, picked: Option<(usize, usize)>) { + // The selected text's own border (Comment Properties may have changed it since): the controls below show it and + // change only it. Without one they set what new text gets until PdfCraft quits; Make Current Properties Default + // on typed text keeps it. let selected = picked.and_then(|(page, annotation)| { let p = app.active_ids().and_then(|(_, id)| app.session.get(id))?.comment_props(page, annotation)?; let own = crate::fill_sign::TextBorder { width: p.width.unwrap_or(0.0), color: p.border_color, shape: p.border_shape.unwrap_or_default() }; @@ -389,61 +306,49 @@ fn fill_text_border_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, picked: O |(_, _, own)| own, ); let mut border = was; - // A border around the text, in its colour; the text keeps its place. let border_label = |w: f64| if w > 0.0 { format!("{w} pt") } else { tl!("None").to_string() }; - let label = vertical.then(|| ui.label(tl!("Border:"))); - let combo = craft_ui::ComboBox::from_id_salt("fill-text-border") - .selected_text(border_label(was.width)) - .width(72.0) - .show_ui(ui, |ui| { - for w in crate::fill_sign::TEXT_BORDERS { - ui.selectable_value(&mut border.width, w, border_label(w)); - } - }) - .response; - match label { - Some(label) => { - combo.labelled_by(label.id); - } - None => { - combo.on_hover_text(tl!("Border:")); - } + let widths: Vec> = crate::fill_sign::TEXT_BORDERS.iter().enumerate().map(|(i, w)| Entry::new(i, border_label(*w))).collect(); + let mut width_at = crate::fill_sign::TEXT_BORDERS.iter().position(|w| *w == was.width).unwrap_or(0); + Select::new(tl!("Border:").to_string(), Bind::bound(&mut width_at), &widths).show(ui); + if let Some(width) = crate::fill_sign::TEXT_BORDERS.get(width_at) { + border.width = *width; } // The border's own colour (the text's unless picked). - if was.width > 0.0 - && let Some(color) = comments::border_colour_button(ui, was.color, [0.0; 3]) - { - border.color = color; - } - // Its shape: an oval or a circle goes around the text, which keeps its place. if was.width > 0.0 { - craft_ui::ComboBox::from_id_salt("fill-text-border-shape") - .selected_text(tl!(was.shape.name())) - .width(96.0) - .show_ui(ui, |ui| { - for shape in pdfcraft_engine::BorderShape::ALL { - ui.selectable_value(&mut border.shape, shape, tl!(shape.name())); + let well = Swatch::new(tl!("Border colour").to_string(), to_srgba(was.color.unwrap_or(app.fill_text_color))).picker("hotbar.fill-border-colour").well().show(ui); + if let Some(request) = well.pick_color { + let target = selected.map(|(page, index, _)| (page, index)); + open_picker(app, request, move |app: &mut PdfCraftApp, picked_colour: Srgba| { + let color = from_srgba(picked_colour); + match target { + Some((page, index)) => { + app.apply_edit(Edit::BorderColorAnnotation { page, index, color: Some(color) }); + } + None => app.fill_text_border_color = Some(color), } - }) - .response - .on_hover_text(tl!("Border shape")); + }); + } + // Its shape: an oval or a circle goes around the text, which keeps its place. + let shapes: Vec> = + pdfcraft_engine::BorderShape::ALL.iter().enumerate().map(|(i, shape)| Entry::new(i, tl!(shape.name()).to_string())).collect(); + let mut shape_at = pdfcraft_engine::BorderShape::ALL.iter().position(|shape| *shape == was.shape).unwrap_or(0); + Select::new(tl!("Border shape").to_string(), Bind::bound(&mut shape_at), &shapes).show(ui); + if let Some(shape) = pdfcraft_engine::BorderShape::ALL.get(shape_at) { + border.shape = *shape; + } } - // No border, no shape: an oval or a circle left without its line would - // keep its box grown around a shape that isn't drawn. + // No border, no shape: an oval or a circle left without its line would keep its box grown around a shape that + // isn't drawn. if border.width <= 0.0 { border.shape = pdfcraft_engine::BorderShape::Rectangle; } match selected { Some((page, index, _)) => { - // One undo step for what one choice changed (Border ▸ None takes a - // circle's line and its shape). + // One undo step for what one choice changed (Border ▸ None takes a circle's line and its shape). let mut edits = Vec::new(); if border.width != was.width { edits.push(Edit::StyleAnnotation { page, index, color: None, opacity: None, width: Some(border.width), endings: None }); } - if border.color != was.color { - edits.push(Edit::BorderColorAnnotation { page, index, color: border.color }); - } if border.shape != was.shape { edits.push(Edit::BorderShapeAnnotation { page, index, shape: border.shape }); } @@ -455,719 +360,109 @@ fn fill_text_border_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, picked: O } None => { app.fill_text_border = border.width; - app.fill_text_border_color = border.color; app.fill_text_border_shape = border.shape; } } } -/// Extra controls rendered below/beside the buttons when a comment or fill tool is active. -fn active_tool_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, t: &Tokens, vertical: bool) { - let current_fill = match app.quick_tool { - QuickTool::Fill(f) => Some(f), - _ => None, - }; - if matches!(current_fill, Some(crate::fill_sign::FillTool::Text | crate::fill_sign::FillTool::Date)) { - controls_divider(ui, t, vertical); - if let Some(color) = comments::quick_bar_colour(ui, app.fill_text_color) { - app.fill_text_color = color; - if let Some((page, index)) = selected_fill_text(app) { - app.apply_edit(Edit::StyleAnnotation { page, index, color: Some(color), opacity: None, width: None, endings: None }); - } +/// The controls of the active comment tool: its border colour (text boxes and callouts), and the quick bar's. +fn comment_controls(ui: &mut egui::Ui, app: &mut PdfCraftApp, tool: comments::CommentTool) { + // Text boxes and callouts: the border's own colour, for new ones and the selected one this tool made (not a + // locked one). With one selected the well shows its colours (Comment Properties may have changed them), else the + // tool's. + if tool.has_border_color() { + let style = app.comment_prefs.style(tool); + let selected = app.active_ids().and_then(|(index, id)| { + let (page, annotation) = app.views.get(index)?.comments.selected?; + let doc = app.session.get(id)?; + let made = doc.allows_annotation() + && doc.info.annotations.iter().any(|a| a.page == page && a.index == annotation && !a.locked && comments::made_by(a, tool)); + made.then(|| (page, annotation, doc.comment_props(page, annotation))) + }); + let shown = match selected.as_ref().and_then(|(.., p)| p.as_ref()) { + Some(p) => p.border_color, + None => style.border_color, } - let resp = icons::button(ui, "a-large-small", 32.0, false, tl!("Font size")); - let resized = egui::Popup::menu(&resp) - .align(egui::RectAlign::RIGHT_START) - .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) - .show(|ui| { - ui.set_min_width(180.0); - ui.label(egui::RichText::new(tl!("Font size")).font(theme::semibold(12.0))); - let size = ui.add( - egui::Slider::new(&mut app.fill_text_size, crate::fill_sign::MIN_TEXT_SIZE..=crate::fill_sign::MAX_TEXT_SIZE) - .logarithmic(true) - .suffix(" pt"), - ); - // #1274: the size also applies to the Fill & Sign text that is selected, - // once per change (a typed value, or the end of a drag), so a drag adds - // one undo step and not one per frame. - (size.changed() && !size.dragged()) || size.drag_stopped() - }) - .is_some_and(|popup| popup.inner); - let size = app.fill_text_size; - if resized - && let Some((page, index)) = selected_fill_text(app) - && app - .active_ids() - .and_then(|(_, id)| app.session.get(id)?.comment_props(page, index)?.font_size) - .is_none_or(|stored| format!("{stored:.3}") != format!("{size:.3}")) - { - app.apply_edit(Edit::FontSizeAnnotation { page, index, size }); - } - // After the text's own controls, so they keep their place in a bar that scrolls. - fill_text_border_controls(ui, app, selected_fill_text(app), vertical); - } - if let QuickTool::Comment(tool) = app.quick_tool { - controls_divider(ui, t, vertical); - // Text boxes and callouts: the border's own colour, for new ones and the selected one - // this tool made (not a locked one). With one selected the button shows its colours - // (Comment Properties may have changed them), else the tool's. - if tool.has_border_color() { - let style = app.comment_prefs.style(tool); - let selected = app.active_ids().and_then(|(index, id)| { - let (page, annotation) = app.views.get(index)?.comments.selected?; - let doc = app.session.get(id)?; - let made = doc.allows_annotation() - && doc.info.annotations.iter().any(|a| a.page == page && a.index == annotation && !a.locked && comments::made_by(a, tool)); - made.then(|| (page, annotation, doc.comment_props(page, annotation))) + .unwrap_or(style.color); + let well = Swatch::new(tl!("Border colour").to_string(), to_srgba(shown)).picker("hotbar.comment-border-colour").well().show(ui); + if let Some(request) = well.pick_color { + let target = selected.map(|(page, annotation, _)| (page, annotation)); + open_picker(app, request, move |app: &mut PdfCraftApp, picked_colour: Srgba| { + let color = from_srgba(picked_colour); + app.comment_prefs.set_border_color(tool, Some(color)); + if let Some((page, annotation)) = target { + app.apply_edit(Edit::BorderColorAnnotation { page, index: annotation, color: Some(color) }); + } }); - let (shown, text) = match selected.as_ref().and_then(|(.., p)| p.as_ref()) { - Some(p) => (p.border_color, p.color.unwrap_or(style.color)), - None => (style.border_color, style.color), - }; - if let Some(color) = comments::border_colour_button(ui, shown, text) { - app.comment_prefs.set_border_color(tool, color); - if let Some((page, annotation, _)) = selected { - app.apply_edit(Edit::BorderColorAnnotation { page, index: annotation, color }); - } - } - } - // The selected comments this tool made take the colour too (locked ones keep theirs). - if let Some(color) = comments::quick_bar_controls(ui, tool, &mut app.comment_prefs) - && let Some((_, id)) = app.active_ids() - && app.session.get(id).is_some_and(|doc| doc.allows_annotation()) - { - app.colour_selection(color, |a| comments::made_by(a, tool)); } } -} - -/// Render a modern iOS-style pill toggle switch. -fn toggle_switch(ui: &mut egui::Ui, on: &mut bool, label: &str, t: &Tokens) -> egui::Response { - let width = 34.0; - let height = 18.0; - let (rect, mut response) = ui.allocate_exact_size(vec2(width, height), Sense::click()); - if response.clicked() { - *on = !*on; - response.mark_changed(); + // The selected comments this tool made take the colour too (locked ones keep theirs). + let pick = comments::quick_bar_controls(ui, tool, &mut app.comment_prefs, &app.recent_colours); + if let Some(color) = pick.colour + && let Some((_, id)) = app.active_ids() + && app.session.get(id).is_some_and(|doc| doc.allows_annotation()) + { + app.colour_selection(color, |a| comments::made_by(a, tool)); } - response.widget_info(|| egui::WidgetInfo::selected(egui::Role::Switch, ui.is_enabled(), *on, label)); - - if ui.is_rect_visible(rect) { - let radius = height / 2.0; - let bg_color = if *on { t.accent } else { t.border }; - ui.painter().rect(rect, CornerRadius::same(radius as u8), bg_color, Stroke::NONE, egui::StrokeKind::Inside); - let circle_radius = radius - 2.5; - let circle_x = if *on { rect.max.x - radius } else { rect.min.x + radius }; - ui.painter().circle_filled(egui::pos2(circle_x, rect.center().y), circle_radius, Color32::WHITE); - } - response -} - -/// Render the dock placement choice: [ Float | Left | Right | Top | Bottom ], scrolling sideways -/// when the picker is narrower than the row. -fn segmented_dock_picker(ui: &mut egui::Ui, bar: &mut Hotbar, t: &Tokens) { - let options = [ - (None, tl!("Float")), - (Some("left"), tl!("Left")), - (Some("right"), tl!("Right")), - (Some("top"), tl!("Top")), - (Some("bottom"), tl!("Bottom")), - ]; - let mut side = options.iter().map(|(side, _)| *side).find(|side| *side == bar.dock.as_deref()).flatten(); - let changed = egui::ScrollArea::horizontal() - .id_salt("hotbar-dock") - .auto_shrink([false, true]) - .show(ui, |ui| crate::dialogs::preferences::segmented_pill_choice(ui, t, &mut side, &options)) - .inner; - if changed { - // `place` accepts every side listed above. - let _ = bar.place(side.unwrap_or("float")); - } -} - -/// The arrow keys the Toolbar size slider answers to while it has focus. -const SIZE_SLIDER_KEYS: [egui::Key; 4] = [egui::Key::ArrowLeft, egui::Key::ArrowRight, egui::Key::ArrowUp, egui::Key::ArrowDown]; - -/// Whether an arrow key was pressed this frame. Read it before the slider is added, because the -/// slider consumes the keys it acts on. -fn size_slider_key_pressed(ui: &egui::Ui) -> bool { - ui.input(|input| SIZE_SLIDER_KEYS.iter().any(|key| input.key_pressed(*key))) -} - -/// Whether the Toolbar size slider is being adjusted, which keeps its picker from moving. -/// -/// A pointer adjustment lasts while the button is held. A keyboard one starts with the first arrow -/// key press that changes the value and lasts until the slider loses focus, so the picker does not -/// jump between presses. `keyboard` carries that state from frame to frame. Focusing the slider, or -/// releasing the pointer on it, does not count as a keyboard adjustment. -fn size_slider_adjusting(slider: &egui::Response, key_pressed: bool, keyboard: &mut bool) -> bool { - let pointer = slider.is_pointer_button_down_on(); - if pointer || !slider.has_focus() { - *keyboard = false; - } else if key_pressed && slider.changed() { - *keyboard = true; - } - pointer || *keyboard -} - -/// Draw the unified floating or side-docked toolbar, combining quick actions, core tools, and custom shortcuts. -pub(crate) fn show(app: &mut PdfCraftApp, area: Rect, page_left: Option, ui: &mut egui::Ui) { - let ctx = ui.ctx().clone(); - let mut bar = std::mem::take(&mut app.hotbar); - bar.normalize(); - let t = Tokens::get(&ctx); - let id = app.panes.area_id("quick-bar"); - let full_side = bar.full_side && bar.dock.is_some(); - let bounds = if full_side { area } else { area.shrink(10.0) }; - if let Some(side) = bar.dock.clone() { - let _ = bar.place(&side); - } - let cell = bar.button_size; - let popup_align = popup_align_for(bar.dock.as_deref(), bar.vertical); - let mut size = ctx.data_mut(|data| data.get_temp::(id)).unwrap_or(vec2(crate::canvas::bars::QUICK_BAR_WIDTH, 220.0)); - if full_side { - size = if bar.vertical { vec2(cell + 12.0, bounds.height()) } else { vec2(bounds.width(), cell + 12.0) }; - } - let travel = (bounds.size() - size).max(vec2(0.0, 0.0)); - let default_x = crate::canvas::bars::quick_bar_offset(page_left.map_or(0.0, |left| left - area.left()), size.x); - let pos = if full_side { - bounds.min + vec2(travel.x * bar.position[0], travel.y * bar.position[1]) - } else if bar.dock.is_none() && !bar.placed { - area.left_top() + vec2(default_x, crate::canvas::bars::QUICK_BAR_EDGE) - } else { - bounds.min + vec2(travel.x * bar.position[0], travel.y * bar.position[1]) - }; - let mut run = None; - let was_picker_open = bar.picker_open; - let mut picker_open = bar.picker_open; - let mut settings_clicked = false; - let shown = egui::Area::new(id).order(egui::Order::Middle).fixed_pos(pos).constrain_to(bounds).show(&ctx, |ui| { - let frame = if full_side { - egui::Frame::NONE.fill(t.chrome).corner_radius(egui::CornerRadius::ZERO).inner_margin(6) - } else { - egui::Frame::new() - .fill(t.card) - .stroke(egui::Stroke::new(1.0, t.border)) - .corner_radius(CornerRadius::same(12)) - .shadow(egui::Shadow { offset: [0, 4], blur: 16, spread: 0, color: Color32::from_black_alpha(if t.dark() { 100 } else { 28 }) }) - .inner_margin(6) - }; - let frame_resp = frame.show(ui, |ui| { - if full_side { - ui.set_min_size((size - vec2(12.0, 12.0)).max(vec2(0.0, 0.0))); - } - ui.spacing_mut().item_spacing = vec2(4.0, 4.0); - if bar.vertical { - ui.set_width(cell); - } else { - ui.set_height(cell); - } - let mut remove = None; - if full_side { - if bar.vertical { - ui.with_layout(egui::Layout::bottom_up(egui::Align::Center), |ui| { - settings_clicked |= settings_button(ui, cell, &mut picker_open); - ui.add_space(4.0); - let remaining = ui.available_height().max(cell); - egui::ScrollArea::vertical().max_height(remaining).show(ui, |ui| { - ui.with_layout(egui::Layout::top_down(egui::Align::Center), |ui| { - core_tool_buttons(ui, app, cell, popup_align, &t); - active_tool_controls(ui, app, &t, true); - if !bar.tools.is_empty() { - ui.separator(); - tool_buttons(ui, app, &bar.tools, cell, &mut run, &mut remove); - } - }); - }); - }); - } else { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - settings_clicked |= settings_button(ui, cell, &mut picker_open); - ui.add_space(4.0); - let remaining = ui.available_width().max(cell); - egui::ScrollArea::horizontal().max_height(cell).max_width(remaining).show(ui, |ui| { - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - core_tool_buttons(ui, app, cell, popup_align, &t); - active_tool_controls(ui, app, &t, false); - if !bar.tools.is_empty() { - ui.separator(); - tool_buttons(ui, app, &bar.tools, cell, &mut run, &mut remove); - } - }); - }); - }); - } - } else { - let layout = - if bar.vertical { egui::Layout::top_down(egui::Align::Center) } else { egui::Layout::left_to_right(egui::Align::Center) }; - ui.with_layout(layout, |ui| { - let grip_size = if bar.vertical { vec2(cell, 18.0) } else { vec2(18.0, cell) }; - let (grip_rect, grip) = ui.allocate_exact_size(grip_size, Sense::drag()); - for x in [-3.0, 3.0] { - for y in [-6.0, 0.0, 6.0] { - let offset = if bar.vertical { vec2(y, x) } else { vec2(x, y) }; - ui.painter().circle_filled(grip_rect.center() + offset, 1.5, t.text_faint); - } - } - let drag_label = tl!("Drag hotbar"); - let grip = grip.on_hover_text(drag_label).on_hover_cursor(egui::CursorIcon::Grab); - grip.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, drag_label)); - if grip.dragged() && bar.dock.is_none() { - let delta = grip.drag_delta(); - if !bar.placed { - let cur_x = (pos.x - bounds.min.x).max(0.0); - let cur_y = (pos.y - bounds.min.y).max(0.0); - bar.position[0] = (cur_x / travel.x.max(1.0)).clamp(0.0, 1.0); - bar.position[1] = (cur_y / travel.y.max(1.0)).clamp(0.0, 1.0); - } - bar.position[0] = (bar.position[0] + delta.x / travel.x.max(1.0)).clamp(0.0, 1.0); - bar.position[1] = (bar.position[1] + delta.y / travel.y.max(1.0)).clamp(0.0, 1.0); - bar.placed = true; - } - if bar.vertical { - let fixed_overhead = grip_size.y + cell + 24.0; - let max_tools_length = (bounds.height() - fixed_overhead).max(cell); - egui::ScrollArea::vertical().max_height(max_tools_length).show(ui, |ui| { - ui.with_layout(layout, |ui| { - core_tool_buttons(ui, app, cell, popup_align, &t); - active_tool_controls(ui, app, &t, true); - if !bar.tools.is_empty() { - ui.separator(); - tool_buttons(ui, app, &bar.tools, cell, &mut run, &mut remove); - } - }); - }); - settings_clicked |= settings_button(ui, cell, &mut picker_open); - } else { - core_tool_buttons(ui, app, cell, popup_align, &t); - active_tool_controls(ui, app, &t, false); - if !bar.tools.is_empty() { - ui.separator(); - let scroll_max = (bounds.width() - cell - 50.0).max(cell); - egui::ScrollArea::horizontal().max_height(cell).max_width(scroll_max).show(ui, |ui| { - ui.with_layout(layout, |ui| { - tool_buttons(ui, app, &bar.tools, cell, &mut run, &mut remove); - }); - }); - } - settings_clicked |= settings_button(ui, cell, &mut picker_open); - } - }); - } - if let Some(index) = remove { - bar.tools.remove(index); + if let Some(request) = pick.request { + open_picker(app, request, move |app: &mut PdfCraftApp, picked_colour: Srgba| { + let color = from_srgba(picked_colour); + if app.active_ids().and_then(|(_, id)| app.session.get(id)).is_some_and(|doc| doc.allows_annotation()) { + app.colour_selection(color, |a| comments::made_by(a, tool)); } }); - if full_side { - let r = frame_resp.response.rect; - let divider = egui::Stroke::new(1.0, t.divider); - match bar.dock.as_deref() { - Some("left") => { - ui.painter().vline(r.right() - 0.5, r.top()..=r.bottom(), divider); - } - Some("right") => { - ui.painter().vline(r.left() + 0.5, r.top()..=r.bottom(), divider); - } - Some("top") => { - ui.painter().hline(r.left()..=r.right(), r.bottom() - 0.5, divider); - } - Some("bottom") => { - ui.painter().hline(r.left()..=r.right(), r.top() + 0.5, divider); - } - _ => {} - } - } - }); - let picker_id = egui::Id::unique("hotbar-picker"); - // A remembered collapsed state can survive disabling the collapse affordance. - let mut expanded = egui::collapsing_header::CollapsingState::load_with_default_open(&ctx, picker_id.with("collapsing"), true); - expanded.set_open(true); - expanded.store(&ctx); - let screen = ctx.content_rect().shrink(12.0); - let margin_x = 14.0; - let card_margin_total = margin_x * 2.0; - let card_width = 280.0f32.min((screen.width() - card_margin_total).max(180.0)); - let outer_width = card_width + card_margin_total; - let bar_rect = shown.response.rect; - let picker_x = - if bar_rect.right() + outer_width + 10.0 < screen.right() { bar_rect.right() + 14.0 } else { bar_rect.left() - outer_width - 14.0 }; - let picker_y = if bar.dock.as_deref() == Some("top") { - (bar_rect.bottom() + 10.0).clamp(screen.top(), (screen.bottom() - 480.0).max(screen.top())) - } else if bar.dock.as_deref() == Some("bottom") { - (bar_rect.top() - 500.0).clamp(screen.top(), (screen.bottom() - 480.0).max(screen.top())) - } else { - bar_rect.top().clamp(screen.top(), (screen.bottom() - 480.0).max(screen.top())) - }; - // Resizing the bar can move or flip its picker; hold the picker in place until the pointer is - // released, or, for the keyboard, until the slider loses focus. - let picker_pos = - bar.picker_drag_pos.unwrap_or_else(|| egui::pos2(picker_x.clamp(screen.left(), (screen.right() - outer_width).max(screen.left())), picker_y)); - let mut sizing = false; - let mut close_dialog = false; - let picker_resp = egui::Window::new(tl!("Hotbar tools")) - .id(picker_id) - .order(egui::Order::Foreground) - .open(&mut picker_open) - .collapsible(false) - .resizable(false) - .title_bar(false) - .fixed_pos(picker_pos) - .frame( - egui::Frame::NONE - .fill(t.card) - .stroke(Stroke::new(1.0, t.border)) - .corner_radius(CornerRadius::same(10)) - .shadow(egui::Shadow { offset: [0, 6], blur: 20, spread: 0, color: Color32::from_black_alpha(if t.dark() { 120 } else { 35 }) }) - .inner_margin(egui::Margin::symmetric(14, 12)), - ) - .show(&ctx, |ui| { - ui.set_width(card_width); - - // Title bar: "Hotbar Tools" on the left, "X" close button on the right - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Hotbar tools")).size(14.0).strong().color(t.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if icons::button(ui, "x", 16.0, false, tl!("Close menu")).clicked() { - close_dialog = true; - } - }); - }); - - ui.add_space(10.0); - - // Section 1: Layout & Sizing - ui.label(egui::RichText::new(tl!("Layout & Sizing")).size(13.0).strong().color(t.text)); - ui.add_space(6.0); - - // Toolbar size slider row - ui.horizontal(|ui| { - ui.label(egui::RichText::new(tl!("Toolbar size")).size(12.5).color(t.text)); - let slider_width = (ui.available_width() - 55.0).clamp(50.0, 140.0); - ui.spacing_mut().slider_width = slider_width; - let key_pressed = size_slider_key_pressed(ui); - let slider = ui.add(egui::Slider::new(&mut bar.button_size, 24.0..=64.0).show_value(false)); - sizing = size_slider_adjusting(&slider, key_pressed, &mut bar.keyboard_sizing); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(egui::RichText::new(format!("{:.0} px", bar.button_size)).size(12.0).color(t.text_muted)); - }); - }); - - ui.add_space(8.0); - - // Vertical layout toggle switch row - ui.horizontal(|ui| { - ui.add_enabled_ui(bar.dock.is_none(), |ui| { - let label = tl!("Vertical layout"); - toggle_switch(ui, &mut bar.vertical, label, &t); - ui.add_space(8.0); - ui.label(egui::RichText::new(label).size(12.5).color(t.text)); - }); - }); - - ui.add_space(10.0); - - // Stick to a side section with segmented control - ui.label(egui::RichText::new(tl!("Stick to a side:")).size(12.5).color(t.text)); - ui.add_space(6.0); - segmented_dock_picker(ui, &mut bar, &t); - - ui.add_space(8.0); - - // Full-side strip checkbox - let strip_hint = tl!("Extend the docked toolbar along the entire side. Choose a side above to enable."); - ui.add_enabled(bar.dock.is_some(), crate::widgets::checkbox(&mut bar.full_side, tl!("Full-side strip"))) - .on_hover_text(strip_hint) - .on_disabled_hover_text(strip_hint); - - ui.add_space(12.0); - ui.separator(); - ui.add_space(10.0); - - // Section 2: Add Tools to Hotbar - ui.label(egui::RichText::new(tl!("Add Tools to Hotbar")).size(13.0).strong().color(t.text)); - ui.add_space(8.0); - - // Search bar pill - let search_frame = egui::Frame::NONE - .fill(t.field) - .stroke(Stroke::new(1.0, t.border)) - .corner_radius(CornerRadius::same(8)) - .inner_margin(egui::Margin::symmetric(10, 6)); - search_frame.show(ui, |ui| { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 8.0; - ui.add(icons::image("search", 14.0, t.text_faint)); - ui.add( - egui::TextEdit::singleline(&mut bar.search) - .hint_text(tl!("Search all tools…")) - .frame(egui::Frame::NONE) - .desired_width(ui.available_width()), - ); - }); - }); - - ui.add_space(8.0); - - // Scrollable tools list with checkboxes - let max_list_height = (screen.height() - 340.0).clamp(120.0, 220.0); - egui::ScrollArea::vertical().max_height(max_list_height).auto_shrink([false, false]).show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 5.0; - for spec in COMMANDS { - if !matches_search(spec, &bar.search) { - continue; - } - let mut selected = bar.tools.iter().any(|id| id == spec.id); - if ui.add(crate::widgets::checkbox(&mut selected, tl!(spec.label))).changed() { - if selected { - bar.tools.push(spec.id.to_owned()); - } else { - bar.tools.retain(|id| id != spec.id); - } - } - } - }); - }); - let clicked_outside = was_picker_open - && !settings_clicked - && picker_resp.as_ref().is_some_and(|wr| { - wr.response.clicked_elsewhere() - || ctx.input(|i| i.pointer.any_click() && !i.pointer.interact_pos().is_some_and(|p| wr.response.rect.contains(p))) - }); - if clicked_outside || ctx.input(|i| i.key_pressed(egui::Key::Escape)) { - close_dialog = true; - } - if close_dialog { - picker_open = false; - } - if !picker_open { - bar.keyboard_sizing = false; - } - bar.picker_drag_pos = (picker_open && sizing).then_some(picker_pos); - ctx.data_mut(|data| { - data.insert_temp(id, shown.response.rect.size()); - data.insert_temp(egui::Id::unique("custom-hotbar"), shown.response.rect.size()); - }); - bar.picker_open = picker_open; - bar.picker_shown = picker_open.then(|| ctx.cumulative_pass_nr()); - app.hotbar = bar; - if let Some(id) = run { - app.execute(id); } } #[cfg(test)] mod tests { use super::*; - use egui_kittest::{Harness, kittest::Queryable}; - - // Build a harness that draws the hotbar docked to `$side`, with its tools picker open. - macro_rules! hotbar_harness { - ($side:expr, $vertical:expr, $full_side:expr) => {{ - let mut app = PdfCraftApp::new(); - app.hotbar.place($side).unwrap(); - app.hotbar.vertical = $vertical; - app.hotbar.full_side = $full_side; - app.hotbar.position = [0.5, 0.5]; - app.hotbar.picker_open = true; - let mut fonts = false; - let mut harness = Harness::builder().with_size(vec2(1000.0, 900.0)).with_accessibility_check(false).build_ui_state( - move |ui, app: &mut PdfCraftApp| { - if !fonts { - ui.ctx().set_fonts(theme::font_definitions()); - fonts = true; - } - show(app, ui.max_rect(), None, ui); - }, - app, - ); - harness.run_steps(5); - harness - }}; - } - - // Drag the size slider from `$from` to `$to` and release, checking on every step that the picker - // (found through its slider) has not left `$pinned`. - macro_rules! drag_slider_pinned { - ($h:expr, $pinned:expr, $from:expr, $to:expr, $what:expr) => {{ - let (from, to): (egui::Pos2, egui::Pos2) = ($from, $to); - $h.hover_at(from); - $h.run_steps(1); - $h.drag_at(from); - $h.run_steps(1); - for step in 1..=8 { - $h.hover_at(from + (to - from) * (step as f32 / 8.0)); - $h.run_steps(2); - assert_eq!($h.get_by_role(egui::accesskit::Role::Slider).rect(), $pinned, "{}: picker moved during drag", $what); - } - $h.drop_at(to); - $h.run_steps(3); - }}; - } - - /// Dragging the Toolbar size slider with the pointer keeps the picker where it is, in both - /// directions and in every layout, and the picker takes its recalculated place after release. - #[test] - fn picker_stays_put_while_resizing_hotbar() { - for (side, vertical, full_side) in [ - ("top", false, false), - ("bottom", false, false), - ("float", false, false), - ("top", false, true), - ("bottom", false, true), - ("left", true, false), - ("right", true, false), - ("float", true, false), - ("left", true, true), - ("right", true, true), - ] { - let what = format!("{side}, vertical={vertical}, strip={full_side}"); - let mut h = hotbar_harness!(side, vertical, full_side); - - // Drag the slider up to the largest size. - let slider = h.get_by_role(egui::accesskit::Role::Slider).rect(); - drag_slider_pinned!(h, slider, slider.left_center() + vec2(slider.width() * 0.2, 0.0), slider.right_center() - vec2(2.0, 0.0), what); - assert!(h.state().hotbar.button_size > 60.0, "{what}: slider did not reach the upper end"); - assert!(h.state().hotbar.picker_drag_pos.is_none(), "{what}: release must unpin the picker"); - let resized = h.get_by_role(egui::accesskit::Role::Slider).rect(); - assert_ne!(resized, slider, "{what}: picker should take its new place after release"); - if !vertical && !full_side { - assert!(resized.left() < slider.left(), "{what}: picker should move to the left after release"); - } - - // And back down to the smallest. - drag_slider_pinned!(h, resized, resized.right_center() - vec2(2.0, 0.0), resized.left_center() + vec2(2.0, 0.0), what); - assert!(h.state().hotbar.button_size < 28.0, "{what}: slider did not reach the lower end"); - assert!(h.state().hotbar.picker_drag_pos.is_none(), "{what}: release must unpin the picker"); - let restored = h.get_by_role(egui::accesskit::Role::Slider).rect(); - assert_ne!(restored, resized, "{what}: picker should take its new place after the reverse drag"); - if !vertical && !full_side { - assert!(restored.left() > resized.left(), "{what}: picker should return to the right"); - } - } - } - - /// Adjusting the Toolbar size slider with the arrow keys also keeps the picker where it is, until - /// the slider loses focus. - #[test] - fn picker_stays_put_while_resizing_hotbar_with_keyboard() { - for (side, vertical, full_side) in [("top", false, false), ("float", false, false), ("bottom", false, true), ("left", true, false)] { - let what = format!("{side}, vertical={vertical}, strip={full_side}"); - let mut h = hotbar_harness!(side, vertical, full_side); - let slider = h.get_by_role(egui::accesskit::Role::Slider).rect(); - h.get_by_role(egui::accesskit::Role::Slider).focus(); - h.run_steps(2); - assert!(h.state().hotbar.picker_drag_pos.is_none(), "{what}: focusing the slider alone must not pin the picker"); - - // The slider moves about a pixel per key press, so this crosses its whole travel. - for _ in 0..150 { - h.key_press(egui::Key::ArrowRight); - h.run_steps(1); - assert_eq!(h.get_by_role(egui::accesskit::Role::Slider).rect(), slider, "{what}: picker moved during keyboard resize"); - } - assert!(h.state().hotbar.button_size > 60.0, "{what}: keys did not reach the upper end"); - assert!(h.state().hotbar.picker_drag_pos.is_some(), "{what}: picker must stay pinned while the slider has focus"); - - // Moving focus away ends the adjustment. - h.key_press(egui::Key::Tab); - h.run_steps(3); - assert!(h.state().hotbar.picker_drag_pos.is_none(), "{what}: losing focus must unpin the picker"); - assert_ne!(h.get_by_role(egui::accesskit::Role::Slider).rect(), slider, "{what}: picker should take its new place after focus leaves"); - } - } - - /// A picker closed while the hotbar isn't drawn (Read mode, full screen, Organize) ends a size - /// adjustment too, so it doesn't open again at the position it was held at. - #[test] - fn closing_the_picker_ends_a_size_adjustment() { - let mut h = hotbar_harness!("top", false, false); - h.get_by_role(egui::accesskit::Role::Slider).focus(); - h.run_steps(2); - for _ in 0..20 { - h.key_press(egui::Key::ArrowRight); - h.run_steps(1); - } - assert!(h.state().hotbar.picker_drag_pos.is_some() && h.state().hotbar.keyboard_sizing, "pinned while the keys resize the bar"); - // What `close_hidden_picker` does on a pass that hides the hotbar: `show` doesn't run. - h.state_mut().hotbar.close_picker(); - assert!(h.state().hotbar.picker_drag_pos.is_none(), "closing ends the held position"); - assert!(!h.state().hotbar.keyboard_sizing, "closing ends the keyboard adjustment"); - } - - #[test] - fn hotbar_validation_and_placement() { - let mut bar = Hotbar::default(); - assert!(bar.tools.is_empty()); - bar.set_tools("comment.ink,comment.freehand_highlight,comment.ink").unwrap(); - assert_eq!(bar.tools.len(), 2); - assert!(bar.set_tools("does.not.exist").is_err()); - assert_eq!(bar.tools.len(), 2); - bar.place("right").unwrap(); - assert!(bar.vertical); - assert_eq!(bar.position, [1.0, 0.5]); - bar.place("bottom").unwrap(); - assert!(!bar.vertical); - assert_eq!(bar.position, [0.5, 1.0]); - assert_eq!(bar.dock.as_deref(), Some("bottom")); - bar.place("float").unwrap(); - assert!(bar.dock.is_none()); - } + /// An old `hotbar` object keeps its tools and the side it was docked to, drops what the dock workspace owns now + /// (position, size, full-side, placement), and a side the dock has no name for docks nowhere. #[test] fn hotbar_preferences_round_trip() { + let old = serde_json::json!({ + "tools": ["comment.freehand_highlight", "comment.ink"], + "position": [0.0, 0.5], "vertical": true, "button_size": 48.0, "dock": "left", "full_side": true, "placed": true, + }); + let (tools, side) = migrate_legacy(&old); + assert_eq!(tools, ["comment.freehand_highlight", "comment.ink"]); + assert_eq!(side, Some(DockSide::Start)); + assert_eq!(migrate_legacy(&serde_json::json!({ "dock": "top" })).1, Some(DockSide::Top)); + assert_eq!(migrate_legacy(&serde_json::json!({ "dock": "float" })).1, None); + + // The list survives a save and a restore, and nothing but the list is saved. + let mut bar = Hotbar::default(); + bar.set_tools("comment.freehand_highlight,comment.ink").unwrap(); + let saved = serde_json::to_value(&bar).unwrap(); + assert_eq!(saved, serde_json::json!({ "tools": ["comment.freehand_highlight", "comment.ink"] })); + let restored: Hotbar = serde_json::from_value(old).unwrap(); + assert_eq!(restored.tools, bar.tools, "an old object with the dropped keys still deserializes"); + + // The floating bar's options are gone from the control channel. + // PLAN: the app is built through `with_host` (pdf-shell-w9); the options error once pdf-hub-w3 removes them. let mut app = PdfCraftApp::new(); + for key in ["hotbar-size", "hotbar-side", "hotbar-full-side"] { + assert!(app.set_option(key, "left").is_err(), "{key} is removed"); + } app.set_option("hotbar-tools", "comment.freehand_highlight,comment.ink").unwrap(); - app.set_option("hotbar-side", "left").unwrap(); - app.set_option("hotbar-size", "48").unwrap(); - app.set_option("hotbar-full-side", "true").unwrap(); - assert!(app.set_option("hotbar-size", "NaN").is_err()); - let mut restored = PdfCraftApp::new(); - restored.restore(&app.persist()); - assert_eq!(restored.hotbar.tools, app.hotbar.tools); - assert_eq!(restored.hotbar.position, [0.0, 0.5]); - assert!(restored.hotbar.vertical); - assert_eq!(restored.hotbar.button_size, 48.0); - assert!(restored.hotbar.full_side); - assert_eq!(restored.hotbar.dock.as_deref(), Some("left")); + let saved = app.persist(); + let mut fresh = PdfCraftApp::new(); + fresh.restore(&saved); + assert_eq!(fresh.hotbar.tools, app.hotbar.tools); } + /// Ids the registry no longer has, and duplicates, are dropped on restore; an unknown id given to the control + /// channel is refused and leaves the list as it was. #[test] fn hotbar_restore_filters_unknown_tools_and_offscreen_positions() { - let mut app = PdfCraftApp::new(); - app.restore(r#"{"hotbar":{"tools":["invalid","comment.ink","comment.ink"],"position":[-10,999]}}"#); - assert_eq!(app.hotbar.tools, ["comment.ink"]); - assert_eq!(app.hotbar.position, [0.0, 1.0]); - } + let (tools, _) = migrate_legacy(&serde_json::json!({ "tools": ["invalid", "comment.ink", "comment.ink"] })); + assert_eq!(tools, ["comment.ink"]); - #[test] - fn hotbar_restore_moves_legacy_default_into_margin_and_keeps_chosen_spots() { let mut app = PdfCraftApp::new(); - app.restore(r#"{"hotbar":{"tools":["comment.ink"],"position":[0.5,0.0],"vertical":false,"button_size":40.0,"dock":null}}"#); - assert_eq!(app.hotbar.position, [0.0, 0.0]); - assert!(app.hotbar.vertical); - assert!(!app.hotbar.placed); + app.hotbar.set_tools("comment.ink").unwrap(); + assert!(app.set_option("hotbar-tools", "does.not.exist").is_err()); assert_eq!(app.hotbar.tools, ["comment.ink"]); - assert_eq!(app.hotbar.button_size, 40.0); - app.restore(r#"{"hotbar":{"position":[0.0,0.0],"vertical":false,"dock":null}}"#); - assert_eq!(app.hotbar.position, [0.0, 0.0]); - assert!(!app.hotbar.vertical); - assert!(app.hotbar.placed, "a legacy bar dragged to the corner stays there"); - app.restore(r#"{"hotbar":{"position":[0.5,0.0],"vertical":false,"dock":null,"placed":true}}"#); - assert_eq!(app.hotbar.position, [0.5, 0.0], "current preferences are not migrated"); - assert!(!app.hotbar.vertical); - } - - #[test] - fn hotbar_search_matches_translated_and_canonical_labels() { - if !crate::i18n::needs_catalogs() { - return; - } - let ink = command("comment.ink").unwrap(); - crate::i18n::set_current(crate::i18n::lang_from_tag("fr").unwrap()); - assert_eq!(tl!(ink.label), "Dessiner à main levée"); - assert!(matches_search(ink, "dessiner"), "translated French label must match"); - assert!(matches_search(ink, "freehand"), "canonical English label must still match"); - assert!(matches_search(ink, "comment.ink"), "command ID must still match"); - assert!(!matches_search(ink, "introuvable")); - crate::i18n::set_current(crate::i18n::Lang::EN); } }