From 7e2fe112b6931a8a4c8f0e87a80b7b66634d2bcf Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:27 -0500 Subject: [PATCH] pdf-comments-w10: net change of 3 commits - pdf-comments-w10: written from its sheet - pdf-comments-w10: repair 1 - pdf-comments-w10: review fixes (review-1) --- crates/ui-egui/src/colour_picker.rs | 82 +++ crates/ui-egui/src/tools/comments/colours.rs | 117 ++++ crates/ui-egui/src/tools/comments/menu.rs | 672 +++++++------------ crates/ui-egui/src/tools/comments/popups.rs | 647 +++++------------- 4 files changed, 638 insertions(+), 880 deletions(-) create mode 100644 crates/ui-egui/src/colour_picker.rs create mode 100644 crates/ui-egui/src/tools/comments/colours.rs diff --git a/crates/ui-egui/src/colour_picker.rs b/crates/ui-egui/src/colour_picker.rs new file mode 100644 index 0000000000..205f3bcd43 --- /dev/null +++ b/crates/ui-egui/src/colour_picker.rs @@ -0,0 +1,82 @@ +//! The host's colour picker for the Other… cell of the palettes: one request, one continuation. + +use craft::color_ui::ui::{ColorPickerDialog, ColorPickerResult}; +use craft::theme::Srgba; +use craft::ui::dialog::{DialogHost, DialogResult}; +use craft::ui::runtime::requests::ColorRequest; + +use crate::PdfCraftApp; +use crate::comments::to_rgb; + +/// What runs with the colour a picker was confirmed with. +type Then = Box; + +/// The dialog host a picker opens on. +pub(crate) enum PickerHost<'a> { + /// The app's own dialog host. + App, + /// The host of another window that runs its own dialogs (Preferences); named so it can be passed without + /// borrowing the app. + Window(&'a mut DialogHost), +} + +/// The continuations of the colour pickers that are open, by request key. +#[derive(Default)] +pub(crate) struct ColourPicks { + pending: Vec<(String, Then)>, +} + +impl ColourPicks { + /// Opens a picker for `request` on `host` and keeps `then` for its answer. A picker already open keeps the + /// input and the request is dropped. + fn open(&mut self, host: &mut DialogHost, request: ColorRequest, then: Then) { + let key = request.key.clone(); + if host.open_unless_open(ColorPickerDialog::from_request(request)).is_ok() { + self.pending.retain(|(k, _)| *k != key); + self.pending.push((key, then)); + } + } + + /// The pickers of `host` that finished: the continuation of each confirmed one with its colour. A cancelled + /// picker drops its continuation. + pub(crate) fn take_answers(&mut self, host: &mut DialogHost) -> Vec<(Then, Srgba)> { + let mut answers = Vec::new(); + while let Some((result, key)) = host.take_keyed::() { + let confirmed: Option = match result { + DialogResult::Ok(r) => Some(r), + DialogResult::Cancel => None, + }; + let key = confirmed.as_ref().map(|r| r.key.clone()).or(key); + let Some(at) = key.and_then(|key| self.pending.iter().position(|(k, _)| *k == key)) else { continue }; + let (_, then) = self.pending.remove(at); + if let Some(r) = confirmed { + answers.push((then, r.picked.color)); + } + } + answers + } +} + +impl PdfCraftApp { + /// Opens the colour picker for `request` on `host` and runs `then` with the colour when it is confirmed. + /// The picker never closes the menu or popover that asked. + // PLAN: assumed fields `colour_picks: ColourPicks` and `dialogs: DialogHost` on PdfCraftApp (pdf-hub-w1) + pub(crate) fn open_colour_picker(&mut self, host: PickerHost<'_>, request: ColorRequest, then: impl FnOnce(&mut PdfCraftApp, Srgba) + 'static) { + let host = match host { + PickerHost::App => &mut self.dialogs, + PickerHost::Window(h) => h, + }; + self.colour_picks.open(host, request, Box::new(then)); + } +} + +/// Runs the continuations of the pickers the app's dialog host finished, once per pass. Every colour picked +/// here came through Other…, so each is remembered as a recent colour first. +// PLAN: pdf-hub-w2 calls this without a context. +pub(crate) fn colour_picker_pass(app: &mut PdfCraftApp) { + // PLAN: assumed field `recent_colours: RecentColours` on PdfCraftApp (pdf-hub-w1) + for (then, color) in app.colour_picks.take_answers(&mut app.dialogs) { + app.recent_colours.remember(to_rgb(color)); + then(app, color); + } +} diff --git a/crates/ui-egui/src/tools/comments/colours.rs b/crates/ui-egui/src/tools/comments/colours.rs new file mode 100644 index 0000000000..72b249f603 --- /dev/null +++ b/crates/ui-egui/src/tools/comments/colours.rs @@ -0,0 +1,117 @@ +//! The comment colour rows: the named swatches as the framework palette takes them, the session's +//! recent custom colours, and the "no fill" / "same as text" choices above a palette. + +use std::sync::{Arc, PoisonError, RwLock}; + +use craft::behavior::Mixed; +use craft::color_ui::ui::SwatchPalette; +use craft::theme::Srgba; +use craft::ui::buttons::ToggleButton; +use craft::ui::contract::{Bind, Show as _}; +use craft::ui::runtime::env::Label; +use craft::ui::runtime::requests::ColorRequest; + +use super::{Rgb, SWATCHES}; + +/// How many custom colours the "Recent colours" row keeps. +const RECENT_CUSTOM: usize = 5; + +/// How far apart two colours' components may be and still count as the same colour. +const SAME_WITHIN: f64 = 0.02; + +/// The named swatches in the palette's own types, named in the current language. +pub(crate) fn swatches() -> Vec<(Label, Srgba)> { + SWATCHES.iter().map(|(name, c)| (Label::from(tl!(name).to_string()), to_srgba(*c))).collect() +} + +/// A colour in the palette's float type; components outside 0..=1 are clamped. +pub(crate) fn to_srgba(c: Rgb) -> Srgba { + let [r, g, b] = c.map(|v| v.clamp(0.0, 1.0) as f32); + Srgba::rgb(r, g, b) +} + +/// A palette colour as the engine's colour; alpha is dropped. +pub(crate) fn to_rgb(c: Srgba) -> Rgb { + [c.r, c.g, c.b].map(|v| f64::from(v.clamp(0.0, 1.0))) +} + +/// Whether two colours are the same one, give or take the rounding a picker adds. +pub(crate) fn same_colour(a: &Rgb, b: &Rgb) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < SAME_WITHIN) +} + +/// Custom colours picked with "Other colour…" this session, newest first. A handle: clones share the +/// list, so a dialog's colour rows, which cannot borrow the app, show what the app remembers. +#[derive(Clone, Default)] +pub(crate) struct RecentColours(Arc>>); + +impl RecentColours { + /// Puts `c` first (once, at most five). A colour that is a swatch, or not a finite colour, is not kept. + pub(crate) fn remember(&self, c: Rgb) { + if !c.iter().all(|v| v.is_finite()) || SWATCHES.iter().any(|(_, s)| same_colour(s, &c)) { + return; + } + let c = c.map(|v| v.clamp(0.0, 1.0)); + let mut recent = self.0.write().unwrap_or_else(PoisonError::into_inner); + recent.retain(|r| !same_colour(r, &c)); + recent.insert(0, c); + recent.truncate(RECENT_CUSTOM); + } + + /// The remembered colours, newest first, as the palette takes them. + pub(crate) fn as_srgba(&self) -> Vec { + self.0.read().unwrap_or_else(PoisonError::into_inner).iter().copied().map(to_srgba).collect() + } +} + +/// What a palette reported this pass. +#[derive(Default)] +pub(crate) struct PalettePick { + /// The colour of a swatch or recent colour that was clicked, also the one already current. + pub(crate) picked: Option, + /// The Other… cell was activated: the host opens its colour picker for this request. + pub(crate) request: Option, +} + +/// The swatches, an Other… cell keyed `key` and the recent colours, with `current` marked (none marks no +/// swatch). Every click on a swatch is reported, so a click on the colour a lead comment has still colours +/// the others of a selection. +pub(crate) fn palette(ui: &mut egui::Ui, label: &str, current: Option, key: &str, recent: &RecentColours) -> PalettePick { + let mut shown: Mixed> = Mixed::Same(current.map(to_srgba)); + let named = swatches(); + let recent = recent.as_srgba(); + let out = SwatchPalette::optional(Label::from(label.to_string()), Bind::bound_mixed(&mut shown), &named) + .other(key, tl!("Other colour…")) + .recent(tl!("Recent colours"), &recent) + .show(ui); + PalettePick { picked: out.picked.map(to_rgb), request: out.pick_color } +} + +/// What a none-or-colour choice reported this pass. +#[derive(Default)] +pub(crate) struct ColourChoice { + /// `Some(None)`: the "none" row was chosen; `Some(Some(c))`: a colour. + pub(crate) choice: Option>, + /// The Other… cell was activated. + pub(crate) request: Option, +} + +fn choice(ui: &mut egui::Ui, none_label: &str, current: Option, key: &str, recent: &RecentColours) -> ColourChoice { + let was = current.is_none(); + let mut on = was; + ToggleButton::new(none_label, Bind::bound(&mut on)).show(ui); + let pick = palette(ui, tl!("Colour"), current, key, recent); + // Turning the row off does nothing: it stands for no colour, which only another pick replaces. + let choice = if on && !was { Some(None) } else { pick.picked.map(Some) }; + ColourChoice { choice, request: pick.request } +} + +/// "No fill" above the palette. +pub(crate) fn fill_choice(ui: &mut egui::Ui, current: Option, key: &str, recent: &RecentColours) -> ColourChoice { + choice(ui, tl!("No fill"), current, key, recent) +} + +/// "Same as text" above the palette, for a border that takes the text's colour unless picked. +pub(crate) fn border_choice(ui: &mut egui::Ui, current: Option, key: &str, recent: &RecentColours) -> ColourChoice { + choice(ui, tl!("Same as text"), current, key, recent) +} diff --git a/crates/ui-egui/src/tools/comments/menu.rs b/crates/ui-egui/src/tools/comments/menu.rs index d8da11fcc3..fe659b3550 100644 --- a/crates/ui-egui/src/tools/comments/menu.rs +++ b/crates/ui-egui/src/tools/comments/menu.rs @@ -1,26 +1,53 @@ -use super::input::delete_selected; -use super::paint::edit_anchor; -use super::state::{Composer, ComposerKind, Gesture}; -use super::{ - Annotation, Color32, CommentPrefs, CommentTool, DocInfo, DocView, Edit, Rect, ReviewState, Rgb, SELECT_BLUE, SWATCHES, Sense, Stroke, color32, - defaultable, icons, theme, vec2, -}; +use craft::behavior::{IconId, Mixed}; +use craft::keymap::CommandRef; +use craft::ui::buttons::{IconButton, ToggleButton}; +use craft::ui::choice::Swatch; +use craft::ui::contract::overlay::Trigger; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::Divider; +use craft::ui::form::SliderField; -/// Save attachment… and, for a PDF, Open in a new tab, first in a file attachment comment's -/// menus as in the Attachments panel: the comment is where the reader finds its file. Reading -/// the file changes nothing, so a read-only document offers them too. -pub(crate) fn attachment_items(ui: &mut egui::Ui, view: &mut DocView, info: &DocInfo, a: &Annotation) { +use craft::ui::menu::{Menu, MenuItem}; +use craft::ui::popover::Popover; +use craft::ui::runtime::env::Env; +use craft::ui::runtime::requests::ColorRequest; +use craft::review::ui::annotate::AnnotateWords; + +// PLAN: `mod colours;` is declared in `tools/comments.rs` (pdf-comments-w7). +use super::colours::{self, RecentColours, fill_choice, palette, to_srgba}; +use super::state::{Composer, ComposerKind}; +use super::{Annotation, CommentPrefs, CommentTool, DocInfo, DocView, Edit, ReviewState, Rgb, defaultable}; + +/// A row of the attachment actions: its label and whether the file opens in a new tab rather than being saved. +pub(crate) struct AttachmentRow { + pub(crate) label: &'static str, + pub(crate) open_in_tab: bool, +} + +/// The attachment actions of a file attachment comment, written once for the menu and the Comments panel card: +/// Save attachment… and, for a PDF, Open in a new tab. Reading the file changes nothing, so a read-only document +/// offers them too. +pub(crate) fn attachment_rows(info: &DocInfo, a: &Annotation) -> Vec { let source = pdfcraft_render::AttachmentSource::Annotation { page: a.page, index: a.index }; - let Some(file) = info.attachments.iter().find(|f| f.source == source) else { return }; - if ui.button(tl!("Save attachment…")).clicked() { - view.comments.attachment_request = Some((a.page, a.index, false)); - ui.close(); + let Some(file) = info.attachments.iter().find(|f| f.source == source) else { return Vec::new() }; + let mut rows = vec![AttachmentRow { label: tl!("Save attachment…"), open_in_tab: false }]; + if file.name.to_lowercase().ends_with(".pdf") { + rows.push(AttachmentRow { label: tl!("Open in a new tab"), open_in_tab: true }); } - if file.name.to_lowercase().ends_with(".pdf") && ui.button(tl!("Open in a new tab")).clicked() { - view.comments.attachment_request = Some((a.page, a.index, true)); - ui.close(); + rows +} + +/// The attachment rows first in a file attachment comment's menu, with a rule after them. +pub(crate) fn attachment_items(ui: &mut egui::Ui, view: &mut DocView, info: &DocInfo, a: &Annotation) { + let rows = attachment_rows(info, a); + for row in &rows { + if MenuItem::new(row.label).show(ui).ran { + view.comments.attachment_request = Some((a.page, a.index, row.open_in_tab)); + } + } + if !rows.is_empty() { + Divider::horizontal().show(ui); } - ui.separator(); } /// What the canvas context menu may offer. @@ -28,164 +55,10 @@ pub(crate) fn attachment_items(ui: &mut egui::Ui, view: &mut DocView, info: &Doc pub(crate) struct MenuRights { /// Comments may be added and changed. pub(crate) allowed: bool, - /// Copied comments wait to be pasted. - pub(crate) can_paste: bool, /// The document's pages may change (Flatten comments draws into them). pub(crate) can_modify: bool, } -/// Items of the canvas context menu for the selected comment (or the page). -/// `deletable`: whether Delete would delete the comment at (page, index) (the engine's -/// `Document::annotation_deletable`: unlocked, and no locked reply to it). -pub(crate) fn context_menu( - ui: &mut egui::Ui, - view: &mut DocView, - info: &DocInfo, - deletable: &dyn Fn(usize, usize) -> bool, - prefs: &CommentPrefs, - rights: MenuRights, -) -> Option { - let MenuRights { allowed, can_paste, can_modify } = rights; - let mut action = None; - // Connected lines, a polygon or a cloud being drawn: finish it from the menu, as other - // editors do (Enter and a double-click finish it too), take the last point back, or stop. - if let Some(Gesture::Draw { tool, points, .. }) = &view.comments.gesture - && tool.clicks_points() - { - let enough = points.len() >= if *tool == CommentTool::PolyLine { 2 } else { 3 }; - if ui.add_enabled(enough, egui::Button::new(tl!("Complete"))).clicked() { - view.comments.finish_request = true; - ui.close(); - } - if ui.button(tl!("Undo last point")).clicked() { - view.comments.undo_point(); - ui.close(); - } - if ui.button(tl!("Cancel drawing")).clicked() { - view.comments.gesture = None; - ui.close(); - } - return None; - } - let selected = view.comments.selected.and_then(|(p, i)| info.annotations.iter().find(|a| a.page == p && a.index == i && !a.is_reply())); - let several = view.comments.also.len(); - match selected { - Some(a) => { - let (page, index) = (a.page, a.index); - attachment_items(ui, view, info, a); - if ui.add_enabled(allowed, egui::Button::new(tl!("Edit text…"))).clicked() { - view.comments.composer = Some(Composer { - page, - at: edit_anchor(info, a), - kind: ComposerKind::Edit(index), - text: a.contents.clone().unwrap_or_default(), - focus: true, - }); - ui.close(); - } - if ui.add_enabled(allowed, egui::Button::new(tl!("Reply"))).clicked() { - view.comments.reveal = true; - action = Some(CanvasAction::OpenComments); - ui.close(); - } - ui.add_enabled_ui(allowed, |ui| { - ui.menu_button(tl!("Set status"), |ui| { - for s in [ReviewState::None, ReviewState::Accepted, ReviewState::Cancelled, ReviewState::Completed, ReviewState::Rejected] { - if ui.button(tl!(s.name())).clicked() { - action = - Some(CanvasAction::Edit(Box::new(Edit::SetAnnotationStatus { page, index, state: s, author: prefs.author.clone() }))); - ui.close(); - } - } - }); - let keep_open = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); - let _ = egui::containers::menu::SubMenuButton::new(tl!("Colour")).config(keep_open).ui(ui, |ui| { - if let Some(c) = swatch_grid(ui, a.color.map(|c| c.map(f64::from))) { - // Several selected: the app gives each of them the colour. - action = Some(if several > 0 { - CanvasAction::Colour(c) - } else { - CanvasAction::Edit(Box::new(Edit::StyleAnnotation { - page, - index, - color: Some(c), - opacity: None, - width: None, - endings: None, - })) - }); - ui.close(); - } - }); - }); - // The checkmark of the reviewer using this copy: checkmarks are each reviewer's own - // (ISO 32000-2 Table 174: "The annotation has been marked by the user"). - let marked = pdfcraft_render::ReviewStates::new(&info.annotations).marked_by(a, &prefs.author); - if ui.add_enabled(allowed, egui::Button::new(tl!(if marked { "Remove checkmark" } else { "Mark with checkmark" }))).clicked() { - action = Some(CanvasAction::Edit(Box::new(Edit::MarkAnnotation { page, index, marked: !marked, author: prefs.author.clone() }))); - ui.close(); - } - if ui.button(tl!("Copy text")).clicked() { - ui.ctx().copy_text(a.contents.clone().unwrap_or_default()); - ui.close(); - } - ui.separator(); - // The comments themselves, to paste into this or another document (⌘C / ⌘V too). - let copy_key = crate::commands::shortcut_label(ui.ctx(), crate::commands::COPY); - if ui.add(egui::Button::new(tl!(if several > 0 { "Copy comments" } else { "Copy comment" })).shortcut_text(copy_key)).clicked() { - view.comments.copy_request = true; - ui.close(); - } - let paste_key = crate::commands::shortcut_label(ui.ctx(), crate::commands::PASTE); - if ui.add_enabled(allowed && can_paste, egui::Button::new(tl!("Paste comments")).shortcut_text(paste_key)).clicked() { - let at = view.comments.context_at.unwrap_or((page, [f64::from(a.rect[0]), f64::from(a.rect[1])])); - view.comments.paste_request = Some(at); - ui.close(); - } - ui.separator(); - // The engine's own check, for each selected comment: a locked comment, or one with a - // locked reply, stays. On a group subordinate, Delete takes just it, as Acrobat's does. - let (dpage, dindex) = view.comments.target().unwrap_or((page, index)); - let deletes = deletable(dpage, dindex) && view.comments.also.iter().all(|&(p, i)| deletable(p, i)); - if ui.add_enabled(allowed && deletes, egui::Button::new(tl!(if several > 0 { "Delete comments" } else { "Delete" }))).clicked() { - action = delete_selected(&mut view.comments, info).map(|e| CanvasAction::Edit(Box::new(e))); - ui.close(); - } - if ui.add_enabled(allowed, egui::Button::new(tl!("Properties…"))).clicked() { - action = Some(CanvasAction::Properties(page, index)); - ui.close(); - } - if ui.add_enabled(defaultable(a), egui::Button::new(tl!("Make Current Properties Default"))).clicked() { - view.comments.default_request = Some((page, index)); - ui.close(); - } - } - None => { - if let Some((page, at)) = view.comments.context_at - && ui.add_enabled(allowed, egui::Button::new(tl!("Add a sticky note here"))).clicked() - { - view.comments.composer = Some(Composer { page, at, kind: ComposerKind::Note, text: String::new(), focus: true }); - ui.close(); - } - if ui.button(tl!("Comments panel")).clicked() { - action = Some(CanvasAction::OpenComments); - ui.close(); - } - } - } - // Every comment of the document into its pages, as Comment ▸ Flatten comments does: signed - // or reviewed pages whose comments should no longer move. - if !info.annotations.is_empty() { - ui.separator(); - if ui.add_enabled(can_modify, egui::Button::new(tl!("Flatten comments"))).clicked() { - view.comments.select(None); - action = Some(CanvasAction::Edit(Box::new(Edit::Flatten { comments: true, fields: false }))); - ui.close(); - } - } - action -} - /// What the canvas asks the app to do. #[derive(Clone, Debug, PartialEq)] pub enum CanvasAction { @@ -193,277 +66,248 @@ pub enum CanvasAction { OpenComments, /// Comment Properties for (page, index). Properties(usize, usize), + /// Put this text on the clipboard, through the app's clipboard service. + CopyText(String), /// Give every selected comment this colour. Colour(Rgb), + /// Open the host's colour picker for the Colour submenu's Other… cell; its answer colours the selected comments. + // PLAN: pdf-canvas-w8 maps this to `open_colour_picker` with `colour_selected_comments` as the continuation. + ColourRequest(ColorRequest), /// Copy Image: image (page, index in `page_images`) to the clipboard. CopyImage(usize, usize), /// Copy Image in Original Format: the same image as a file (JPEG as stored, else PNG). CopyImageFile(usize, usize), } -/// How many custom colours the "Recent colours" row keeps. -pub(super) const RECENT_CUSTOM: usize = 5; - -/// Return the stable egui id for the recent custom-colour palette. -fn recent_custom_id() -> egui::Id { - egui::Id::unique("pdfcraft-recent-custom-colours") +/// What the comment rows of the canvas context menu read. +pub(crate) struct CommentMenuCx<'a> { + pub(crate) view: &'a mut DocView, + pub(crate) info: &'a DocInfo, + /// Whether Delete would delete the comment at (page, index) (the engine's `Document::annotation_deletable`: + /// unlocked, and no locked reply to it). + pub(crate) deletable: &'a dyn Fn(usize, usize) -> bool, + pub(crate) prefs: &'a CommentPrefs, + pub(crate) rights: MenuRights, + pub(crate) recent: &'a RecentColours, + /// The active comment tool, for the rows of a shape being drawn. + pub(crate) tool: Option, } -/// Custom colours picked with "Other colour…" this session, newest first (#1193). -pub fn recent_custom_colours(ctx: &egui::Context) -> Vec { - ctx.data(|d| d.get_temp::>(recent_custom_id())).unwrap_or_default() +fn row(ui: &mut egui::Ui, label: &str, enabled: bool) -> bool { + MenuItem::new(label).enabled(enabled).show(ui).ran } -/// Put `c` first in the recent custom colours (once, at most [`RECENT_CUSTOM`]). Colours that are -/// already swatches are not repeated there. -pub fn remember_custom_colour(ctx: &egui::Context, c: Rgb) { - if !c.iter().all(|v| v.is_finite()) || SWATCHES.iter().any(|(_, s)| same_colour(s, &c)) { - return; - } - let c = c.map(|v| v.clamp(0.0, 1.0)); - ctx.data_mut(|d| { - let recent = d.get_temp_mut_or_default::>(recent_custom_id()); - recent.retain(|r| !same_colour(r, &c)); - recent.insert(0, c); - recent.truncate(RECENT_CUSTOM); - }); -} - -pub(super) fn same_colour(a: &Rgb, b: &Rgb) -> bool { - a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.02) -} - -fn rgb_of(c: Color32) -> Rgb { - [c.r(), c.g(), c.b()].map(|v| f64::from(v) / 255.0) -} - -/// One round swatch; `on` rings it as the current colour. -fn swatch(ui: &mut egui::Ui, c: Rgb, on: bool, tooltip: &str) -> egui::Response { - let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tooltip)); - ui.painter().circle_filled(r.center(), 9.0, color32(c)); - ui.painter().circle_stroke(r.center(), 9.0, Stroke::new(1.0, Color32::from_black_alpha(40))); - if on || resp.hovered() { - ui.painter().circle_stroke(r.center(), 11.0, Stroke::new(1.5, SELECT_BLUE)); - } - resp.on_hover_text(tooltip) -} - -/// The "+" swatch that opens "Other colour…": a ring with a plus, the size of a swatch. -fn other_colour_swatch(ui: &mut egui::Ui, open: bool) -> egui::Response { - let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click()); - let ink = ui.visuals().widgets.inactive.fg_stroke.color; - ui.painter().circle_stroke(r.center(), 9.0, Stroke::new(1.0, ink.gamma_multiply(0.6))); - let c = r.center(); - for d in [vec2(4.5, 0.0), vec2(0.0, 4.5)] { - ui.painter().line_segment([c - d, c + d], Stroke::new(1.5, ink)); - } - if open || resp.hovered() { - ui.painter().circle_stroke(c, 11.0, Stroke::new(1.5, SELECT_BLUE)); - } - let label = tl!("Other colour…"); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, open, label)); - resp.on_hover_text(label) -} - -/// A grid of colour swatches with a "+" swatch for "Other colour…" (a full picker, as Acrobat's -/// quick colours offer) and, once used, the recent custom colours; returns the colour chosen. -/// The "+" sits in the first row, so the grid is no taller than before until the picker opens. -pub fn swatch_grid(ui: &mut egui::Ui, current: Option) -> Option { - let mut picked = None; - let on = |c: &Rgb| current.is_some_and(|cur| same_colour(&cur, c)); - // Keyed on this grid's own place in the parent, so two grids in one dialog open their - // pickers separately. - let base = ui.next_auto_id(); - ui.skip_ahead_auto_ids(1); - let open_id = base.with("other-colour"); - let value_id = open_id.with("value"); - let mut open = ui.data(|d| d.get_temp::(open_id)).unwrap_or(false); - egui::Grid::new(base.with("swatches")).spacing(vec2(6.0, 6.0)).show(ui, |ui| { - for (i, (name, c)) in SWATCHES.iter().enumerate() { - if swatch(ui, *c, on(c), tl!(name)).clicked() { - picked = Some(*c); - } - if i == 4 && other_colour_swatch(ui, open).clicked() { - open = !open; - // Start from the current colour each time the picker opens. - ui.data_mut(|d| d.insert_temp(value_id, current.map_or(Color32::BLACK, color32))); - } - if i % 5 == 4 { - ui.end_row(); - } +/// Rows of the canvas context menu for the selected comment (or the page), inside `Menu::context`. +pub(crate) fn context_rows(ui: &mut egui::Ui, cx: CommentMenuCx<'_>) -> Option { + let CommentMenuCx { view, info, deletable, prefs, rights, recent, tool } = cx; + let MenuRights { allowed, can_modify } = rights; + let mut action = None; + // Connected lines, a polygon or a cloud being drawn: finish it from the menu, as other editors do (Enter + // and a double-click finish it too), take the last point back, or stop. + if let Some(tool) = tool.filter(|t| t.clicks_points()) + && !view.comments.tool.drawing().is_empty() + { + let enough = view.comments.tool.drawing().len() >= if tool == CommentTool::PolyLine { 2 } else { 3 }; + if row(ui, tl!("Complete"), enough) { + let words = Env::of(ui).words::(); + view.comments.tool.finish_drawing(&words); } - }); - let recent = recent_custom_colours(ui.ctx()); - if !recent.is_empty() { - ui.label(egui::RichText::new(tl!("Recent colours")).small()); - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 6.0; - for c in &recent { - let [r, g, b, _] = color32(*c).to_array(); - if swatch(ui, *c, on(c), &format!("#{r:02X}{g:02X}{b:02X}")).clicked() { - picked = Some(*c); + if row(ui, tl!("Undo last point"), true) { + view.comments.tool.undo_point(); + } + if row(ui, tl!("Cancel drawing"), true) { + view.comments.tool.cancel_drawing(); + } + return None; + } + // PLAN: assumed `CommentView::primary() -> Option<(usize, usize)>` and `selection()` (pdf-comments-w7, A-2) + let selected = view.comments.primary().and_then(|(p, i)| info.annotations.iter().find(|a| a.page == p && a.index == i && !a.is_reply())); + let several = view.comments.selection().len() > 1; + match selected { + Some(a) => { + let (page, index) = (a.page, a.index); + attachment_items(ui, view, info, a); + if row(ui, tl!("Edit text…"), allowed) { + view.comments.composer = Some(Composer { + page, + at: super::bridge::edit_anchor(info, a), + kind: ComposerKind::Edit(index), + text: a.contents.clone().unwrap_or_default(), + focus: true, + }); + } + if row(ui, tl!("Reply"), allowed) { + view.comments.reveal = true; + action = Some(CanvasAction::OpenComments); + } + Menu::submenu_row_enabled(ui, tl!("Set status"), allowed, |ui, _| { + for s in [ReviewState::None, ReviewState::Accepted, ReviewState::Cancelled, ReviewState::Completed, ReviewState::Rejected] { + if row(ui, tl!(s.name()), true) { + action = Some(CanvasAction::Edit(Box::new(Edit::SetAnnotationStatus { page, index, state: s, author: prefs.author.clone() }))); + } } + }); + Menu::submenu_row_enabled(ui, tl!("Colour"), allowed, |ui, _| { + let pick = palette(ui, tl!("Colour"), a.color.map(|c| c.map(f64::from)), "comment.menu.colour", recent); + if let Some(c) = pick.picked { + // Several selected: the app gives each of them the colour. + action = Some(if several { + CanvasAction::Colour(c) + } else { + CanvasAction::Edit(Box::new(Edit::StyleAnnotation { page, index, color: Some(c), opacity: None, width: None, endings: None })) + }); + } + if let Some(request) = pick.request { + action = Some(CanvasAction::ColourRequest(request)); + } + }); + // The checkmark of the reviewer using this copy: checkmarks are each reviewer's own + // (ISO 32000-2 Table 174: "The annotation has been marked by the user"). + let marked = pdfcraft_render::ReviewStates::new(&info.annotations).marked_by(a, &prefs.author); + if row(ui, tl!(if marked { "Remove checkmark" } else { "Mark with checkmark" }), allowed) { + action = Some(CanvasAction::Edit(Box::new(Edit::MarkAnnotation { page, index, marked: !marked, author: prefs.author.clone() }))); + } + if row(ui, tl!("Copy text"), true) { + action = Some(CanvasAction::CopyText(a.contents.clone().unwrap_or_default())); + } + Divider::horizontal().show(ui); + // The comments themselves, to paste into this or another document; the rows take their chords + // from the command board. + // The command board owns both gates: the Paste handler (pdf-canvas-w16) reads `allowed`, the + // clipboard and the paste place (`view.comments.context_at`). + MenuItem::command(CommandRef::new("edit.copy")).show(ui); + MenuItem::command(CommandRef::new("edit.paste")).show(ui); + Divider::horizontal().show(ui); + // The engine's own check, for each selected comment: a locked comment, or one with a locked + // reply, stays. On a group subordinate, Delete takes just it, as Acrobat's does. + let (dpage, dindex) = view.comments.target().unwrap_or((page, index)); + let deletes = deletable(dpage, dindex) && view.comments.selection().iter().all(|&(p, i)| deletable(p, i)); + if row(ui, tl!(if several { "Delete comments" } else { "Delete" }), allowed && deletes) { + action = super::bridge::delete_selected(&mut view.comments, info).map(|e| CanvasAction::Edit(Box::new(e))); + } + if row(ui, tl!("Properties…"), allowed) { + action = Some(CanvasAction::Properties(page, index)); + } + if row(ui, tl!("Make Current Properties Default"), defaultable(a)) { + view.comments.default_request = Some((page, index)); + } + } + None => { + if let Some((page, at)) = view.comments.context_at + && row(ui, tl!("Add a sticky note here"), allowed) + { + view.comments.composer = Some(Composer { page, at, kind: ComposerKind::Note, text: String::new(), focus: true }); + } + if row(ui, tl!("Comments panel"), true) { + action = Some(CanvasAction::OpenComments); } - }); - } - if open && picked.is_none() { - let mut value = ui.data(|d| d.get_temp::(value_id)).unwrap_or_else(|| current.map_or(Color32::BLACK, color32)); - egui::widgets::color_picker::color_picker_color32(ui, &mut value, egui::widgets::color_picker::Alpha::Opaque); - ui.data_mut(|d| d.insert_temp(value_id, value)); - // Dragging in the picker previews nothing; Apply commits once (one undo step). - if ui.button(tl!("Apply")).clicked() { - let c = rgb_of(value); - remember_custom_colour(ui.ctx(), c); - picked = Some(c); } } - if picked.is_some() { - open = false; + // Every comment of the document into its pages, as Comment ▸ Flatten comments does: signed or reviewed + // pages whose comments should no longer move. + if !info.annotations.is_empty() { + Divider::horizontal().show(ui); + if row(ui, tl!("Flatten comments"), can_modify) { + view.comments.select(None); + action = Some(CanvasAction::Edit(Box::new(Edit::Flatten { comments: true, fields: false }))); + } } - ui.data_mut(|d| d.insert_temp(open_id, open)); - picked + action } -/// "No fill" and the colour swatches; returns the choice clicked (`Some(None)`: no fill). -pub fn fill_picker(ui: &mut egui::Ui, current: Option) -> Option> { - let mut picked = None; - ui.push_id("fill-picker", |ui| { - ui.vertical(|ui| { - if ui.selectable_label(current.is_none(), tl!("No fill")).clicked() { - picked = Some(None); - } - if let Some(c) = swatch_grid(ui, current) { - picked = Some(Some(c)); - } - }); - }); - picked +/// What the quick bar's controls reported this pass. +#[derive(Default)] +pub(crate) struct QuickBarPick { + /// The colour picked from a swatch, for the selected comments this tool made. + pub(crate) colour: Option, + /// The Other… cell of the colour or fill palette was activated: the caller opens the picker for it. + pub(crate) request: Option, } -pub(crate) fn quick_bar_colour(ui: &mut egui::Ui, current: Rgb) -> Option { - let (r, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click()); - ui.painter().circle_filled(r.center(), 9.0, color32(current)); - ui.painter().circle_stroke(r.center(), 9.0, Stroke::new(1.0, Color32::from_black_alpha(50))); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Colour"))); - let resp = resp.on_hover_text(tl!("Colour")); - let mut picked = None; - egui::Popup::menu(&resp).align(egui::RectAlign::RIGHT_START).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - if let Some(c) = swatch_grid(ui, Some(current)) { - picked = Some(c); - ui.close(); +/// A control that opens a popover under it: `opener` draws the control, a click on it opens and closes the +/// popover, and `body` fills it. The open flag is the popover's own kept value. +fn popover_from(ui: &mut egui::Ui, label: &str, opener: impl FnOnce(&mut egui::Ui) -> egui::Response, body: impl FnOnce(&mut egui::Ui)) { + let resp = opener(ui); + let mut body = Some(body); + Popover::new(label, Bind::kept()).overlay(|o| o.opened_by(&resp, Trigger::Click)).show(ui, |ui, _| { + if let Some(body) = body.take() { + body(ui); } }); - picked } /// The comment tools' extra quick-bar controls: pin, colour, fill, opacity and thickness. -pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &mut CommentPrefs) -> Option { +pub(crate) fn quick_bar_controls(ui: &mut egui::Ui, tool: CommentTool, prefs: &mut CommentPrefs, recent: &RecentColours) -> QuickBarPick { let style = prefs.style(tool); - if icons::button(ui, "pin", 32.0, prefs.pinned, if prefs.pinned { tl!("Keep tool selected: on") } else { tl!("Keep tool selected") }).clicked() { - prefs.pinned = !prefs.pinned; - } - let selected_color = quick_bar_colour(ui, style.color); - if let Some(c) = selected_color { - prefs.set_color(tool, c); - } + let mut out = QuickBarPick::default(); + let mut pinned = prefs.pinned; + ToggleButton::new(tl!("Keep tool selected"), Bind::bound(&mut pinned)).icon(IconId::new("pin")).icon_only().show(ui); + prefs.pinned = pinned; + popover_from( + ui, + tl!("Colour"), + |ui| { + Swatch::new(tl!("Colour"), colours::to_srgba(style.color)).show(ui).response + }, + |ui| { + let pick = palette(ui, tl!("Colour"), Some(style.color), "comment.tool.colour", recent); + if let Some(c) = pick.picked { + prefs.set_color(tool, c); + out.colour = Some(c); + } + out.request = pick.request; + }, + ); if tool.has_fill() { - let resp = fill_button(ui, style.fill); - egui::Popup::menu(&resp).align(egui::RectAlign::RIGHT_START).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.label(egui::RichText::new(tl!("Fill colour")).font(theme::semibold(12.0))); - if let Some(f) = fill_picker(ui, style.fill) { - prefs.set_fill(tool, f); - ui.close(); - } - }); + popover_from( + ui, + tl!("Fill colour"), + |ui| { + Swatch::optional(tl!("Fill colour"), Mixed::Same(style.fill.map(to_srgba))).show(ui).response + }, + |ui| { + let pick = fill_choice(ui, style.fill, "comment.tool.fill", recent); + if let Some(f) = pick.choice { + prefs.set_fill(tool, f); + } + if pick.request.is_some() { + out.request = pick.request; + } + }, + ); } - let resp = icons::button(ui, "blend", 32.0, false, tl!("Opacity")); - egui::Popup::menu(&resp).align(egui::RectAlign::RIGHT_START).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_min_width(180.0); - let mut percent = (style.opacity * 100.0).round(); - ui.label(egui::RichText::new(tl!("Opacity")).font(theme::semibold(12.0))); - // The whole comment's: its fill and text take it too. - if ui.add(egui::Slider::new(&mut percent, 10.0..=100.0).step_by(5.0).suffix(" %")).changed() { - prefs.set_opacity(tool, percent / 100.0); - prefs.set_part_opacity(tool, None, None); - } - }); + popover_from( + ui, + tl!("Opacity"), + |ui| { + IconButton::new(IconId::new("blend")).label(tl!("Opacity")).show(ui).response + }, + |ui| { + let mut percent = (style.opacity * 100.0).round(); + let start = percent; + SliderField::new(tl!("Opacity"), Bind::bound(&mut percent), 10.0..=100.0).step(5.0).unit("%").show(ui); + if percent != start { + // The whole comment's: its fill and text take it too. + prefs.set_opacity(tool, percent / 100.0); + prefs.set_part_opacity(tool, None, None); + } + }, + ); if tool.has_width() { - let resp = icons::button(ui, "sliders-horizontal", 32.0, false, tl!("Line thickness")); - egui::Popup::menu(&resp).align(egui::RectAlign::RIGHT_START).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| { - ui.set_min_width(180.0); - let mut w = style.width; - ui.label(egui::RichText::new(tl!("Line thickness")).font(theme::semibold(12.0))); - if ui.add(egui::Slider::new(&mut w, tool.min_width()..=super::MAX_LINE_WIDTH).step_by(0.5).suffix(" pt")).changed() { - prefs.set_width(tool, w); - } - }); - } - selected_color -} - -/// A border-colour button: a hollow square in the border's colour (`current`, else the text's, -/// `text`), with a menu of "Same as text" and the swatches. Returns the choice (`Some(None)`: -/// the text's colour again). -pub(crate) fn border_colour_button(ui: &mut egui::Ui, current: Option, text: Rgb) -> Option> { - let (r, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click()); - let sq = Rect::from_center_size(r.center(), vec2(15.0, 15.0)); - ui.painter().rect_stroke(sq, 1.0, Stroke::new(3.0, color32(current.unwrap_or(text))), egui::StrokeKind::Inside); - if resp.hovered() { - ui.painter().rect_stroke(r.shrink(2.0), 4.0, Stroke::new(1.0, Color32::from_black_alpha(40)), egui::StrokeKind::Inside); - } - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!("Border colour"))); - let resp = resp.on_hover_text(tl!("Border colour")); - let mut picked = None; - egui::Popup::menu(&resp).align(egui::RectAlign::RIGHT_START).show(|ui| { - ui.label(egui::RichText::new(tl!("Border colour")).font(theme::semibold(12.0))); - if ui.add(egui::Button::new(tl!("Same as text")).selected(current.is_none())).clicked() { - picked = Some(None); - ui.close(); - } - if let Some(c) = swatch_grid(ui, current) { - picked = Some(Some(c)); - ui.close(); - } - }); - picked -} - -/// The quick bar's fill button: a filled square in the fill colour, or a crossed-out outline -/// for no fill. -fn fill_button(ui: &mut egui::Ui, fill: Option) -> egui::Response { - let (r, resp) = ui.allocate_exact_size(vec2(32.0, 32.0), Sense::click()); - let sq = Rect::from_center_size(r.center(), vec2(16.0, 16.0)); - let edge = Stroke::new(1.0, Color32::from_black_alpha(90)); - match fill { - Some(c) => { - ui.painter().rect_filled(sq, 2.0, color32(c)); - } - None => { - ui.painter().line_segment([sq.left_bottom(), sq.right_top()], Stroke::new(1.5, Color32::from_rgb(0xD3, 0x2F, 0x2F))); - } - } - ui.painter().rect_stroke(sq, 2.0, edge, egui::StrokeKind::Inside); - if resp.hovered() { - ui.painter().rect_stroke(r.shrink(2.0), 6.0, Stroke::new(1.0, Color32::from_black_alpha(40)), egui::StrokeKind::Inside); - } - let label = match fill { - Some(_) => tl!("Fill colour"), - None => tl!("Fill colour: none"), - }; - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); - resp.on_hover_text(label) -} - -/// Status badge icon and label for a review state name. -pub fn status_badge(state: &str) -> Option<(&'static str, &'static str, Color32)> { - match state { - "Accepted" => Some(("thumbs-up", "Accepted", Color32::from_rgb(0x2D, 0x9D, 0x5B))), - "Rejected" => Some(("thumbs-down", "Rejected", Color32::from_rgb(0xD3, 0x2F, 0x2F))), - "Cancelled" => Some(("circle-x", "Cancelled", Color32::from_rgb(0x8E, 0x8E, 0x8E))), - "Completed" => Some(("check", "Completed", Color32::from_rgb(0x2D, 0x9D, 0x5B))), - // A status set back to None stays shown: None is a state (ISO 32000-2 Table 174). - "None" => Some(("minus", "None", Color32::from_rgb(0x8E, 0x8E, 0x8E))), - _ => None, + popover_from( + ui, + tl!("Line thickness"), + |ui| { + IconButton::new(IconId::new("sliders-horizontal")).label(tl!("Line thickness")).show(ui).response + }, + |ui| { + let mut w = style.width; + SliderField::new(tl!("Line thickness"), Bind::bound(&mut w), tool.min_width()..=super::MAX_LINE_WIDTH).step(0.5).unit("pt").show(ui); + if w != style.width { + prefs.set_width(tool, w); + } + }, + ); } + out } diff --git a/crates/ui-egui/src/tools/comments/popups.rs b/crates/ui-egui/src/tools/comments/popups.rs index 8ffb10dc89..7a6e688ce1 100644 --- a/crates/ui-egui/src/tools/comments/popups.rs +++ b/crates/ui-egui/src/tools/comments/popups.rs @@ -1,6 +1,8 @@ +use craft::review::ui::thread::{NOTE_POPUP_LIMITS, NoteDrafts, NotePopup, NotePopupMessage}; +use craft::ui::contract::overlay::PlacementKind; + use super::state::PageCx; -use super::{Annotation, Color32, CommentPrefs, CornerRadius, DocInfo, DocView, Edit, PagePointer, PageXform, Pos2, QuickTool, Rect, pos2, theme}; -use crate::page_keys::PageKeys; +use super::{Annotation, CommentPrefs, DocInfo, DocView, Edit, Rect}; /// A comment with a pop-up window of its own: not a text box, a Fill & Sign mark, a reply or a /// status (replies are found by `/IRT` reference, [`Annotation::is_comment`]). @@ -8,95 +10,6 @@ pub(super) fn has_popup(a: &Annotation) -> bool { a.subtype != "FreeText" && !a.fill_sign && a.is_comment() } -/// The connector from a comment to its open pop-up, in the comment's colour, while the pointer is -/// on either or the comment is selected (Acrobat's "lines connecting comment markups to their -/// pop-ups on mouse rollover"). It is a faint wedge: a point on the comment where it is -/// nearest the window, widening to a base on the window's side that faces -/// the comment ([`wedge_base`]). -pub(super) fn paint_connectors(painter: &egui::Painter, cx: &PageCx<'_>, view: &DocView, pointer: Option) { - let cv = &view.comments; - for ((page, index), window) in &cv.popup_rects { - if *page != cx.page { - continue; - } - let Some(a) = cx.get(*index) else { continue }; - if !a.popup.is_some_and(|p| p.open) { - continue; - } - let rects: Vec = cx.screen_rects(a).collect(); - let on_mark = pointer.is_some_and(|p| rects.iter().any(|r| r.expand(3.0).contains(p))); - if !(on_mark || cv.is_selected((*page, *index)) || cv.popup_hovered == Some((*page, *index))) { - continue; - } - let Some(mark) = rects.first() else { continue }; - let from = nearest_on(*mark, window.center()); - let to = nearest_on(*window, from); - if from.distance(to) < 4.0 { - continue; - } - let color = a - .color - .map_or(Color32::from_rgb(0xDC, 0x26, 0x26), |c| Color32::from_rgb((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8)); - let faded = Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), WEDGE_ALPHA); - let [b0, b1] = wedge_base(*window, from, to); - let mut wedge = egui::Mesh::default(); - for p in [from, b0, b1] { - wedge.colored_vertex(p, faded); - } - wedge.add_triangle(0, 1, 2); - painter.add(egui::Shape::mesh(wedge)); - } -} - -/// How opaque a connector's wedge is (of 255). -const WEDGE_ALPHA: u8 = 90; - -/// The two ends of a connector's base on `window`: centred on `to` (the point of the window -/// nearest the comment) along the side that faces `from`, as wide as a small part of the window -/// and kept on that side. At a corner, the side is the one the comment lies further beyond. -fn wedge_base(window: Rect, from: Pos2, to: Pos2) -> [Pos2; 2] { - let half = (window.width().min(window.height()) * 0.08).clamp(5.0, 18.0); - // `half` along [lo, hi] around `c`, moved in to stay on the side (a side shorter than the - // base gives all of it). - let spread = |c: f32, lo: f32, hi: f32| { - let h = half.min((hi - lo).max(0.0) / 2.0); - let c = c.clamp(lo + h, hi - h); - (c - h, c + h) - }; - let on_horizontal = (to.y - window.top()).abs() < 0.5 || (to.y - window.bottom()).abs() < 0.5; - let on_vertical = (to.x - window.left()).abs() < 0.5 || (to.x - window.right()).abs() < 0.5; - let beyond_x = (from.x - to.x).abs() / window.width().max(1.0); - let beyond_y = (from.y - to.y).abs() / window.height().max(1.0); - if on_horizontal && !(on_vertical && beyond_x > beyond_y) { - let (a, b) = spread(to.x, window.left(), window.right()); - [pos2(a, to.y), pos2(b, to.y)] - } else { - let (a, b) = spread(to.y, window.top(), window.bottom()); - [pos2(to.x, a), pos2(to.x, b)] - } -} - -/// The point of `r`'s boundary nearest `p` (`p` inside `r` is pushed to the nearer vertical edge). -fn nearest_on(r: Rect, p: Pos2) -> Pos2 { - let x = p.x.clamp(r.left(), r.right()); - let y = p.y.clamp(r.top(), r.bottom()); - if r.left() < x && x < r.right() && r.top() < y && y < r.bottom() { - pos2(if (p.x - r.left()).abs() <= (p.x - r.right()).abs() { r.left() } else { r.right() }, y) - } else { - pos2(x, y) - } -} - -/// A pop-up window's size on screen, in points, whatever the zoom (the readers keep theirs the -/// same as the page zooms), kept within these bounds whatever size the file gives it. -const MIN_WIDTH: f32 = 200.0; -const MAX_WIDTH: f32 = 800.0; -const MIN_HEIGHT: f32 = 120.0; -const MAX_HEIGHT: f32 = 800.0; -/// The side of the grip at a window's lower right corner that resizes it. -const RESIZE_GRIP: f32 = 10.0; -/// How far a reply's panel sits in from the panel around it. -const NEST: i8 = 6; /// Past this depth a reply's panel stops nesting and sits under the one before it. const MAX_NESTING: usize = 8; @@ -141,7 +54,7 @@ fn thread<'a>(top: (usize, usize), replies: &[&'a Annotation]) -> Vec<(&'a Annot /// A thread as nested panels: each reply ([`thread`] order) and the positions of the replies /// drawn inside its panel; then the positions of the replies to the comment itself. Nesting stops -/// at [`MAX_NESTING`], so drawing it recurses no deeper than that. +/// at [`MAX_NESTING`], so reading it recurses no deeper than that. fn nest<'a>(order: &[(&'a Annotation, usize)]) -> (Vec<(&'a Annotation, Vec)>, Vec) { let mut nodes: Vec<(&Annotation, Vec)> = Vec::with_capacity(order.len()); let mut roots = Vec::new(); @@ -160,398 +73,200 @@ fn nest<'a>(order: &[(&'a Annotation, usize)]) -> (Vec<(&'a Annotation, Vec Palette { - // `color` mixed into white, `f` of the way. - let mix = |f: f32| { - let c = |v: u8| (255.0 + (f32::from(v) - 255.0) * f).round().clamp(0.0, 255.0) as u8; - Color32::from_rgb(c(color.r()), c(color.g()), c(color.b())) - }; - let title = mix(0.8); - let light = |c: Color32| 0.299 * f32::from(c.r()) + 0.587 * f32::from(c.g()) + 0.114 * f32::from(c.b()) > 150.0; - Palette { - edge: color, - title, - title_ink: if light(title) { Color32::from_gray(20) } else { Color32::WHITE }, - body: mix(0.35), - panel_edge: mix(0.7), - ink: Color32::from_gray(20), - faint: Color32::from_gray(80), - } -} - -/// What a pop-up window's parts share as they draw. -struct Parts<'v> { - allowed: bool, - author: &'v str, - pal: Palette, - cv: &'v mut super::state::CommentView, - edits: &'v mut Vec, -} - -/// One comment's or reply's text in its box, typed in place (saved when the box loses focus); -/// read-only when comments can't be changed or it is locked. -fn text_box(ui: &mut egui::Ui, parts: &mut Parts<'_>, a: &Annotation, name: &str) { - let key = (a.page, a.index); - if parts.allowed && !a.locked { - let typed = parts.cv.popup_text.as_ref().filter(|(p, i, _)| (*p, *i) == key).map(|(_, _, s)| s.clone()); - let mut text = typed.unwrap_or_else(|| a.contents.clone().unwrap_or_default()); - let field = ui - .add( - egui::TextEdit::multiline(&mut text) - .desired_rows(1) - .desired_width(f32::INFINITY) - .font(theme::regular(12.5)) - .text_color(parts.pal.ink) - .background_color(Color32::WHITE) - .margin(egui::Margin::symmetric(4, 2)) - .id_salt(("popup-text", a.page, a.index)), - ) - .accessible_name(name); - if field.changed() { - parts.cv.popup_text = Some((a.page, a.index, text.clone())); - } - if field.lost_focus() - && let Some((_, _, s)) = parts.cv.popup_text.take_if(|(p, i, _)| (*p, *i) == key) - && s.trim_end() != a.contents.as_deref().unwrap_or_default() - { - parts.edits.push(Edit::SetAnnotationContents { page: a.page, index: a.index, text: s.trim_end().to_string() }); - } - } else { - egui::Frame::NONE.fill(Color32::WHITE).inner_margin(egui::Margin::symmetric(4, 2)).show(ui, |ui| { - ui.set_width(ui.available_width()); - ui.label(egui::RichText::new(a.contents.as_deref().unwrap_or_default()).font(theme::regular(12.5)).color(parts.pal.ink)); - }); - } -} - -/// The row under a comment's or reply's text: a Reply button at its end (the start is kept for -/// more of a reply's controls), and the box to type that reply in once it is pressed (Post, or -/// Ctrl/⌘+Enter, posts it; Enter starts a new line, as in the readers' pop-ups). -fn footer(ui: &mut egui::Ui, parts: &mut Parts<'_>, a: &Annotation) { - let key = (a.page, a.index); - // Small buttons, as the readers' footers have. - ui.spacing_mut().button_padding = egui::vec2(6.0, 1.0); - let mut opened = false; - if parts.allowed { - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let label = egui::RichText::new(tl!("Reply")).font(theme::regular(11.0)).color(parts.pal.ink); - let button = egui::Button::new(label) - .fill(Color32::WHITE.gamma_multiply(0.6)) - .stroke(egui::Stroke::new(1.0, parts.pal.panel_edge)) - .min_size(egui::vec2(0.0, 16.0)); - if ui.add(button).clicked() { - parts.cv.popup_reply = Some((a.page, a.index, String::new())); - opened = true; - } - }); - }); - } - let Some(mut reply) = parts.cv.popup_reply.as_ref().filter(|(p, i, _)| (*p, *i) == key).map(|(_, _, s)| s.clone()) else { return }; - let field = ui.add( - egui::TextEdit::multiline(&mut reply) - .desired_rows(1) - .desired_width(f32::INFINITY) - .hint_text(tl!("Add a reply")) - .font(theme::regular(12.5)) - .text_color(parts.pal.ink) - .background_color(Color32::WHITE) - .margin(egui::Margin::symmetric(4, 2)) - .id_salt(("popup-reply", a.page, a.index)), - ); - if opened { - field.request_focus(); - } - if field.changed() { - parts.cv.popup_reply = Some((a.page, a.index, reply.clone())); - } - let enter = super::submit_key(ui, &field, false); - let ok = !reply.trim().is_empty(); - let (post, cancel) = ui - .horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let small = |s: &str| egui::RichText::new(s).font(theme::regular(11.0)); - let post = ui.add_enabled(ok, egui::Button::new(small(tl!("Post"))).min_size(egui::vec2(0.0, 16.0))).clicked(); - let cancel = ui.add(egui::Button::new(small(tl!("Cancel"))).min_size(egui::vec2(0.0, 16.0))).clicked(); - (post, cancel) - }) - .inner - }) - .inner; - if (post || enter) && ok { - parts.cv.popup_reply = None; - parts.edits.push(Edit::ReplyToAnnotation { page: a.page, index: a.index, text: reply.trim().to_string(), author: parts.author.to_string() }); - } else if cancel { - parts.cv.popup_reply = None; - } -} - -/// A reply's panel: who wrote it and when, its text and footer, and the panels of its own -/// replies inside it. -fn reply_panel(ui: &mut egui::Ui, parts: &mut Parts<'_>, nodes: &[(&Annotation, Vec)], at: usize) { +/// The replies of `nodes` below `at`, each with its depth, in the order the window reads them. +fn flatten<'a>(nodes: &[(&'a Annotation, Vec)], at: usize, depth: usize, out: &mut Vec<(&'a Annotation, usize)>) { let Some((r, kids)) = nodes.get(at) else { return }; - let pal = parts.pal; - egui::Frame::NONE.stroke(egui::Stroke::new(1.0, pal.panel_edge)).corner_radius(CornerRadius::same(3)).inner_margin(egui::Margin::same(4)).show( - ui, - |ui| { - ui.set_width(ui.available_width()); - ui.spacing_mut().item_spacing.y = 3.0; - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if let Some(m) = &r.modified { - ui.label(egui::RichText::new(m).font(theme::regular(10.5)).color(pal.faint)); - } - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - let who = r.author.as_deref().unwrap_or("?"); - ui.add(egui::Label::new(egui::RichText::new(who).font(theme::semibold(11.5)).color(pal.ink)).truncate()); - }); - }); - }); - text_box(ui, parts, r, r.author.as_deref().unwrap_or("?")); - footer(ui, parts, r); - for kid in kids { - egui::Frame::NONE.inner_margin(egui::Margin { left: NEST, ..Default::default() }).show(ui, |ui| reply_panel(ui, parts, nodes, *kid)); - } - }, - ); + out.push((r, depth)); + for kid in kids { + flatten(nodes, *kid, depth + 1, out); + } } -/// The open pop-up windows of the comments on screen, laid out as the readers' are: a title bar -/// with the comment's kind and author, its date and ×; the comment's text, editable in place; its -/// replies as panels, each inside the one it answers; and a Reply button under each, which opens -/// a box to answer it. The window keeps its size on screen as the page zooms, and its text and -/// replies scroll inside it. The title bar drags the window and its lower right corner resizes -/// it, both saved with the comment; × closes it. Returns the edits to apply (one, or a batch when -/// a click both saves typed text and closes). Hidden comments show none. -pub(crate) fn popups(ctx: &egui::Context, view: &mut DocView, info: &DocInfo, prefs: &CommentPrefs, hidden: bool, allowed: bool) -> Option { - let pointer = ctx.input(|i| i.pointer.hover_pos()); + +/// One message of a window, owned until the window is built. +struct Owned { + key: (usize, usize), + id: u64, + title: String, + author: String, + text: String, + modified: Option, + depth: usize, + editable: bool, +} + +fn modified_seconds(a: &Annotation) -> Option { + a.modified.as_deref().and_then(super::bridge::pdf_date_seconds) +} + +/// The window's messages: the comment, then its text replies in thread order. Replies are the comment's text +/// replies only, filed by `/IRT` reference as in the Comments panel: a review status or a checkmark (`/State`) +/// is a reply too but not one to read here, and a member of the comment's group (`/RT /Group`) is part of the +/// comment. Replace Text as `main` writes it keeps the replacement on the caret grouped under an empty +/// strikeout: the window shows and edits the caret's text, and locking the comment locks that text too. +/// Returns the messages and the annotation holding the comment's text. +fn messages( + info: &DocInfo, + tops: &std::collections::HashMap<(usize, usize), (usize, usize)>, + a: &Annotation, + allowed: bool, +) -> (Vec, (usize, usize)) { + let key = (a.page, a.index); + let replies: Vec<&Annotation> = info + .annotations + .iter() + .filter(|r| r.state.is_none() && !r.grouped && r.parent.is_some_and(|parent| tops.get(&(r.page, r.index)).copied().unwrap_or(parent) == key)) + .collect(); + let mut holder = info + .annotations + .iter() + .find(|r| r.grouped && r.parent == Some(key) && a.contents.as_deref().unwrap_or("").is_empty() && r.contents.as_deref().is_some_and(|c| !c.is_empty())) + .cloned() + .unwrap_or_else(|| a.clone()); + holder.locked |= a.locked; + let kind = tl!(crate::comments_panel::kind_label(a)); + let title = match a.author.as_deref() { + Some(who) => format!("{kind} – {who}"), + None => kind.to_string(), + }; + let mut out = vec![Owned { + key: (holder.page, holder.index), + // PLAN: assumed `bridge::id_of(page: usize, index: usize) -> AnnotationId` (pdf-comments-w7) + id: super::bridge::id_of(holder.page, holder.index).0, + title, + author: a.author.clone().unwrap_or_default(), + text: holder.contents.clone().unwrap_or_default(), + modified: modified_seconds(a), + depth: 0, + editable: allowed && !holder.locked, + }]; + let (nodes, roots) = nest(&thread(key, &replies)); + let mut ordered = Vec::with_capacity(nodes.len()); + for root in roots { + flatten(&nodes, root, 1, &mut ordered); + } + for (r, depth) in ordered { + let who = r.author.clone().unwrap_or_else(|| "?".to_string()); + out.push(Owned { + key: (r.page, r.index), + id: super::bridge::id_of(r.page, r.index).0, + title: who.clone(), + author: who, + text: r.contents.clone().unwrap_or_default(), + modified: modified_seconds(r), + depth, + editable: false, + }); + } + (out, (holder.page, holder.index)) +} + +/// The open pop-up windows of the comments on screen: each a framework note window with its comment's +/// text, editable in place, and its replies. The window keeps its size on screen as the page zooms; its +/// place and size are saved with the comment when a move or resize ends, and × closes it. Returns the edits +/// to apply (one, or a batch when a gesture both saves typed text and closes). Hidden comments show none. +/// `hovered` is the comment the page body reports under the pointer; its connector shows while it is. +// PLAN: pdf-canvas-w8 passes `hovered` from the page body's `PageParts` output. +pub(crate) fn note_popups( + ui: &mut egui::Ui, + view: &mut DocView, + info: &DocInfo, + prefs: &CommentPrefs, + hidden: bool, + allowed: bool, + hovered: Option<(usize, usize)>, +) -> Option { let mut edits: Vec = Vec::new(); - let mut rects = Vec::new(); - let mut hovered = None; // The comment each reply files under, as the Comments panel threads them (by reference). let tops = pdfcraft_render::thread_tops(&info.annotations); - let xforms: Vec<(usize, PageXform)> = view.page_xforms(); - for (page, xf) in xforms { - let shown: Vec = - info.annotations.iter().filter(|a| !hidden && a.page == page && has_popup(a) && a.popup.is_some_and(|p| p.open)).cloned().collect(); + let now = (craft::platform::clock::unix_ms() / 1000.0) as i64; + let limits = NOTE_POPUP_LIMITS; + let max = limits.max.unwrap_or(egui::Vec2::splat(f32::MAX)); + let clamp = |s: egui::Vec2| s.max(limits.min).min(max); + for (page, xf) in view.page_xforms() { + let pcx = PageCx { page, xf: &xf, info, prefs, allowed, hidden }; + let shown: Vec<&Annotation> = + info.annotations.iter().filter(|a| !hidden && a.page == page && has_popup(a) && a.popup.is_some_and(|p| p.open)).collect(); for a in shown { let Some(p) = a.popup else { continue }; - let key = (page, a.index); let placed = xf.user_rect(info, page, p.rect); - // Its place follows the page; its size is the pop-up's `/Rect` in points on screen, - // or the size its corner is being dragged to. - // A `/Rect` with numbers that aren't finite gives the least size. - let side = |a: f32, b: f32| Some((b - a).abs()).filter(|v| v.is_finite()).unwrap_or(0.0); - let saved = egui::vec2(side(p.rect[0], p.rect[2]), side(p.rect[1], p.rect[3])); - let clamp = |s: egui::Vec2| egui::vec2(s.x.clamp(MIN_WIDTH, MAX_WIDTH), s.y.clamp(MIN_HEIGHT, MAX_HEIGHT)); - let resizing = view.comments.popup_resize.filter(|(rp, ri, _)| (*rp, *ri) == key).map(|(_, _, size)| size); - let size = clamp(resizing.unwrap_or(saved)); - let dragging = view.comments.popup_drag.filter(|(dp, di, _)| (*dp, *di) == key).map(|(_, _, at)| at); - let pos = dragging.unwrap_or(placed.left_top()); - let id = egui::Id::unique(("comment-popup", view.id.0, page, a.index)); - let color = a - .color - .map_or(Color32::from_rgb(0xFF, 0xD6, 0x5C), |c| Color32::from_rgb((c[0] * 255.0) as u8, (c[1] * 255.0) as u8, (c[2] * 255.0) as u8)); - let pal = palette(color); - // A screen rectangle on this page in user space, to save as the pop-up's `/Rect`. Only - // converts: the pointer, the keys (none) and the redaction look are unused. - let to_user = |r: Rect| { - let cx = PageCx { - page, - xf: &xf, - ptr: &PagePointer::default(), - info, - tool: QuickTool::Select, - prefs: &CommentPrefs::default(), - allowed, - hidden, - redact_mark: ([0.0; 3], 1.0), - keys: PageKeys::new(true), + // Its size is the pop-up's `/Rect` in points on screen whatever the zoom; a `/Rect` with numbers + // that aren't finite gives the least size. + let side = |lo: f32, hi: f32| Some((hi - lo).abs()).filter(|v| v.is_finite()).unwrap_or(0.0); + let saved = clamp(egui::vec2(side(p.rect[0], p.rect[2]), side(p.rect[1], p.rect[3]))); + let rect = Rect::from_min_size(placed.left_top(), saved); + let (owned, holder) = messages(info, &tops, a, allowed); + let msgs: Vec> = owned + .iter() + .map(|m| NotePopupMessage { + id: m.id, + title: &m.title, + author: &m.author, + text: &m.text, + modified: m.modified, + depth: m.depth, + editable: m.editable, + }) + .collect(); + let mark = pcx.screen_rects(a).next(); + // PLAN: `Annotation::color` is f32 components in 0..=1; the window takes 8-bit. + let color = a.color.map(|c| c.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() as u8)); + let selected = view.comments.is_selected((page, a.index)); + // PLAN: A-2 `popup_drafts: HashMap<(usize, usize), NoteDrafts>`, one per open window (lead ruling, review 1). + let drafts: &mut NoteDrafts = view.comments.popup_drafts.entry((page, a.index)).or_default(); + let mut window = NotePopup::new(super::bridge::id_of(page, a.index).0, owned.first().map_or("", |m| m.title.as_str()), rect, &msgs, drafts) + .color(color) + .selected(selected) + .now(now) + .allowed(allowed); + if let Some(mark) = mark { + window = window.anchor(mark, hovered == Some((page, a.index))); + } + let out = window.show(ui); + if out.closed { + edits.push(Edit::SetAnnotationPopup { page, index: a.index, rect: None, open: Some(false) }); + } + if let Some(text) = out.body { + let text = text.trim_end().to_string(); + let current = info.annotations.iter().find(|r| (r.page, r.index) == holder).and_then(|r| r.contents.as_deref()).unwrap_or_default(); + if text != current { + edits.push(Edit::SetAnnotationContents { page: holder.0, index: holder.1, text }); + } + } + if let Some((id, text)) = out.reply + && let Some(m) = owned.iter().find(|m| m.id == id) + && !text.trim().is_empty() + { + edits.push(Edit::ReplyToAnnotation { page: m.key.0, index: m.key.1, text: text.trim().to_string(), author: prefs.author.clone() }); + } + if let Some((at, kind)) = out.placed + && allowed + { + let resized = match kind { + PlacementKind::Size(_) => true, + PlacementKind::Keyboard => (at.size() - rect.size()).length() >= 0.5, + _ => false, }; - cx.rect_to_user(r) - }; - let area = egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(pos).show(ctx, |ui| { - let frame = egui::Frame::popup(ui.style()).inner_margin(egui::Margin::ZERO).corner_radius(CornerRadius::same(3)).fill(pal.body); - let window = frame.stroke(egui::Stroke::new(1.0, pal.edge)).show(ui, |ui| { - ui.set_width(size.x); - // The whole size, however short its thread. - ui.set_min_height(size.y); - ui.spacing_mut().item_spacing.y = 3.0; - // Title bar: the comment's kind and author, its date and ×, on one line; it - // drags the window. - let bar = egui::Frame::NONE.fill(pal.title).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| { - ui.set_width(size.x - 12.0); - ui.horizontal(|ui| { - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - // Closing changes the comment's /Open, which needs comment permission. - if ui.add_enabled_ui(allowed, |ui| crate::icons::button(ui, "x", 14.0, false, tl!("Close"))).inner.clicked() { - edits.push(Edit::SetAnnotationPopup { page, index: a.index, rect: None, open: Some(false) }); - } - if let Some(m) = &a.modified { - ui.label(egui::RichText::new(m).font(theme::regular(10.5)).color(pal.title_ink)); - } - // The kind and author take the rest of the line, cut short to fit. - ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { - let kind = tl!(crate::comments_panel::kind_label(&a)); - let title = match a.author.as_deref() { - Some(who) => format!("{kind} – {who}"), - None => kind.to_string(), - }; - ui.add(egui::Label::new(egui::RichText::new(title).font(theme::semibold(12.0)).color(pal.title_ink)).truncate()); - }); - }) - }); - }); - // The bar drags the window, except where the × is: a region registered after - // the button would take its clicks. - let bar_rect = bar.response.rect; - let grip = ui.interact( - Rect::from_min_max(bar_rect.min, pos2(bar_rect.right() - 24.0, bar_rect.bottom())), - id.with("grip"), - egui::Sense::drag(), - ); - if grip.hovered() || grip.dragged() { - ui.ctx().set_cursor_icon(egui::CursorIcon::Grab); - } - if grip.drag_started_by(egui::PointerButton::Primary) { - view.comments.popup_drag = Some((page, a.index, pos)); - } - if grip.dragged() - && let Some((_, _, at)) = view.comments.popup_drag.as_mut() - { - *at += grip.drag_delta(); - } - if grip.drag_stopped() - && let Some((_, _, at)) = view.comments.popup_drag.take() - && allowed - && at.distance(placed.left_top()) >= 2.0 - { - // The same size on the page, at the new place. Only converts the - // rectangle to user space: the pointer and the redaction look are unused. - let rect = to_user(Rect::from_min_size(at, placed.size())); - edits.push(Edit::SetAnnotationPopup { page, index: a.index, rect: Some(rect), open: None }); - } - // Replies, as the thread reads: text replies only, filed under this - // comment by `/IRT` reference as in the Comments panel, each under the - // one it answers. A review status or a checkmark (`/State`) is a reply too, - // but not one to read here, and a member of the comment's group (`/RT - // /Group`, ISO 32000-2 §12.5.6.2) is part of the comment, not a reply. - let replies: Vec<&Annotation> = info - .annotations - .iter() - .filter(|r| { - r.state.is_none() - && !r.grouped - && r.parent.is_some_and(|parent| tops.get(&(r.page, r.index)).copied().unwrap_or(parent) == key) - }) - .collect(); - // The comment's text. Replace Text as `main` writes it (#5688) keeps the - // replacement on the caret grouped under an empty strikeout: the window shows - // and edits the caret's text, the proposal's. Locking the comment locks that - // text too. - let mut holder = info - .annotations - .iter() - .find(|r| { - r.grouped - && r.parent == Some(key) - && a.contents.as_deref().unwrap_or("").is_empty() - && r.contents.as_deref().is_some_and(|c| !c.is_empty()) - }) - .cloned() - .unwrap_or_else(|| a.clone()); - holder.locked |= a.locked; - let order = thread(key, &replies); - let (nodes, roots) = nest(&order); - let mut parts = Parts { allowed, author: &prefs.author, pal, cv: &mut view.comments, edits: &mut edits }; - // The body keeps the window's height: the text and replies scroll in what the - // title bar leaves, with a bar that shows whenever there is more (egui's show - // only near the pointer), in the ink's colour. - egui::Frame::NONE.inner_margin(egui::Margin::same(4)).show(ui, |ui| { - ui.set_width(size.x - 8.0); - ui.spacing_mut().scroll = egui::style::ScrollStyle { - dormant_handle_opacity: 0.4, - dormant_background_opacity: 0.1, - foreground_color: true, - ..egui::style::ScrollStyle::solid() - }; - ui.visuals_mut().override_text_color = Some(pal.ink); - let body_height = (size.y - bar_rect.height() - 8.0).max(24.0); - let scroll = - egui::ScrollArea::vertical().id_salt(("popup-body", page, a.index)).max_height(body_height).auto_shrink([false, false]); - scroll.show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 3.0; - text_box(ui, &mut parts, &holder, tl!("Add a comment")); - footer(ui, &mut parts, &a); - for root in &roots { - reply_panel(ui, &mut parts, &nodes, *root); - } - }); - }); - }); - // The lower right corner resizes the window; its new size is saved with the - // comment, its upper left corner where it was, when the drag ends. - let corner = window.response.rect.right_bottom(); - let grip = - ui.interact(Rect::from_min_max(corner - egui::vec2(RESIZE_GRIP, RESIZE_GRIP), corner), id.with("resize"), egui::Sense::drag()); - if grip.hovered() || grip.dragged() { - ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeNwSe); - } - // Two short diagonal strokes mark the grip. - for inset in [3.0, 7.0] { - let stroke = egui::Stroke::new(1.0, pal.faint); - ui.painter().line_segment([corner - egui::vec2(3.0, inset), corner - egui::vec2(inset, 3.0)], stroke); - } - if grip.drag_started_by(egui::PointerButton::Primary) { - view.comments.popup_resize = Some((page, a.index, size)); - } - if grip.dragged() - && let Some((_, _, s)) = view.comments.popup_resize.as_mut() - { - *s += grip.drag_delta(); - } - if grip.drag_stopped() - && let Some((_, _, s)) = view.comments.popup_resize.take() - && allowed - { - let s = clamp(s); - // A press on the grip that ends where it began changes nothing. - // The window's size in points is the `/Rect`'s, its upper left corner kept - // where it is on screen: the rectangle of that size on the page there. A page - // turned a quarter (its `/Rotate` and the view's) shows the `/Rect`'s width - // down the screen. + if resized { + // The window's size in points is the `/Rect`'s, its upper left corner kept where it is on + // screen. A page turned a quarter shows the `/Rect`'s width down the screen. A press that + // ends where it began changes nothing. + let s = clamp(at.size()); let zoom = xf.zoom(); - if (s - clamp(saved)).length() >= 2.0 && zoom.is_finite() && zoom > 0.0 { + if (s - saved).length() >= 2.0 && zoom.is_finite() && zoom > 0.0 { let turn = info.pages.get(page).map_or(0, |pg| u32::from(pg.rotation)) + u32::from(xf.rot); let on_page = if turn % 180 == 90 { egui::vec2(s.y, s.x) } else { s } * zoom; - let rect = to_user(Rect::from_min_size(placed.left_top(), on_page)); - edits.push(Edit::SetAnnotationPopup { page, index: a.index, rect: Some(rect), open: None }); + let user = super::bridge::screen_to_user_rect(&pcx, Rect::from_min_size(placed.left_top(), on_page)); + edits.push(Edit::SetAnnotationPopup { page, index: a.index, rect: Some(user), open: None }); } + } else if at.left_top().distance(rect.left_top()) >= 2.0 { + // The same size on the page, at the new place. + let user = super::bridge::screen_to_user_rect(&pcx, Rect::from_min_size(at.left_top(), placed.size())); + edits.push(Edit::SetAnnotationPopup { page, index: a.index, rect: Some(user), open: None }); } - }); - let shown_at = area.response.rect; - if pointer.is_some_and(|p| shown_at.contains(p)) { - hovered = Some(key); } - rects.push((key, shown_at)); } } - view.comments.popup_rects = rects; - view.comments.popup_hovered = hovered; match edits.len() { 0 => None, 1 => edits.pop(),