diff --git a/crates/ui-egui/src/tools/content_ui.rs b/crates/ui-egui/src/tools/content_ui.rs index 884b32ec98..f00cf0da04 100644 --- a/crates/ui-egui/src/tools/content_ui.rs +++ b/crates/ui-egui/src/tools/content_ui.rs @@ -3,18 +3,38 @@ //! (images keep their proportions), double-click text to retype it, format it from the panel, //! Delete to remove it. Each change is one undoable engine edit. -#[cfg(not(target_arch = "wasm32"))] -use crate::file_filter::AddFilterAnyCase as _; -use egui::{Color32, CornerRadius, Pos2, Rect, Stroke}; -use pdfcraft_engine::{Added, AddedContent, AddedText, Edit}; +use std::ops::Range; +use std::sync::Arc; + +use craft::behavior::geometry::{BoxAllow, BoxHandles, BoxRules, BoxState, ScaleRule}; +use craft::behavior::hit::HitShape; +use craft::behavior::kurbo::{Point, Rect as DocRect}; +use craft::behavior::press::PressPhase; +use craft::behavior::{CancelReason, Cursor, CursorIcon, IconId}; +use craft::draw::ui::TransformBox; +use craft::pages::ui::{PageBody, PlacedPage}; +use craft::platform::clipboard::{BITMAP, ClipboardImage, TEXT}; +use craft::text::ui::editor::{CaretLine, EditKind, EditorEnd, HostLine, HostRun, TextEditor, TextEditorHost, TextSelection}; +use craft::theme::Tone; +use craft::ui::buttons::IconButton; +use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer}; +use craft::ui::canvas_controls::{HoverOutline, HoverShape, TaskBar}; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::{Shade, Text}; +use craft::ui::form::Field; +use craft::ui::layout_components::Row; +use craft::ui::primitives::textures::{CachedTexture, Revision, TextureStore, TextureStoreOptions}; +use craft::ui::primitives::{ContentPainterCx, Draw}; +use craft::ui::runtime::env::UnitKind; +use craft::ui::sections::Section; +use craft::ui::text::NumberField; +use egui::{Color32, CornerRadius, Pos2, Rect}; +use pdfcraft_engine::{Added, AddedContent, AddedText, Document, Edit}; use pdfcraft_render::DocInfo; -use crate::canvas::{DocView, PageToolContext, PageXform}; -use crate::page_cursor::Layer; -use crate::page_keys::PageKeys; -use crate::page_router::{Hit, Owner, PagePress}; -use crate::theme::Tokens; -use crate::widgets; +use crate::canvas::DocView; +use crate::canvas::page_parts::{Owner, PageLayer, PagePart, PagePress}; +use crate::edit_text_ui::{Typed, TypingHistory}; /// The colour of the warning under text the standard fonts can't draw. pub(crate) const UNDRAWABLE: Color32 = Color32::from_rgb(0xD7, 0x37, 0x3F); @@ -60,10 +80,8 @@ pub(crate) fn undrawn_message(n: &pdfcraft_engine::TextNotice) -> String { crate::i18n::fmt(template, &[("c", &n.ch.to_string()), ("code", &format!("U+{:04X}", u32::from(n.ch)))]) } -const SELECT_BLUE: Color32 = Color32::from_rgb(0x14, 0x73, 0xE6); - /// The text being typed or retyped in place. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug)] pub struct TextDraft { pub page: usize, /// `None` for new text; the item index for retyping. @@ -75,30 +93,123 @@ pub struct TextDraft { /// its `aligns` follow `text` as it is typed. pub style: AddedText, pub focus: bool, - /// The selected bytes of `text` (empty: the caret), for aligning the lines it touches. - pub selection: Option>, - /// The text the box's own Undo history starts from ([`crate::edit_text_ui::forget_typing_before`]). - pub typing_from: Option, + /// The selection in chars with its caret end, the value the box's `TextEditor` binds; it also + /// says which lines an alignment touches. `None` until the editor reports one. + pub selection: Option, + /// The box's own Undo history, from the text the box opened with. + pub(crate) history: TypingHistory, +} + +/// Two drafts are equal when everything the user sees and commits is: the history is how the box got +/// there, not what it holds. +impl PartialEq for TextDraft { + fn eq(&self, other: &Self) -> bool { + self.page == other.page + && self.index == other.index + && self.rect == other.rect + && self.text == other.text + && self.style == other.style + && self.focus == other.focus + && self.selection == other.selection + } } impl TextDraft { - /// Take the shared text box for this box ([`crate::edit_text_ui::forget_typing_before`]): its - /// own history, or none once the page has its text. - pub(crate) fn claim_typing(&mut self, ctx: &egui::Context, doc: pdfcraft_engine::DocId) { - crate::edit_text_ui::forget_typing_before(ctx, input_id(), doc, &mut self.typing_from, &self.style.text); + /// A box on `page` for the item `index` (`None`: new text) over `rect` in display space, with + /// `text` in `style`: nothing selected, no focus requested, and an Undo history that starts at `text`. + pub fn new(page: usize, index: Option, rect: [f64; 4], text: String, style: AddedText) -> TextDraft { + let history = TypingHistory::new(Typed::of(text.clone(), None, style.aligns.clone())); + TextDraft { page, index, rect, text, style, focus: false, selection: None, history } } /// Typing the page doesn't have yet: Undo takes it back in the box before touching the document. pub(crate) fn has_unapplied_typing(&self) -> bool { self.text != self.style.text } + + /// The box as the history records it. + fn typed(&self) -> Typed { + Typed::of(self.text.clone(), self.selection, self.style.aligns.clone()) + } } +/// Where a page is on screen as the parts last registered it: what a press, which arrives in screen +/// points, needs to say where it was in the page's display space (origin bottom left, y up). #[derive(Clone, Copy, Debug, PartialEq)] -enum Grab { - Move, - /// Which corner: (left, top) in screen terms. - Corner(bool, bool), +pub(crate) struct PageFrame { + page: usize, + /// The page's top left on screen. + origin: Pos2, + /// Screen points per page point. + scale: f64, + /// The page's height in page points. + height: f64, +} + +impl PageFrame { + fn of(placed: &PlacedPage, info: &DocInfo) -> Option { + let height = f64::from(info.pages.get(placed.page)?.height); + Some(PageFrame { page: placed.page, origin: placed.rect.min, scale: placed.scale, height }) + } + + fn screen(&self, display: [f64; 2]) -> Pos2 { + Pos2::new( + self.origin.x + (display[0] * self.scale) as f32, + self.origin.y + ((self.height - display[1]) * self.scale) as f32, + ) + } + + fn screen_rect(&self, r: [f64; 4]) -> Rect { + Rect::from_two_pos(self.screen([r[0], r[1]]), self.screen([r[2], r[3]])) + } + + fn display(&self, p: Pos2) -> [f64; 2] { + let k = if self.scale > 0.0 { self.scale } else { 1.0 }; + [f64::from(p.x - self.origin.x) / k, self.height - f64::from(p.y - self.origin.y) / k] + } + + /// `r` moved by what the pointer travelled from `from` to `to`. + fn moved(&self, r: [f64; 4], from: Pos2, to: Pos2) -> [f64; 4] { + let (a, b) = (self.display(from), self.display(to)); + let (dx, dy) = (b[0] - a[0], b[1] - a[1]); + [r[0] + dx, r[1] + dy, r[2] + dx, r[3] + dy] + } +} + +/// An added item shown at a box other than the applied one while the pointer drags it, between the +/// press and the release. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Preview { + page: usize, + index: usize, + /// The box in display space. + rect: [f64; 4], + /// The item is resized by a corner, not moved. + resizing: bool, +} + +/// The open box as the page body paints it: the white paper and the laid-out text. The editor draws +/// its caret and selection over it. +#[derive(Clone, Debug)] +struct DraftPaint { + /// The editor's box. + paper: Rect, + /// The page's own copy of the text, to be covered until its replacement is rendered. + cover: Option, + /// Whether the paper is filled: not once the page without the item is shown behind it. + fill: bool, + galley: Arc, + origin: Pos2, +} + +impl PartialEq for DraftPaint { + fn eq(&self, other: &Self) -> bool { + self.paper == other.paper + && self.cover == other.cover + && self.fill == other.fill + && self.origin == other.origin + && Arc::ptr_eq(&self.galley, &other.galley) + } } #[derive(Clone, Debug, Default, PartialEq)] @@ -108,25 +219,34 @@ pub struct ContentView { pub draft: Option, /// Select the item an add creates (the page's item count before it). pub select_added: Option<(usize, usize)>, - grab: Option<(usize, Grab, Pos2)>, - /// Where the press nobody holds began, on which page: Add text's click starts its new box there. - pressed_at: Option<(usize, Pos2)>, - /// A button is down on the pages this frame (for [`keys`], which runs after them). - held: bool, + /// A click on added text opens it for typing (Add text and Edit text); with the other tools a + /// double click does. The page body sets it from the tool. + pub(crate) edit_on_click: bool, + /// Done was pressed on the open box: the page body returns to Select ([`ContentView::take_done`]). + done: bool, + preview: Option, + drawn: Option, undrawable: UndrawableMemo, layout: Option<(AddedText, f32, f64, [f64; 4])>, } impl ContentView { - /// Forget an in-progress pointer grab for content editing. - pub(crate) fn cancel_pointer_gesture(&mut self) { - self.grab = None; - self.pressed_at = None; + /// Whether Done ended the box since the last call; the page body goes back to Select then. + pub(crate) fn take_done(&mut self) -> bool { + std::mem::take(&mut self.done) } - /// An added item is being moved or resized on `page`. - pub(crate) fn moving_on(&self, page: usize) -> bool { - self.grab.is_some_and(|(p, ..)| p == page) + /// Paints the open box's paper and text, under the editor's caret: called by the page control's + /// content painter after the page, the document's own pixels being content. + pub(crate) fn paint_draft(&self, content: &ContentPainterCx<'_>) { + let Some(drawn) = &self.drawn else { return }; + if let Some(cover) = drawn.cover { + content.painter.rect_filled(cover, CornerRadius::ZERO, Color32::WHITE); + } + if drawn.fill { + content.painter.rect_filled(drawn.paper, CornerRadius::ZERO, Color32::WHITE); + } + content.painter.galley(drawn.origin, Arc::clone(&drawn.galley), Color32::BLACK); } pub(crate) fn finish_draft(&mut self, added: &[Added]) -> Option { @@ -155,11 +275,13 @@ impl ContentView { pub(crate) struct MoveBackground { key: Option<(u64, usize, usize)>, renderer: Option, - texture: Option, + /// The two rasters live in this store, which keeps what the painter shows from being evicted. + store: Option>, + texture: Option, /// The item alone on a transparent page: the pixels that follow the pointer. The page's own /// raster has whatever the item covers in its box too, which must stay where it is (#4464). item_renderer: Option, - item: Option, + item: Option, tag: Option, /// The item's display-space box when the gesture started. from: Option<[f64; 4]>, @@ -182,12 +304,8 @@ impl MoveBackground { pub fn prepare(&mut self, ctx: &egui::Context, doc: &pdfcraft_engine::Document, cv: &ContentView, scale: f32) { let picture = |page, index| on_page(doc.added(), page).into_iter().any(|(i, a)| i == index && matches!(a.content, AddedContent::Image(_))); - let key = match (cv.grab, cv.selected) { - (Some((gp, Grab::Move, _)), Some((sp, si))) if gp == sp => Some((doc.edit_generation(), sp, si)), - // Text resized by a corner rewraps, so only a picture's pixels can follow the corner. - (Some((gp, Grab::Corner(..), _)), Some((sp, si))) if gp == sp && picture(sp, si) => Some((doc.edit_generation(), sp, si)), - _ => None, - }; + // Text resized by a corner rewraps, so only a picture's pixels can follow the corner. + let key = cv.preview.filter(|p| !p.resizing || picture(p.page, p.index)).map(|p| (doc.edit_generation(), p.page, p.index)); if !(key.is_none() && self.settling.is_some()) && self.key != key { *self = Self { key, ..Default::default() }; if let Some((_, page, index)) = key { @@ -221,22 +339,18 @@ impl MoveBackground { /// Takes in the rasters rendered at `tag`. `false` when either failed: the preview is then /// dropped whole, including rasters in from an earlier scale. fn receive(&mut self, ctx: &egui::Context, tag: u64) -> bool { + let store = self.store.get_or_insert_with(|| TextureStore::in_context(ctx, "added-content-move", TextureStoreOptions::pages())).clone(); let (Some(renderer), Some(item_renderer)) = (self.renderer.as_ref(), self.item_renderer.as_ref()) else { return false; }; let mut failed = false; - for (r, slot, name) in - [(renderer, &mut self.texture, "added-content-move-background"), (item_renderer, &mut self.item, "added-content-move-item")] - { + for (r, slot, raster) in [(renderer, &mut self.texture, Raster::Page), (item_renderer, &mut self.item, Raster::Item)] { let Some(out) = r.try_recv() else { continue }; if out.error.is_some() { failed = true; } else if out.request.tag == tag { - *slot = Some(ctx.load_texture( - name, - crate::canvas::texture_image([out.width as usize, out.height as usize], out.rgba), - egui::TextureOptions::LINEAR, - )); + let image = crate::canvas::texture_image([out.width as usize, out.height as usize], out.rgba); + *slot = Some(store.put(ctx, raster, Revision::new(tag), image)); } } if failed { @@ -268,331 +382,250 @@ impl MoveBackground { } /// The page without the moving item, then the item's own pixels (from its raster alone, so - /// nothing it covered comes along) at the dragged (to the pages' `pointer`) or applied - /// position. - pub fn paint(&self, painter: &egui::Painter, xf: &PageXform, page: usize, info: &DocInfo, cv: &ContentView, pointer: Option) { - let (Some((_, kp, _)), Some(background), Some(item), Some(from)) = (self.key, &self.texture, &self.item, self.from) else { return }; - if kp != page { + /// nothing it covered comes along) at the dragged (`cv`'s preview) or applied position. `draw` + /// puts the rasters up; `content` is the page control's painter, which the shared draft paint + /// and the pixels of the document go through. + pub fn paint(&self, draw: &Draw<'_>, content: &ContentPainterCx<'_>, placed: &PlacedPage, info: &DocInfo, cv: &ContentView) { + let (Some((_, kp, ki)), Some(background), Some(item), Some(from)) = (self.key, self.texture.as_ref(), self.item.as_ref(), self.from) else { return; - } - let r = screen_rect(xf, info, page, from); - let base = self.settling.map_or(r, |s| screen_rect(xf, info, page, s)); - let to = if let Some((_, grab, start)) = cv.grab { - let Some(p) = pointer else { return }; - dragged(base, grab, p - start, self.picture) - } else if self.settling.is_some() { + }; + let Some(frame) = PageFrame::of(placed, info).filter(|f| f.page == kp) else { return }; + let r = frame.screen_rect(from); + let to = if let Some(p) = cv.preview.filter(|p| (p.page, p.index) == (kp, ki)) { + frame.screen_rect(p.rect) + } else if let Some(applied) = self.settling { + let base = frame.screen_rect(applied); // A moved text box keeps its top edge (its height follows its lines). if self.picture { base } else { r.translate(base.left_top() - r.left_top()) } } else { return; }; - let painter = painter.with_clip_rect(painter.clip_rect().intersect(xf.rect)); - xf.paint_image(&painter, background.id(), 0.0, 0.0, 1.0, 1.0); + // Painting marks both rasters as seen, so the store keeps them for the whole gesture. + if let Some(store) = &self.store { + let ctx = content.painter.ctx(); + let revision = Revision::new(self.tag.unwrap_or_default()); + for raster in [Raster::Page, Raster::Item] { + let _ = store.state(ctx, &raster, revision); + } + } + let page = placed.rect; + let whole = Rect::from_min_max(Pos2::ZERO, Pos2::new(1.0, 1.0)); + draw.texture(page, background.id, whole); // A pixel around the box, so its edges come along. Clip the source to the page raster so // an item extending past the page border never samples clamped edge texels (#3938, #4477). let (r, to) = (r.expand(1.0), to.expand(1.0)); - let clipped = r.intersect(xf.rect); - if !clipped.is_positive() || r.width() <= 0.0 || r.height() <= 0.0 { + let clipped = r.intersect(page); + if !clipped.is_positive() || r.width() <= 0.0 || r.height() <= 0.0 || page.width() <= 0.0 || page.height() <= 0.0 { return; } let map = |p: Pos2| Pos2::new(to.min.x + (p.x - r.min.x) / r.width() * to.width(), to.min.y + (p.y - r.min.y) / r.height() * to.height()); - let mut mesh = egui::Mesh::with_texture(item.id()); - for a in [clipped.left_top(), clipped.right_top(), clipped.right_bottom(), clipped.left_bottom()] { - let (u, v) = xf.screen_to_norm(a); - mesh.vertices.push(egui::epaint::Vertex { pos: map(a), uv: Pos2::new(u, v), color: Color32::WHITE }); + let dest = Rect::from_two_pos(map(clipped.min), map(clipped.max)); + // What shows is what lies on the page: the part of the destination inside it, with the + // source cut down the same way. + let shown = dest.intersect(page); + if !shown.is_positive() || dest.width() <= 0.0 || dest.height() <= 0.0 { + return; } - mesh.add_triangle(0, 1, 2); - mesh.add_triangle(0, 2, 3); - painter.add(egui::Shape::mesh(mesh)); + let norm = |p: Pos2| Pos2::new((p.x - page.min.x) / page.width(), (p.y - page.min.y) / page.height()); + let (a, b) = (norm(clipped.min), norm(clipped.max)); + let at = |p: Pos2| Pos2::new((p.x - dest.min.x) / dest.width(), (p.y - dest.min.y) / dest.height()); + let (t0, t1) = (at(shown.min), at(shown.max)); + let lerp = |from: f32, to: f32, t: f32| from + (to - from) * t; + let uv = Rect::from_min_max(Pos2::new(lerp(a.x, b.x, t0.x), lerp(a.y, b.y, t0.y)), Pos2::new(lerp(a.x, b.x, t1.x), lerp(a.y, b.y, t1.y))); + draw.texture(shown, item.id, uv); } } +/// The two rasters of a move preview. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Raster { + /// The page without the moving item. + Page, + /// The item alone. + Item, +} + /// Text style for new text (the panel's Format controls set it). pub fn default_style() -> AddedText { AddedText { size: 12.0, ..AddedText::default() } } -/// Display-space rect → screen. -fn screen_rect(xf: &PageXform, info: &DocInfo, page: usize, r: [f64; 4]) -> Rect { - let ph = info.pages[page].height as f64; - xf.view_rect([r[0] as f32, (ph - r[3]) as f32, r[2] as f32, (ph - r[1]) as f32]) -} - -/// Screen point → display space. -fn to_display(xf: &PageXform, info: &DocInfo, page: usize, p: Pos2) -> [f64; 2] { - let (vx, vy) = xf.screen_to_view(p); - [vx as f64, info.pages[page].height as f64 - vy as f64] -} - fn on_page(added: &[Added], page: usize) -> Vec<(usize, &Added)> { added.iter().filter(|a| a.page == page).enumerate().collect() } -pub(crate) fn hits_added(xf: &PageXform, info: &DocInfo, page: usize, added: &[Added], point: Pos2) -> bool { - on_page(added, page) - .iter() - .filter(|(_, a)| matches!(a.content, AddedContent::Text(_))) - .any(|(_, a)| screen_rect(xf, info, page, a.content.rect()).expand(2.0).contains(point)) +/// The parts of the added text on `page`, one per item in paint order: the page body registers +/// them with the rest of the page's parts, over a form field under them, and the topmost item wins +/// where boxes overlap. Pictures are `picture_parts`' (pdf-edit-w9). A box open for typing has none: +/// its editor takes the presses. +// PLAN: A-2 gives `page_parts(view, page, placed)`; the items live in the document, not in `DocView`, so the +// document is a parameter (caller: pdf-canvas-w9's page body). +pub(crate) fn page_parts(view: &DocView, doc: &Document, page: usize, placed: &PlacedPage) -> Vec { + let Some(frame) = PageFrame::of(placed, &doc.info) else { return Vec::new() }; + let draft = view.content.draft.as_ref().filter(|d| d.page == page).and_then(|d| d.index); + on_page(doc.added(), page) + .into_iter() + .filter(|(i, a)| matches!(a.content, AddedContent::Text(_)) && draft != Some(*i)) + .map(|(index, a)| { + let shape = HitShape::Rect(frame.screen_rect(a.content.rect()).expand(2.0)); + PagePart::new(Owner::Added { index }, page, shape, PageLayer::Placed).cursor(CursorIcon::Move) + }) + .collect() } -fn handles(r: Rect) -> [(Pos2, bool, bool); 4] { - [(r.left_top(), true, true), (r.right_top(), false, true), (r.left_bottom(), true, false), (r.right_bottom(), false, false)] +/// A press on an added item (`press.owner` is its part), or, on any other owner, the page's +/// picture selection following the picture controller. A drag shows the item at the dragged box +/// and a release that moved it at least a point applies the move; a release that didn't changes +/// nothing but the selection. A click selects, a double click (or with `edit_on_click` a click) +/// opens the text for typing. `pages` are the pages as this pass's body placed them, which the +/// press's screen points are read against. The edit the press ends in, if any. +// PLAN: A-2 gives `added_press(view, doc, press)`; the placement is a parameter so no page geometry is +// carried between passes (caller: pdf-canvas-w9's `page_tools.rs`, with `body.pages`). +pub(crate) fn added_press(view: &mut DocView, doc: &Document, pages: &[PlacedPage], press: &PagePress) -> Option { + let page = press.page; + let added = doc.added(); + let Owner::Added { index } = press.owner else { + sync_image_selection(view, page, &doc.page_images(page), added); + return None; + }; + let (_, item) = on_page(added, page).into_iter().find(|(i, _)| *i == index)?; + let AddedContent::Text(text) = &item.content else { return None }; + let frame = PageFrame::of_page(pages, &doc.info, page)?; + let cv = &mut view.content; + match press.phase { + PressPhase::DragStart { start, pos, .. } | PressPhase::Drag { start, pos, .. } => { + cv.selected = Some((page, index)); + let rect = frame.moved(text.rect, start.origin, pos); + cv.preview = Some(Preview { page, index, rect, resizing: false }); + None + } + PressPhase::Release { start, pos, click: false, .. } => { + cv.preview = None; + if (pos - start.origin).length() < 1.0 { + return None; + } + // A moved text box keeps its size, so its top edge moves with it (its height follows its lines). + let rect = frame.moved(text.rect, start.origin, pos); + Some(Edit::UpdateContent { page, index, content: item.content.with_rect(rect) }) + } + PressPhase::Release { start, click: true, .. } => { + cv.preview = None; + cv.selected = Some((page, index)); + if start.clicks < 2 && !cv.edit_on_click { + return None; + } + // Text that can't be drawn stays where it is being typed (#125). + if cv.hold_blocked() || cv.draft.as_ref().is_some_and(|d| d.page == page && d.index == Some(index)) { + return None; + } + let typed = cv.finish_draft(added); + let mut draft = TextDraft::new(page, Some(index), text.rect, text.text.clone(), text.clone()); + draft.focus = true; + cv.draft = Some(draft); + cv.selected = Some((page, index)); + typed + } + PressPhase::Cancel { .. } => { + cv.preview = None; + None + } + _ => None, + } } -/// The rect while moving or resizing (images keep their proportions). -fn dragged(r: Rect, grab: Grab, d: egui::Vec2, keep_aspect: bool) -> Rect { - match grab { - Grab::Move => r.translate(d), - Grab::Corner(left, top) => { - let (mut dx, mut dy) = (if left { -d.x } else { d.x }, if top { -d.y } else { d.y }); - if keep_aspect && r.width() > 0.0 && r.height() > 0.0 { - // Use the axis with the larger relative pointer change so shrinking along one axis - // does not freeze when the other axis has not moved inward (#4477). - let (rx, ry) = (dx / r.width(), dy / r.height()); - let delta = if rx.abs() > ry.abs() { rx } else { ry }; - let k = (1.0 + delta).max(0.05); - dx = r.width() * k - r.width(); - dy = r.height() * k - r.height(); - } - let mut out = r; - if left { - out.min.x -= dx; - } else { - out.max.x += dx; - } - if top { - out.min.y -= dy; - } else { - out.max.y += dy; - } - Rect::from_two_pos(out.min, out.max) +/// Add text: a press on a page that nothing else holds starts a new box there, keeping the box being +/// typed. It is the tool's, not a part's: the press is the canvas's background (M-8). The tool value +/// is built again each pass, so the box starts on the press itself and no gesture state is kept. +pub(crate) struct AddTextTool<'a> { + view: &'a mut DocView, + doc: &'a Document, + pages: &'a [PlacedPage], + style: &'a AddedText, +} + +impl<'a> AddTextTool<'a> { + /// The tool over `view`'s content, writing the text kept by a click to `view.pending_edit`, with + /// `pages` as the body placed them and `style` for the new text. + pub(crate) fn new(view: &'a mut DocView, doc: &'a Document, pages: &'a [PlacedPage], style: &'a AddedText) -> Self { + AddTextTool { view, doc, pages, style } + } + + /// The box a click at `at` (screen) on `page` starts. + fn start_box(&mut self, page: usize, at: Pos2) { + let Some(frame) = PageFrame::of_page(self.pages, &self.doc.info, page) else { return }; + let added = self.doc.added(); + let cv = &mut self.view.content; + // Text that can't be drawn stays where it is being typed (#125). + if cv.hold_blocked() { + return; + } + // A click elsewhere keeps the text being typed and starts a new box (#74). The editor ends its + // session on the same background press, so whichever runs first finds the other done. + let typed = cv.finish_draft(added); + // The Format panel styles the new text, not the box just kept. + (cv.selected, cv.select_added) = (None, None); + let at = frame.display(at); + let mut style = self.style.clone(); + style.text.clear(); + let page_width = self.doc.info.pages.get(page).map_or(f64::INFINITY, |p| p.width as f64); + let rect = [at[0], at[1] - style.size * 1.2, (at[0] + 200.0).min(page_width), at[1]]; + style.rect = rect; + let mut draft = TextDraft::new(page, None, rect, String::new(), style); + draft.focus = true; + cv.draft = Some(draft); + if typed.is_some() { + self.view.pending_edit = typed; } } } -/// What of the added text and pictures lies under `p` on `page`: the selected item's corners, then -/// the topmost item. Placed on the page, over a form field under it. -pub(crate) fn hit(xf: &PageXform, info: &DocInfo, page: usize, added: &[Added], view: &DocView, p: Pos2) -> Option { - if !xf.rect.contains(p) { +impl PageFrame { + /// The frame of `page` among the pages the body placed. + fn of_page(pages: &[PlacedPage], info: &DocInfo, page: usize) -> Option { + pages.iter().find(|p| p.page == page).and_then(|p| PageFrame::of(p, info)) + } +} + +impl CanvasTool for AddTextTool<'_> { + fn press(&mut self, pointer: &ToolPointer, _cx: &mut ToolContext<'_>) -> ToolAction { + let Some(placed) = self.pages.iter().find(|p| p.rect.contains(pointer.pos)) else { return ToolAction::Ignored }; + self.start_box(placed.page, pointer.pos); + ToolAction::Done + } + + fn drag(&mut self, _pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {} + + fn release(&mut self, _pointer: &ToolPointer, _cx: &mut ToolContext<'_>) {} + + fn cancel(&mut self, _reason: CancelReason, _cx: &mut ToolContext<'_>) {} + + /// The text tool draws nothing over the page: the box being typed is the page body's. + fn paint(&self, _draw: &Draw<'_>, _cx: &ToolContext<'_>) {} + + fn cursor(&self, _cx: &ToolContext<'_>) -> Cursor { + Cursor::System(CursorIcon::Text) + } + + fn command_form(&self) -> ToolPath { + ToolPath::Command("the Add Text command (Edit ▸ Add text)") + } +} + +/// Delete removes the selected item (not while a box is open): one undoable edit. `None` when +/// nothing is selected. +pub(crate) fn delete_selected(view: &mut DocView) -> Option { + if view.content.draft.is_some() { return None; } - let items: Vec<(usize, &Added)> = on_page(added, page).into_iter().filter(|(_, a)| matches!(a.content, AddedContent::Text(_))).collect(); - let selected = view.content.selected.filter(|s| s.0 == page).and_then(|(_, si)| items.iter().find(|(i, _)| *i == si)); - if let Some((index, a)) = selected - && let Some((_, left, top)) = - handles(screen_rect(xf, info, page, a.content.rect()).expand(1.0)).into_iter().find(|(c, ..)| c.distance(p) <= 6.0) - { - let icon = if left == top { egui::CursorIcon::ResizeNwSe } else { egui::CursorIcon::ResizeNeSw }; - return Some(Hit::new(Owner::Added { index: *index, corner: Some((left, top)) }, Layer::Handle, icon)); - } - let (index, _) = items.iter().rev().find(|(_, a)| screen_rect(xf, info, page, a.content.rect()).expand(2.0).contains(p))?; - Some(Hit::new(Owner::Added { index: *index, corner: None }, Layer::Placed, egui::CursorIcon::Move)) + let (page, index) = view.content.selected.take()?; + view.content.preview = None; + Some(Edit::DeleteContent { page, index }) } -/// What added content is told on one page. -#[derive(Clone, Copy)] -pub(crate) struct ContentCx<'a> { - pub added: &'a [Added], - /// What the press the pages hold is to this page. With the Edit panel open, a press on added - /// text is its own with the tools that pick it up ([`hit`]). - pub press: PagePress, - /// Edit text's input is open: no dialog, palette, other window or other tab has it. - pub gate: bool, - /// The tool picks added content up (Select, Add text, Edit text): a drag moves it or resizes it. - pub picks_up: bool, - /// The Add text tool: a click nobody holds starts a new box where it was pressed. - pub adding_text: bool, - /// A click on added text opens it for typing (Add text, Edit text); otherwise a double-click does. - pub edit_on_click: bool, - /// The style of new text. - pub style: &'a AddedText, -} - -/// Pointer input on one page in Edit mode, on the presses that are added content's ([`hit`]) and, -/// with Add text, the clicks nobody holds. `true` when it used the input. -pub(crate) fn page_input(cx: PageToolContext<'_>, ccx: ContentCx<'_>, view: &mut DocView) -> bool { - let PageToolContext { resp, xf, ptr, page, info, .. } = cx; - let ContentCx { added, press, gate, picks_up, adding_text, edit_on_click, style } = ccx; - view.content.held = ptr.any_down; - if !gate { - return false; - } - let mut consumed = false; - let pointer = ptr.pos; - let cv = &mut view.content; - if let Some((gp, grab, start)) = cv.grab - && gp == page - { - consumed = true; - if resp.drag_stopped() || !ptr.primary_down { - cv.grab = None; - let end = pointer.unwrap_or(start); - if let Some((sp, si)) = cv.selected - && sp == page - && let Some((_, a)) = on_page(added, page).into_iter().find(|(i, a)| *i == si && matches!(a.content, AddedContent::Text(_))) - && (end - start).length() >= 1.0 - { - let r = dragged(screen_rect(xf, info, page, a.content.rect()), grab, end - start, false); - let (p0, p1) = (to_display(xf, info, page, r.left_bottom()), to_display(xf, info, page, r.right_top())); - let mut rect = [p0[0], p0[1], p1[0], p1[1]]; - if let AddedContent::Text(t) = &a.content - && grab == Grab::Move - { - // Text height follows its lines: keep the top edge's offset only. - rect = [rect[0], rect[3] - (t.rect[3] - t.rect[1]), rect[2], rect[3]]; - } - view.pending_edit = Some(Edit::UpdateContent { page, index: si, content: a.content.with_rect(rect) }); - } - } - return consumed; - } - // Where a press nobody holds begins on this page: Add text's click starts its box there. - if let Some(o) = ptr.pressed().filter(|_| press != PagePress::Elsewhere) { - cv.pressed_at = (press == PagePress::Free).then_some((page, o)); - } - let Some(p) = pointer.filter(|p| xf.rect.contains(*p)) else { return consumed }; - let items: Vec<(usize, &Added)> = on_page(added, page).into_iter().filter(|(_, a)| matches!(a.content, AddedContent::Text(_))).collect(); - // What the press was on ([`hit`]): an item, or a corner of the selected one. - let owned = match press { - PagePress::Mine(Owner::Added { index, corner }) => Some((index, corner)), - _ => None, - }; - // The tools that don't pick added content up have no hit on it: with the Edit panel open their - // clicks on added text still select it and their presses there are its, by this test at the - // pointer, as before. - let under = (!picks_up) - .then(|| items.iter().rev().find(|(_, a)| screen_rect(xf, info, page, a.content.rect()).expand(2.0).contains(p)).map(|(i, _)| *i)) - .flatten(); - let target = if picks_up { owned } else { under.map(|i| (i, None)) }; - if adding_text { - view.cursor.claim(Layer::ToolArea, egui::CursorIcon::Text); - // A new box where nothing drawn over the page holds the press. - if resp.clicked() && press == PagePress::Free { - // Text that can't be drawn stays where it is being typed (#125). - if cv.hold_blocked() { - return true; - } - // A click elsewhere keeps the text being typed and starts a new box (#74). The click - // can reach the page before the editor sees it lose focus, so finish it here. - let typed = cv.draft.take().and_then(|d| finish(cv, d, added)); - // The Format panel styles the new text, not the box just kept. - (cv.selected, cv.select_added) = (None, None); - // Where the click was pressed, as every owner acts where its press was. - let start = cv.pressed_at.take().filter(|(pg, _)| *pg == page).map_or(p, |(_, o)| o); - let at = to_display(xf, info, page, start); - let mut style = style.clone(); - style.text.clear(); - let page_width = info.pages.get(page).map_or(f64::INFINITY, |p| p.width as f64); - let rect = [at[0], at[1] - style.size * 1.2, (at[0] + 200.0).min(page_width), at[1]]; - style.rect = rect; - cv.draft = Some(TextDraft { page, index: None, rect, text: String::new(), style, focus: true, selection: None, typing_from: None }); - consumed = true; - if typed.is_some() { - view.pending_edit = typed; - } - return consumed; - } - } - // A drag on what the press was on: a corner resizes the selected item, the item itself moves, - // with the tools that pick added content up. - if ptr.drag_started { - let origin = ptr.origin.unwrap_or(p); - match owned.filter(|_| picks_up) { - Some((_, Some((left, top)))) => { - cv.grab = Some((page, Grab::Corner(left, top), origin)); - consumed = true; - } - Some((index, None)) => { - cv.selected = Some((page, index)); - cv.grab = Some((page, Grab::Move, origin)); - consumed = true; - } - None => {} - } - return consumed || owned.is_some(); - } - // A double-click, or with `edit_on_click` a click, opens the text the press was on for typing. - if (resp.double_clicked() || edit_on_click && resp.clicked()) - && let Some((i, None)) = target - && let Some((_, a)) = items.iter().find(|(index, _)| *index == i) - && let AddedContent::Text(t) = &a.content - { - if cv.hold_blocked() { - return true; - } - if cv.draft.as_ref().is_some_and(|d| d.page == page && d.index == Some(i)) { - return true; - } - if let Some(edit) = cv.finish_draft(added) { - view.pending_edit = Some(edit); - } - cv.draft = Some(TextDraft { - page, - index: Some(i), - rect: t.rect, - text: t.text.clone(), - style: t.clone(), - focus: true, - selection: None, - typing_from: None, - }); - cv.selected = Some((page, i)); - consumed = true; - return consumed; - } - // A click selects the item its press was on, keeps the selected one when on a corner of it, and - // on anything else on this page (but the objects selected together, which take the selection - // themselves) leaves it unselected. - if resp.clicked() { - match (target, press) { - (Some((i, None)), _) => { - cv.selected = Some((page, i)); - consumed = true; - } - (Some((_, Some(_))), _) => consumed = true, - (None, PagePress::Elsewhere | PagePress::Mine(Owner::Objects { .. })) => {} - (None, _) => cv.selected = None, - } - } - consumed || owned.is_some() || under.is_some() && resp.is_pointer_button_down_on() -} - -/// Outlines of added items (hover and selection with handles) and the box being dragged, the -/// pages' `pointer` over them. -pub(crate) fn paint_page( - painter: &egui::Painter, - xf: &PageXform, - page: usize, - info: &DocInfo, - added: &[Added], - view: &DocView, - pointer: Option, -) { - let cv = &view.content; - for (i, a) in on_page(added, page) { - if matches!(a.content, AddedContent::Image(_)) { - continue; - } - if cv.draft.as_ref().is_some_and(|d| d.page == page && d.index == Some(i)) { - continue; - } - let mut r = screen_rect(xf, info, page, a.content.rect()); - let selected = cv.selected == Some((page, i)); - if selected - && let (Some((gp, g, start)), Some(p)) = (cv.grab, pointer) - && gp == page - { - r = dragged(r, g, p - start, matches!(a.content, AddedContent::Image(_))); - } - if selected { - painter.rect_stroke(r.expand(1.0), CornerRadius::ZERO, Stroke::new(1.5, SELECT_BLUE), egui::StrokeKind::Outside); - for (c, ..) in handles(r.expand(1.0)) { - painter.circle(c, 3.5, Color32::WHITE, Stroke::new(1.5, SELECT_BLUE)); - } - } else if pointer.is_some_and(|p| r.expand(2.0).contains(p)) { - painter.rect_stroke(r.expand(1.0), CornerRadius::ZERO, Stroke::new(1.0, SELECT_BLUE.gamma_multiply(0.7)), egui::StrokeKind::Outside); - } - } +/// Escape clears the selection; whether there was one to clear. +pub(crate) fn deselect(view: &mut DocView) -> bool { + view.content.preview = None; + view.content.selected.take().is_some() } /// The image controller owns image selection; the added-content panel follows the same XObject. @@ -615,7 +648,7 @@ pub(crate) fn sync_image_selection(view: &mut DocView, page: usize, images: &[pd if matches.next().is_none() { selected } else { None } }); view.content.select_added = None; - view.content.grab = None; + view.content.preview = None; } /// Leaving the image controller cannot leave a hidden added image owning keyboard actions. @@ -629,31 +662,7 @@ pub(crate) fn release_image_selection(view: &mut DocView, added: &[Added]) { if image_selected { view.content.selected = None; view.content.select_added = None; - view.content.grab = None; - } -} - -/// Delete removes the selected item; Escape clears the selection. Not while something is over the -/// pages. -pub(crate) fn keys(ctx: &egui::Context, keys: PageKeys, view: &mut DocView, image_controller_active: bool) { - if image_controller_active && view.image_selection.is_some() - || matches!(view.pending_edit.as_ref(), Some(Edit::EditPageImage { .. })) - || view.content.selected.is_none() - || view.content.draft.is_some() - || ctx.egui_wants_keyboard_input() - { - return; - } - let del = keys.pressed(ctx, egui::Key::Delete) || keys.pressed(ctx, egui::Key::Backspace); - let esc = keys.pressed(ctx, egui::Key::Escape); - // Not while a button is down: the press held would then name another item. - if del - && !view.content.held - && let Some((page, index)) = view.content.selected.take() - { - view.pending_edit = Some(Edit::DeleteContent { page, index }); - } else if esc { - view.content.selected = None; + view.content.preview = None; } } @@ -671,46 +680,314 @@ pub(crate) fn after_refresh(view: &mut DocView, added: &[Added]) { } } -/// The in-place text editor, with Done and Discard beside it. Returns the edit once the text is -/// committed (a click away, or Done), and whether Done finished adding text. Discard or Escape -/// throws the draft away. -pub(crate) fn editor(ctx: &egui::Context, keys: PageKeys, view: &mut DocView, info: &DocInfo, added: &[Added]) -> (Option, bool) { - let doc_id = view.id; - let Some(page) = view.content.draft.as_ref().map(|d| d.page) else { return (None, false) }; - let Some(xf) = view.page_xform(page) else { return (None, false) }; - let zoom = xf.zoom(); - let Some(draft) = view.content.draft.as_mut() else { return (None, false) }; - let font = crate::edit_text_ui::editor_font(&draft.style, (draft.style.size as f32 * zoom).clamp(1.0, 300.0)); - let text = AddedText { text: draft.text.clone(), ..draft.style.clone() }; - let Some(page_width) = info.pages.get(page).map(|p| p.width as f64) else { return (None, false) }; - if let Some((key, z, width, rect)) = &view.content.layout - && *key == text - && *z == zoom - && *width == page_width - { - draft.rect = *rect; - } else { - let source = draft.style.rect; - if draft.index.is_some() && draft.text == draft.style.text { - draft.rect = source; - } else { - let natural = ctx.fonts_mut(|f| f.layout_no_wrap(draft.text.clone(), font.clone(), Color32::BLACK).size().x) as f64 / zoom as f64; - let width = natural.max(pdfcraft_engine::added_text_width(&text)) + 2.0; - let available = page_width - source[0]; - let width = width.max(source[2] - source[0]).min(available.max(1.0)); - draft.rect = [source[0], source[1], source[0] + width, source[3]]; - draft.rect = pdfcraft_engine::added_text_rect(&AddedText { rect: draft.rect, ..text.clone() }); - } - view.content.layout = Some((text, zoom, page_width, draft.rect)); +/// The page's added content as controls over the pages: the selected text's frame (resized by its +/// corners), the outline of the text under the pointer, and the open box's `TextEditor` session +/// with Done and Discard hung below it. Returns the edit a resize or the end of the session makes. +/// The box's paper and text are painted by [`ContentView::paint_draft`]. +/// +/// A pass applies only what its own pass receives: the frame's and the editor's events come from the +/// pass that shows them, and the preview they leave is held fact, never replayed. `hovered` is the +/// (page, item) of the added-text part under the pointer, as the page body reads it from the parts. +// PLAN: assumed the page body passes `PageParts::hovered`'s `Owner::Added { index }` with its page (pdf-canvas-w9). +pub(crate) fn content_controls(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc: &Document, hovered: Option<(usize, usize)>) -> Option { + if view.content.draft.is_none() { + view.content.drawn = None; } - let r = screen_rect(&xf, info, page, draft.rect); - let source_rect = draft.index.map(|_| screen_rect(&xf, info, page, draft.style.rect)); - // At least 60 points wide, so a short box can still be clicked into. Where that is wider than - // the box, the editor reaches past it away from the edge its text keeps (the right edge for - // right-aligned text, both halves for centred), so the text stays where the page draws it. - // shortcut: lines aligned differently from each other in a box under 60 points keep the - // editor's left edge; anchor each line on its own if such boxes turn out to matter. - let width = r.width().max(60.0); + let mut edit = None; + for placed in body.pages { + let Some(frame) = PageFrame::of(placed, &doc.info) else { continue }; + let hover = hovered.filter(|(page, _)| *page == placed.page).map(|(_, index)| index); + let resized = item_controls(ui, body, view, doc, &frame, hover); + let typed = draft_session(ui, body, view, doc, placed, &frame); + edit = edit.or(resized).or(typed); + } + edit +} + +/// `r` (display space) as a box in the canvas's document units. +fn doc_rect(view: &craft::behavior::CanvasView, frame: &PageFrame, r: [f64; 4]) -> DocRect { + let (a, b) = (view.to_doc(frame.screen([r[0], r[1]])), view.to_doc(frame.screen([r[2], r[3]]))); + DocRect::from_points(a, b) +} + +/// The box `state` in display space: its bounds. +fn display_rect(view: &craft::behavior::CanvasView, frame: &PageFrame, state: &BoxState) -> [f64; 4] { + let corners = state.quad.map(|p| frame.display(view.to_screen(p))); + let fold = |pick: fn(f64, f64) -> f64, i: usize, init: f64| corners.iter().fold(init, |m, c| pick(m, c[i])); + [fold(f64::min, 0, f64::INFINITY), fold(f64::min, 1, f64::INFINITY), fold(f64::max, 0, f64::NEG_INFINITY), fold(f64::max, 1, f64::NEG_INFINITY)] +} + +/// The selected text's frame and the hover outline on one page. +fn item_controls(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc: &Document, frame: &PageFrame, hovered: Option) -> Option { + let page = frame.page; + let items = on_page(doc.added(), page); + let draft = view.content.draft.as_ref().filter(|d| d.page == page).and_then(|d| d.index); + let text_at = |index: usize| items.iter().find(|(i, a)| *i == index && matches!(a.content, AddedContent::Text(_))).map(|(_, a)| *a); + let selected = view.content.selected.filter(|s| s.0 == page && draft != Some(s.1)).and_then(|(_, i)| text_at(i).map(|a| (i, a))); + if let Some(i) = hovered.filter(|i| draft != Some(*i) && selected.map(|s| s.0) != Some(*i)) + && let Some(a) = text_at(i) + { + let outline = HoverShape::Rect(doc_rect(&body.view, frame, a.content.rect())); + let _ = HoverOutline::new(tl!("Added text"), Some(outline)).show(ui); + } + let (index, item) = selected?; + let applied = item.content.rect(); + let shown = view.content.preview.filter(|p| (p.page, p.index) == (page, index)).map_or(applied, |p| p.rect); + // Text resizes freely and rewraps; a picture's own frame is the picture controller's. + let rules = BoxRules::default() + .with_scale(ScaleRule::Free) + .with_aspect_linked(false) + .with_allow(BoxAllow::new(false, false, false).with_warp(false)) + .with_min_side(4.0) + .with_handles(BoxHandles::Corners); + let state = BoxState::from_rect(doc_rect(&body.view, frame, shown)); + let out = TransformBox::text_frame(tl!("Added text frame"), Bind::given(state), doc_rect(&body.view, frame, applied)) + .rules(rules) + .session_arrows(false) + .show(ui); + if out.discard { + view.content.selected = None; + view.content.preview = None; + } + let events = &out.edit.events; + if let Some(done) = events.committed() { + view.content.preview = None; + let rect = display_rect(&body.view, frame, done); + // A click with no drag leaves the box as it was: nothing is applied. + let moved = rect.iter().zip(applied).any(|(a, b)| (a - b).abs() > 1.0e-3); + return moved.then(|| Edit::UpdateContent { page, index, content: item.content.with_rect(rect) }); + } + if events.cancel_reason().is_some() { + view.content.preview = None; + } else if let Some(live) = events.value() { + view.content.preview = Some(Preview { page, index, rect: display_rect(&body.view, frame, live), resizing: true }); + } + None +} + +/// The least width of the open box on screen, in points, so a short box can still be clicked into. +const LEAST_WIDTH: f32 = 60.0; + +/// The editor's inset around its text in screen points: across and down. +const INSET: egui::Vec2 = egui::vec2(4.0, 2.0); + +/// Where the draft's box and text lie on screen, and what they are laid out with. +struct BoxLayout { + font: egui::FontId, + color: Color32, + letter_spacing: f32, + /// The wrap width in screen points. + wrap: f32, + /// The galley's top left on screen. + origin: Pos2, +} + +/// The chars of each row of `galley` (without its line break) with its box, in the galley's space. +fn rows_of(galley: &egui::Galley) -> Vec<(Range, Rect)> { + let mut start = 0; + galley + .rows + .iter() + .map(|placed| { + let chars = placed.row.glyphs.len(); + let range = start..start + chars; + start += chars + usize::from(placed.ends_with_newline); + (range, Rect::from_min_size(placed.pos, placed.row.size)) + }) + .collect() +} + +/// The byte where char `at` of `text` starts, or the text's end. +fn byte_at(text: &str, at: usize) -> usize { + text.char_indices().nth(at).map_or(text.len(), |(byte, _)| byte) +} + +/// The draft's text as the `TextEditor` sees it: laid out as the page draws it (each paragraph with +/// its own alignment, character spacing scaled like the font), its geometry mapped to the canvas's +/// document units, and every edit recorded in the box's own Undo history. +struct AddedTextHost<'a> { + draft: &'a mut TextDraft, + ctx: egui::Context, + view: craft::behavior::CanvasView, + layout: BoxLayout, + laid_out: Option<(String, Vec>, Arc)>, +} + +impl AddedTextHost<'_> { + /// The galley of the draft's text now, laid out again only when the text or its alignments changed. + fn galley(&mut self) -> Arc { + if let Some((text, aligns, galley)) = &self.laid_out + && *text == self.draft.text + && *aligns == self.draft.style.aligns + { + return Arc::clone(galley); + } + let BoxLayout { font, color, letter_spacing, wrap, .. } = &self.layout; + let galley = aligned_galley(&self.ctx, &self.draft.text, &self.draft.style, font, *color, *letter_spacing, *wrap); + self.laid_out = Some((self.draft.text.clone(), self.draft.style.aligns.clone(), Arc::clone(&galley))); + galley + } + + /// A point of the galley's space in document units. + fn doc(&self, local: egui::Vec2) -> Point { + self.view.to_doc(self.layout.origin + local) + } + + /// A point in document units in the galley's space. + fn local(&self, p: Point) -> egui::Vec2 { + self.view.to_screen(p) - self.layout.origin + } + + /// Screen points per document unit, never zero. + fn zoom(&self) -> f32 { + let zoom = self.view.zoom as f32; + if zoom > 0.0 { zoom } else { 1.0 } + } + + /// The row holding char `at`: a soft wrap belongs to the row it ends. + fn row_of(rows: &[(Range, Rect)], at: usize) -> usize { + rows.iter().position(|(r, _)| r.start <= at && at < r.end).or_else(|| rows.iter().rposition(|(r, _)| r.start <= at)).unwrap_or(0) + } +} + +impl TextEditorHost for AddedTextHost<'_> { + fn text(&self) -> &str { + &self.draft.text + } + + fn replace(&mut self, range: Range, text: &str, kind: EditKind) -> bool { + let before = self.draft.text.clone(); + let start = byte_at(&before, range.start); + let end = byte_at(&before, range.end).max(start); + self.draft.text.replace_range(start..end, text); + // Each paragraph keeps its own alignment through the typing, the edit's place telling which of + // two equal paragraphs changed. + let caret = start + text.len(); + self.draft.style.aligns = pdfcraft_engine::paragraph_align::remap_at(&before, &self.draft.text, &self.draft.style.aligns, Some(caret)); + self.draft.selection = Some(TextSelection::caret_at(range.start + text.chars().count())); + let now = self.draft.typed(); + self.draft.history.record(kind, now); + true + } + + fn hit(&mut self, at: Point) -> (usize, usize) { + let galley = self.galley(); + let cursor = galley.cursor_from_pos(self.local(at)); + (cursor.index.0, galley.layout_from_cursor(cursor).row) + } + + fn caret(&mut self, offset: usize, line: Option) -> Option { + let galley = self.galley(); + let mut cursor = egui::text::CCursor::new(offset); + if line.is_some_and(|line| galley.layout_from_cursor(cursor).row != line) { + cursor.prefer_next_row = !cursor.prefer_next_row; + } + let r = galley.pos_from_cursor(cursor); + Some(CaretLine::new(self.doc(egui::vec2(r.min.x, r.min.y)), self.doc(egui::vec2(r.min.x, r.max.y)))) + } + + fn selection_quads(&mut self, range: Range) -> Vec<[Point; 4]> { + let galley = self.galley(); + let x = |at: usize| galley.pos_from_cursor(egui::text::CCursor::new(at)).min.x; + rows_of(&galley) + .into_iter() + .filter_map(|(chars, rect)| { + let (from, to) = (range.start.max(chars.start), range.end.min(chars.end)); + (from < to).then(|| { + let (x0, x1) = (x(from), x(to)); + [ + self.doc(egui::vec2(x0, rect.min.y)), + self.doc(egui::vec2(x1, rect.min.y)), + self.doc(egui::vec2(x1, rect.max.y)), + self.doc(egui::vec2(x0, rect.max.y)), + ] + }) + }) + .collect() + } + + fn underline_segments(&mut self, range: Range) -> Vec<[Point; 2]> { + let galley = self.galley(); + let x = |at: usize| galley.pos_from_cursor(egui::text::CCursor::new(at)).min.x; + rows_of(&galley) + .into_iter() + .filter_map(|(chars, rect)| { + let (from, to) = (range.start.max(chars.start), range.end.min(chars.end)); + (from < to).then(|| [self.doc(egui::vec2(x(from), rect.max.y)), self.doc(egui::vec2(x(to), rect.max.y))]) + }) + .collect() + } + + fn lines(&mut self) -> Vec { + let galley = self.galley(); + let chars: Vec = self.draft.text.chars().collect(); + let x = |at: usize| galley.pos_from_cursor(egui::text::CCursor::new(at)).min.x; + let zoom = self.zoom(); + rows_of(&galley) + .into_iter() + .map(|(range, rect)| { + let text: String = chars.get(range.clone()).map(|c| c.iter().collect()).unwrap_or_default(); + let xs: Vec = range.clone().map(x).chain(std::iter::once(x(range.end))).collect(); + let origin = xs.first().copied().unwrap_or(rect.min.x); + let positions = xs.iter().take(range.len()).map(|v| (v - origin) / zoom).collect(); + let widths = xs.windows(2).map(|w| (w[1] - w[0]) / zoom).collect(); + let (top, bottom) = (self.doc(rect.min.to_vec2()), self.doc(rect.max.to_vec2())); + let rect = Rect::from_two_pos(Pos2::new(top.x as f32, top.y as f32), Pos2::new(bottom.x as f32, bottom.y as f32)); + // epaint keeps no baseline: the row's bottom stands for it. + let baseline = rect.max.y; + let runs = vec![HostRun::new(0..text.len(), false, positions, widths)]; + HostLine::new(text, range, rect, baseline, runs) + }) + .collect() + } + + fn line_range(&mut self, line: usize) -> Range { + let galley = self.galley(); + rows_of(&galley).into_iter().nth(line).map_or(0..0, |(range, _)| range) + } + + fn line_step(&mut self, offset: usize, lines: i32) -> usize { + let galley = self.galley(); + let rows = rows_of(&galley); + let current = Self::row_of(&rows, offset); + let last = rows.len().saturating_sub(1); + let target = (current as i64 + i64::from(lines)).clamp(0, last as i64) as usize; + if target == current { + // Up from the first row goes to the text's start, down from the last to its end. + return if lines < 0 { 0 } else { self.draft.text.chars().count() }; + } + let x = galley.pos_from_cursor(egui::text::CCursor::new(offset)).min.x; + let y = rows.get(target).map_or(0.0, |(_, rect)| rect.center().y); + galley.cursor_from_pos(egui::vec2(x, y)).index.0 + } + + fn line_edge(&mut self, offset: usize, end: bool) -> usize { + let galley = self.galley(); + let rows = rows_of(&galley); + rows.get(Self::row_of(&rows, offset)).map_or(0, |(range, _)| if end { range.end } else { range.start }) + } +} + +/// The open box's session on `placed`'s page: layout, the editor, Done and Discard and the line +/// for text the fonts can't draw. The edit the session ends in, if any. +fn draft_session(ui: &mut egui::Ui, body: &PageBody<'_>, view: &mut DocView, doc: &Document, placed: &PlacedPage, frame: &PageFrame) -> Option { + let page = placed.page; + let ctx = ui.ctx().clone(); + let zoom = placed.scale as f32; + let page_width = f64::from(doc.info.pages.get(page)?.width); + let editor_id = egui::Id::new(("added-text-editor", view.view_key())); + let background_ready = view.content.draft.as_ref().and_then(|d| d.index).is_some_and(|index| view.text_background.ready_added(page, index)); + let cv = &mut view.content; + let draft = cv.draft.as_mut().filter(|d| d.page == page)?; + let font = crate::edit_text_ui::editor_font(&draft.style, (draft.style.size as f32 * zoom).clamp(1.0, 300.0)); + grow(&ctx, draft, &mut cv.layout, &font, zoom, page_width); + let r = frame.screen_rect(draft.rect); + let source_rect = draft.index.map(|_| frame.screen_rect(draft.style.rect)); + // Where the least width is wider than the box, the editor reaches past it away from the edge its + // text keeps (the right edge for right-aligned text, both halves for centred), so the text stays + // where the page draws it. Lines aligned differently from each other in a box that narrow keep + // the editor's left edge. + let width = r.width().max(LEAST_WIDTH); // The alignment every line shares, its own or the box's. let first = draft.style.paragraph_align(0); let shared = (1..pdfcraft_engine::paragraph_align::count(&draft.text)).all(|i| draft.style.paragraph_align(i) == first).then_some(first); @@ -720,119 +997,100 @@ pub(crate) fn editor(ctx: &egui::Context, keys: PageKeys, view: &mut DocView, in _ => 0.0, }; let at = r.min - egui::vec2((width - r.width()) * anchor, 0.0); - let background_ready = draft.index.is_some_and(|index| view.text_background.ready_added(page, index)); - let tokens = Tokens::get(ctx); - let (mut commit, mut cancel, mut done) = (false, false, false); - let mut undrawable = None; - let memo = &view.content.undrawable; - // Clicks outside the document (the Format text panel) keep the text open, as they keep a - // paragraph being edited open. - // Where the click that took the focus was: the pointer itself may be gone by then (a touch, a - // pen lifted away). The keyboard moving there (Tab, a screen reader) keeps it open too. - let away = |p: egui::Pos2| !view.viewport_rect().contains(p); - let outside = ctx.input(|i| i.pointer.interact_pos()).is_some_and(away) || crate::edit_text_ui::focus_pos(ctx).is_some_and(away); - // Shown at once, like the paragraph editor: a fade-in shows the page's copy through it. Over - // the page, so only where the document shows: text scrolled under the mode bar or a side - // panel must leave them their pointer (#2755). - egui::Area::new(egui::Id::unique(("added-text", view.view_key()))) - .fade_in(false) - .order(egui::Order::Foreground) - .fixed_pos(at) - .constrain_to(view.viewport_rect()) - .constrain(false) - .show(ctx, |ui| { - let Some(t) = view.content.draft.as_mut() else { return }; - ui.set_width(r.width() + 64.0); - if let Some(source_rect) = source_rect.filter(|_| !background_ready) { - ui.painter().rect_filled(source_rect.union(r).expand(1.0), CornerRadius::ZERO, Color32::WHITE); - } - // The box is white in every theme, so the caret must not follow the theme (pale in dark mode) (#655). - ui.visuals_mut().text_cursor.stroke.color = crate::edit_text_ui::caret_color_on(Color32::WHITE); - let [cr, cg, cb] = t.style.color.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8); - let color = Color32::from_rgb(cr, cg, cb); - // Character spacing shows as the page will draw it, scaled like the font. - let letter_spacing = (t.style.char_spacing * f64::from(zoom)) as f32; - // Laid out as the page draws it, each paragraph with its own alignment, so opening the - // box doesn't show it realigned. - let style = t.style.clone(); - let line_font = font.clone(); - let mut layouter = |ui: &egui::Ui, text: &dyn egui::TextBuffer, wrap: f32| { - aligned_galley(ui, text.as_str(), &style, &line_font, color, letter_spacing, wrap) - }; - let before = t.text.clone(); - let input = input_id(); - t.claim_typing(ui.ctx(), doc_id); - ui.horizontal_top(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - let output = egui::TextEdit::multiline(&mut t.text) - .font(font) - .desired_width(width) - .desired_rows(1) - .layouter(&mut layouter) - // Keep the page editor's original inset; the theme's larger button padding - // otherwise shifts narrow right-aligned boxes away from their text edge. - .margin(egui::Margin::symmetric(4, 2)) - .background_color(if background_ready { Color32::TRANSPARENT } else { Color32::WHITE }) - .text_color(color) - .hint_text(tl!("Type text")) - .id(input) - .show(ui); - let resp = output.response; - if let Some(cursor) = output.cursor_range { - let chars = cursor.as_sorted_char_range(); - let byte = |index: usize| t.text.char_indices().nth(index).map_or(t.text.len(), |(at, _)| at); - t.selection = Some(byte(chars.start.into())..byte(chars.end.into())); - } - // Each paragraph keeps its own alignment through the typing. - if t.text != before { - crate::edit_text_ui::follow_typing(ui.ctx(), input, &before, &t.text, &mut [&mut t.style.aligns]); - } - // The editor has no visible label; name it for assistive tech. - resp.response.clone().accessible_name(tl!("Added text")); - if t.focus { - resp.request_focus(); - if let Some(range) = &t.selection { - crate::edit_text_ui::reselect(ui.ctx(), input, &t.text, range); - } - t.focus = false; - } - let buttons = egui::Frame::NONE - .fill(tokens.card) - .stroke(Stroke::new(1.0, tokens.border)) - .corner_radius(CornerRadius::same(6)) - .inner_margin(2) - .show(ui, |ui| { - ui.spacing_mut().item_spacing = egui::vec2(2.0, 2.0); - ui.horizontal(|ui| { - done = crate::icons::button(ui, "check", 24.0, false, tl!("Done adding text")).clicked(); - cancel = crate::icons::button(ui, "x", 24.0, false, tl!("Discard this text (Esc)")).clicked(); - }); - }) - .response - .rect; - // Pressing a button, or moving the keyboard to one, takes the focus from the text: - // that is not a click away. - let on_buttons = ui.input(|i| i.pointer.interact_pos()).is_some_and(|p| buttons.contains(p)) - || crate::edit_text_ui::focus_pos(ui.ctx()).is_some_and(|p| buttons.contains(p)); - cancel |= keys.pressed(ui.ctx(), egui::Key::Escape); - commit = done || resp.lost_focus() && !on_buttons && !outside && !view.objects.hold_editor; - }); - // Page text is drawn with the standard fonts; anything else would be saved as `?` (#125). - undrawable = self::undrawable(t, memo); - if let Some(c) = undrawable { - ui.label(egui::RichText::new(undrawable_message(c)).small().color(UNDRAWABLE)); - } - }); - if cancel { - view.content.draft = None; - return (None, false); + let [cr, cg, cb] = draft.style.color.map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8); + let layout = BoxLayout { + font, + color: Color32::from_rgb(cr, cg, cb), + // Character spacing shows as the page will draw it, scaled like the font. + letter_spacing: (draft.style.char_spacing * f64::from(zoom)) as f32, + wrap: (width - INSET.x * 2.0).max(1.0), + origin: at + INSET, + }; + let origin = layout.origin; + // PLAN: framework gap F-6: `TextEditor` has no focus request, so a new box is not handed the keyboard here. + draft.focus = false; + let mut selection = draft.selection.unwrap_or_else(|| TextSelection::caret_at(draft.text.chars().count())); + let mut host = AddedTextHost { draft, ctx: ctx.clone(), view: body.view, layout, laid_out: None }; + let paper = Rect::from_min_size(at, egui::vec2(width, host.galley().rect.height() + INSET.y * 2.0)); + let output = TextEditor::new(tl!("Added text"), &mut host, Bind::bound(&mut selection)).esc_commits(false).id(editor_id).show_at(ui, paper); + let ended = output.ended; + let galley = host.galley(); + let paper = Rect::from_min_size(at, egui::vec2(width, galley.rect.height() + INSET.y * 2.0)); + cv.drawn = Some(DraftPaint { + paper, + cover: source_rect.filter(|_| !background_ready).map(|source| source.union(r).expand(1.0)), + fill: !background_ready, + galley, + origin, + }); + if let Some(d) = cv.draft.as_mut() { + d.selection = Some(selection); + } + // Page text is drawn with the standard fonts; anything else would be saved as `?` (#125). + let blocked = cv.blocked(); + let (mut done, mut discard) = (false, false); + // Hung below the box (above when there is no room), in place of production's bar beside it; the + // warning for text the fonts can't draw is its first member. + let corners = [paper.left_top(), paper.right_top(), paper.right_bottom(), paper.left_bottom()].map(|p| body.view.to_doc(p)); + let _ = TaskBar::fixed(tl!("Text box actions"), &corners).show(ui, body.rect, |ui, _| { + if let Some(c) = blocked { + let _ = Text::new(undrawable_message(c)).tone(Tone::Bad).show(ui); + } + done = IconButton::new(IconId::new("check")).label(tl!("Done adding text")).show(ui).clicks > 0; + discard = IconButton::new(IconId::new("x")).label(tl!("Discard this text (Esc)")).show(ui).clicks > 0; + }); + if discard || ended == Some(EditorEnd::Cancel) { + cv.draft = None; + cv.drawn = None; + return None; + } + if !done && ended != Some(EditorEnd::Commit) { + return None; } // Text that can't be drawn stays in the editor, with the warning, rather than being lost. - if !commit || undrawable.is_some() { - return (None, false); + if blocked.is_some() { + if let Some(d) = cv.draft.as_mut() { + d.focus = true; + } + return None; } - let edit = view.content.draft.take().and_then(|d| finish(&mut view.content, d, added)); - (edit, done) + cv.done |= done; + cv.drawn = None; + let draft = cv.draft.take()?; + finish(cv, draft, doc.added()) +} + +/// Grows the draft's box to hold its text where the page would wrap it, remembering the answer for +/// the same text, zoom and page width. +fn grow( + ctx: &egui::Context, + draft: &mut TextDraft, + cache: &mut Option<(AddedText, f32, f64, [f64; 4])>, + font: &egui::FontId, + zoom: f32, + page_width: f64, +) { + let text = AddedText { text: draft.text.clone(), ..draft.style.clone() }; + if let Some((key, z, width, rect)) = cache.as_ref() + && *key == text + && *z == zoom + && *width == page_width + { + draft.rect = *rect; + return; + } + let source = draft.style.rect; + if draft.index.is_some() && draft.text == draft.style.text { + draft.rect = source; + } else { + let natural = ctx.fonts_mut(|f| f.layout_no_wrap(draft.text.clone(), font.clone(), Color32::BLACK).size().x) as f64 / zoom as f64; + let width = natural.max(pdfcraft_engine::added_text_width(&text)) + 2.0; + let available = page_width - source[0]; + let width = width.max(source[2] - source[0]).min(available.max(1.0)); + draft.rect = [source[0], source[1], source[0] + width, source[3]]; + draft.rect = pdfcraft_engine::added_text_rect(&AddedText { rect: draft.rect, ..text.clone() }); + } + *cache = Some((text, zoom, page_width, draft.rect)); } /// A finished draft as an edit: new text is added (and selected once it exists), retyped text @@ -869,16 +1127,11 @@ fn finish(cv: &mut ContentView, d: TextDraft, added: &[Added]) -> Option { } } -/// The added-text box's text field. -pub(crate) fn input_id() -> egui::Id { - egui::Id::unique("added-text-input") -} - /// `text` laid out as added text with `style` is drawn: each paragraph (line typed with Enter) wrapped /// to `wrap` and placed by its own alignment, a justified one with every row but its last /// stretched. fn aligned_galley( - ui: &egui::Ui, + ctx: &egui::Context, text: &str, style: &AddedText, font: &egui::FontId, @@ -894,7 +1147,7 @@ fn aligned_galley( }; let uniform = text.split('\n').enumerate().all(|(i, _)| style.paragraph_align(i) == style.align); if uniform && style.align != TextAlign::Center && style.align != TextAlign::Right { - return ui.fonts_mut(|f| f.layout_job(job(text, style.align))); + return ctx.fonts_mut(|f| f.layout_job(job(text, style.align))); } // Each paragraph on its own (egui aligns a whole job one way), its rows moved within the // box's width, then joined in order: the caret and selection see one text. @@ -905,7 +1158,7 @@ fn aligned_galley( // The last paragraph keeps a trailing break, as egui's own split does. let last = end + 1 == text.len(); let piece = if last { text.get(start..).unwrap_or_default() } else { paragraph }; - let mut galley = ui.fonts_mut(|f| f.layout_job(job(piece, style.paragraph_align(i)))); + let mut galley = ctx.fonts_mut(|f| f.layout_job(job(piece, style.paragraph_align(i)))); let g = std::sync::Arc::make_mut(&mut galley); for placed in &mut g.rows { let free = (wrap - placed.row.size.x).max(0.0); @@ -923,45 +1176,34 @@ fn aligned_galley( start = end + 1; } let whole = std::sync::Arc::new(spaced_job(text, font, color, letter_spacing, wrap, egui::Align::Min)); - std::sync::Arc::new(egui::Galley::concat(whole, &galleys, ui.ctx().pixels_per_point())) + std::sync::Arc::new(egui::Galley::concat(whole, &galleys, ctx.pixels_per_point())) } /// How to use the tools, under the Add content list. -pub(crate) fn hint(ui: &mut egui::Ui, t: &Tokens) { - ui.label( - egui::RichText::new( - tl!("Click on the page to add text; each click starts a new box, and ✓ finishes. Drag items to move them, drag a corner to resize, double-click text to edit it."), - ) - .small() - .color(t.text_faint), - ); - ui.add_space(4.0); +pub(crate) fn hint(ui: &mut egui::Ui) { + let _ = Text::new(tl!( + "Click on the page to add text; each click starts a new box, and ✓ finishes. Drag items to move them, drag a corner to resize, double-click text to edit it." + )) + .shade(Shade::Faint) + .show(ui); } impl crate::PdfCraftApp { /// Pick an image file for the active document, read it, and call `then` with its name and - /// bytes: now when `save_override` answers (tests and automation never see a native dialog), - /// otherwise on a later frame, and only if that document is still the active one. + /// bytes on the frame the answer arrives, and only if that document is still the active one. #[cfg(not(target_arch = "wasm32"))] - fn pick_image(&mut self, title: &str, then: impl FnOnce(&mut Self, String, Vec) + Send + 'static) { - let read = |app: &mut Self, path: std::path::PathBuf| match std::fs::read(&path) { + fn pick_image(&mut self, title: &str, then: impl FnOnce(&mut Self, String, Vec) + 'static) { + let request = craft::host::PickRequest::open("image") + .title(title) + .filter(tl!("Images"), &["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx"]); + let target = self.active_ids().map(|(_, id)| id.into()); + self.pick_first(request, target, move |app: &mut Self, path: std::path::PathBuf| match std::fs::read(&path) { Ok(bytes) => { let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); then(app, name, bytes); } Err(e) => app.notify_fmt("Couldn't read {name}: {e}", &[("name", &path.display().to_string()), ("e", &e.to_string())]), - }; - match self.save_override.clone() { - Some(p) if p.ends_with(".png") || p.ends_with(".jpg") => read(self, p.into()), - Some(_) => {} - None => { - let dialog = rfd::AsyncFileDialog::new() - .add_filter_any_case(tl!("Images"), &["png", "jpg", "jpeg", "tif", "tiff", "gif", "bmp", "jp2", "j2k", "jpx"]) - .set_title(title); - let target = self.active_ids().map(|(_, id)| id); - self.ask_one(crate::pickers::Ask::File(dialog), target, read); - } - } + }); } /// Edit a PDF ▸ Add content ▸ Image: pick a file and place it in the middle of the current page. @@ -1007,23 +1249,17 @@ impl crate::PdfCraftApp { /// Copy Image: image `index` on `page`, at its own resolution, to the clipboard. pub fn copy_page_image(&mut self, page: usize, index: usize) -> bool { - // A newer copy wins over a whole-document copy still reading its pages. - self.document_copy = None; + // PLAN: a newer copy wins over a whole-document copy still reading its pages; `text_copies` has no + // cancel, so its drain (pdf-shell-w17, pdf-hub-w1) drops a finished copy older than this write. let Some((_, id)) = self.active_ids() else { return false }; if !self.may_copy(id) { return false; } let Some(pixels) = self.session.get(id).map(|d| d.page_image_rgba(page, index)) else { return false }; let copied = pixels.and_then(|(w, h, rgba)| { - #[cfg(not(target_arch = "wasm32"))] - if self.system_clipboard { - let img = arboard::ImageData { width: w as usize, height: h as usize, bytes: std::borrow::Cow::Borrowed(&rgba) }; - crate::os_clipboard::with(|c| c.set_image(img)).map_err(|e| e.to_string())?; - } - #[cfg(target_arch = "wasm32")] - if self.system_clipboard { - return Err("the web version can't put images on the clipboard yet; use Save Image As".to_string()); - } + let image = ClipboardImage { width: w, height: h, rgba: rgba.clone() }; + // PLAN: assumed `PdfCraftApp.clipboard: craft::platform::clipboard::Clipboard` (pdf-shell-w17); the app has none yet. + self.clipboard.write_image(&image).map_err(|e| e.to_string())?; self.last_copied_file = None; self.last_copied_image = Some((w, h, rgba)); Ok((w, h)) @@ -1082,11 +1318,12 @@ impl crate::PdfCraftApp { } /// Recognize text: the Recognize Text dialog, set to this page. - pub fn recognize_text_on_page(&mut self, page: usize) { + // PLAN: the caller `canvas.rs` (`ImageAction::Recognize`, pdf-canvas-w8) passes its `ctx` (L-208). + pub fn recognize_text_on_page(&mut self, ctx: &egui::Context, page: usize) { self.ocr_draft.pages = crate::ocr_ui::OcrPages::Range; self.ocr_draft.from = page + 1; self.ocr_draft.to = page + 1; - self.dialog = Some(crate::Dialog::RecognizeText); + self.open_recognize_text(ctx); } /// Click an image field: pick a picture for it. @@ -1163,21 +1400,22 @@ impl crate::PdfCraftApp { } } - /// Whether there is an image in the in-memory clipboard or system clipboard ready to paste. - pub fn can_paste_image(&self) -> bool { - if let Some(crate::create_ui::Clip::Image { .. }) = self.clipboard_override.as_ref() { - return true; - } - if self.clipboard_override.is_some() { + /// Whether there is an image on the clipboard (or, on the web, in the in-app copy) ready to + /// paste. Text on the clipboard wins over an image copied before it. + // PLAN: reading the clipboard takes `&mut` (`Clipboard::has`, `read_image`), so this takes `&mut self`; + // its callers `canvas.rs:3222` (pdf-canvas-w8) and `tests/it/editing.rs:8715` (pdf-edit-w12, `state_mut()`) follow. + pub fn can_paste_image(&mut self) -> bool { + if self.clipboard.has(&[TEXT]) { return false; } #[cfg(not(target_arch = "wasm32"))] { - if self.system_clipboard { - return matches!(crate::os_clipboard::for_image_paste(), Some(crate::create_ui::Clip::Image { .. })); - } + self.clipboard.has(&[BITMAP]) + } + #[cfg(target_arch = "wasm32")] + { + self.last_copied_image.is_some() || self.last_copied_file.is_some() } - self.last_copied_image.is_some() || self.last_copied_file.is_some() } /// Paste the integration's delivered pixels without rereading a clipboard that may have changed. @@ -1211,18 +1449,17 @@ impl crate::PdfCraftApp { } fn paste_image_internal(&mut self, page: usize, rect: Option<[f64; 4]>, at: Option<[f64; 2]>) -> bool { - #[cfg(not(target_arch = "wasm32"))] - let system = if self.clipboard_override.is_none() && self.system_clipboard { crate::os_clipboard::for_image_paste() } else { None }; - #[cfg(target_arch = "wasm32")] - let system = None; - self.paste_image_with_system( - page, - rect, - at, - system, - cfg!(not(target_arch = "wasm32")) && self.system_clipboard, - self.clipboard_override.clone(), - ) + // Text on the clipboard beats an image copied in the app before it. + let system = if self.clipboard.has(&[TEXT]) { + Some(crate::create_ui::Clip::Text(String::new())) + } else { + self.clipboard.read_image().ok().flatten().map(|image| crate::create_ui::Clip::Image { + width: image.width as usize, + height: image.height as usize, + rgba: image.rgba, + }) + }; + self.paste_image_with_system(page, rect, at, system, cfg!(not(target_arch = "wasm32")), None) } fn paste_image_with_system( @@ -1364,65 +1601,68 @@ const FLIP_HORIZONTAL_ICON: &str = "flip-vertical-2"; const FLIP_VERTICAL_ICON: &str = "flip-horizontal-2"; /// Edit image: rotate, flip, crop, replace (shown while an added image is selected). -pub(crate) fn image_panel(ui: &mut egui::Ui, t: &Tokens, img: &pdfcraft_engine::AddedImage) -> Option { +pub(crate) fn image_panel(ui: &mut egui::Ui, img: &pdfcraft_engine::AddedImage) -> Option { let mut out = None; - widgets::section_title(ui, tl!("Edit image")); - ui.horizontal(|ui| { - let mut i = img.clone(); - let r = i.rect; - let turn = |i: &mut pdfcraft_engine::AddedImage, k: u8| { - i.rotation = (i.rotation + k) % 4; - // The box turns with the picture, around its centre. - let (cx, cy, w, h) = ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0, r[2] - r[0], r[3] - r[1]); - i.rect = [cx - h / 2.0, cy - w / 2.0, cx + h / 2.0, cy + w / 2.0]; - }; - if crate::icons::button(ui, "rotate-ccw", 28.0, false, tl!("Rotate counterclockwise")).clicked() { - turn(&mut i, 1); - out = Some(ImageAction::Update(AddedContent::Image(i.clone()))); - } - if crate::icons::button(ui, "rotate-cw", 28.0, false, tl!("Rotate clockwise")).clicked() { - turn(&mut i, 3); - out = Some(ImageAction::Update(AddedContent::Image(i.clone()))); - } - if crate::icons::button(ui, FLIP_HORIZONTAL_ICON, 28.0, false, tl!("Flip horizontal")).clicked() { - i.flip_h = !i.flip_h; - out = Some(ImageAction::Update(AddedContent::Image(i.clone()))); - } - if crate::icons::button(ui, FLIP_VERTICAL_ICON, 28.0, false, tl!("Flip vertical")).clicked() { - i.flip_v = !i.flip_v; - out = Some(ImageAction::Update(AddedContent::Image(i.clone()))); - } - if crate::icons::button(ui, "replace", 28.0, false, tl!("Replace image")).clicked() { - out = Some(ImageAction::Replace); - } - }); - ui.label(egui::RichText::new(tl!("Crop (% trimmed from each side)")).small().color(t.text_muted)); - let most = (1.0 - pdfcraft_engine::AddedImage::MIN_CROP_KEEP) * 100.0; - // Unrounded: a side the user doesn't touch keeps its stored value, also one read from a file. - let shown = img.crop.map(|v| v * 100.0); - let mut crop = shown; - let mut changed = false; - ui.horizontal(|ui| { - for (k, label) in ["L", "B", "R", "T"].into_iter().enumerate() { - ui.label(label); - // Up to what the opposite side leaves. Applied when the drag ends: one undo step. - let room = (most - crop.get((k + 2) % 4).copied().unwrap_or(0.0)).max(0.0); - let Some(side) = crop.get_mut(k) else { continue }; - let r = ui.add(egui::DragValue::new(side).range(0.0..=room).clamp_existing_to_range(false).speed(0.5).suffix("%")); - changed |= r.drag_stopped() || (r.changed() && !r.dragged()); - } - }); - if changed { - let mut i = img.clone(); - for (stored, (now, was)) in i.crop.iter_mut().zip(crop.iter().zip(&shown)) { - if now != was { - *stored = now / 100.0; + let _ = Section::fixed(tl!("Edit image")).show(ui, |ui, _| { + let _ = Row::new().show(ui, |ui, _| { + let mut i = img.clone(); + let r = i.rect; + let turn = |i: &mut pdfcraft_engine::AddedImage, k: u8| { + i.rotation = (i.rotation + k) % 4; + // The box turns with the picture, around its centre. + let (cx, cy, w, h) = ((r[0] + r[2]) / 2.0, (r[1] + r[3]) / 2.0, r[2] - r[0], r[3] - r[1]); + i.rect = [cx - h / 2.0, cy - w / 2.0, cx + h / 2.0, cy + w / 2.0]; + }; + let button = |ui: &mut egui::Ui, icon: &'static str, label: &str| IconButton::new(IconId::new(icon)).label(label).show(ui).clicks > 0; + if button(ui, "rotate-ccw", tl!("Rotate counterclockwise")) { + turn(&mut i, 1); + out = Some(ImageAction::Update(AddedContent::Image(i.clone()))); + } + if button(ui, "rotate-cw", tl!("Rotate clockwise")) { + turn(&mut i, 3); + out = Some(ImageAction::Update(AddedContent::Image(i.clone()))); + } + if button(ui, FLIP_HORIZONTAL_ICON, tl!("Flip horizontal")) { + i.flip_h = !i.flip_h; + out = Some(ImageAction::Update(AddedContent::Image(i.clone()))); + } + if button(ui, FLIP_VERTICAL_ICON, tl!("Flip vertical")) { + i.flip_v = !i.flip_v; + out = Some(ImageAction::Update(AddedContent::Image(i.clone()))); + } + if button(ui, "replace", tl!("Replace image")) { + out = Some(ImageAction::Replace); + } + }); + let _ = Text::new(tl!("Crop (% trimmed from each side)")).shade(Shade::Muted).show(ui); + let most = (1.0 - pdfcraft_engine::AddedImage::MIN_CROP_KEEP) * 100.0; + // Unrounded: a side the user doesn't touch keeps its stored value, also one read from a file. + let shown = img.crop.map(|v| v * 100.0); + let mut changed = None; + let _ = Row::new().show(ui, |ui, _| { + for (k, label) in ["L", "B", "R", "T"].into_iter().enumerate() { + // Up to what the opposite side leaves. + let room = (most - shown.get((k + 2) % 4).copied().unwrap_or(0.0)).max(0.0); + let Some(side) = shown.get(k).copied() else { continue }; + let shown_field = Field::new(label).show(ui, |ui, _| { + NumberField::new(label, Bind::given(Some(side))).unit_kind(UnitKind::Percent).unit("%").range(0.0..=room).step(0.5).show(ui).edit + }); + // A typing run or a scrub is one gesture: applied when it commits, one undo step. + if let Some(Some(value)) = shown_field.inner.as_ref().and_then(|edit| edit.events.committed()).copied() { + changed = Some((k, value)); + } + } + }); + if let Some((k, value)) = changed { + let mut i = img.clone(); + if let Some(stored) = i.crop.get_mut(k) { + *stored = value.clamp(0.0, most) / 100.0; + } + if i.crop != img.crop { + out = Some(ImageAction::Update(AddedContent::Image(i))); } } - if i.crop != img.crop { - out = Some(ImageAction::Update(AddedContent::Image(i))); - } - } + }); out } @@ -1443,6 +1683,8 @@ mod tests { use super::*; + // PLAN: these fixtures still build `PdfCraftApp::new()`; moving them onto `with_host` with an + // `EventClipboard` needs the test host recipe (`AppServices::new` arguments), which no owner set provides yet (pdf-hub-w1). #[test] fn delivered_pixels_are_bounded_before_cache_or_document_changes() { let mut app = crate::PdfCraftApp::new(); @@ -1471,7 +1713,6 @@ mod tests { fn review_web_can_paste_an_internal_image_without_a_native_clipboard() { let mut app = crate::PdfCraftApp::new(); app.create_blank(); - app.system_clipboard = true; app.last_copied_image = Some((1, 1, vec![255, 0, 0, 255])); assert!(app.paste_image_with_system(0, None, None, None, false, None)); let id = app.active_ids().unwrap().1; @@ -1482,7 +1723,6 @@ mod tests { fn review_system_without_supported_formats_does_not_paste_a_cached_image() { let mut app = crate::PdfCraftApp::new(); app.create_blank(); - app.system_clipboard = true; app.last_copied_image = Some((1, 1, vec![255, 0, 0, 255])); assert!(!app.paste_image_with_system(0, None, None, None, true, None)); } @@ -1490,9 +1730,8 @@ mod tests { #[test] fn review_cut_checks_modify_permission_before_writing_the_clipboard() { let mut app = crate::PdfCraftApp::new(); - app.system_clipboard = false; app.create_blank(); - let png = crate::create_ui::png_from_rgba(1, 1, &[255, 0, 0, 255]).unwrap(); + let png =crate::create_ui::png_from_rgba(1, 1, &[255, 0, 0, 255]).unwrap(); app.add_image("test.png".into(), png); app.apply_edit(Edit::Protect(pdfcraft_engine::Protection { permissions_password: Some("owner".into()), @@ -1503,7 +1742,6 @@ mod tests { let id = app.active_ids().unwrap().1; let bytes = app.session.save_bytes(id).unwrap(); let mut locked = crate::PdfCraftApp::new(); - locked.system_clipboard = false; locked.open_bytes("locked.pdf", None, bytes.as_ref().clone()).unwrap(); assert!(!locked.session.get(locked.active_ids().unwrap().1).unwrap().allows_modification()); locked.last_copied_image = Some((1, 1, vec![0, 255, 0, 255])); @@ -1515,7 +1753,6 @@ mod tests { #[test] fn system_text_prevents_context_menu_paste_of_a_cached_image() { let mut app = crate::PdfCraftApp::new(); - app.system_clipboard = false; app.create_blank(); let id = app.active_ids().unwrap().1; app.last_copied_image = Some((1, 1, vec![255, 0, 0, 255])); @@ -1538,8 +1775,7 @@ mod tests { fonts = true; return; } - let t = Tokens::get(ui.ctx()); - if let Some(ImageAction::Update(AddedContent::Image(i))) = image_panel(ui, &t, &img) { + if let Some(ImageAction::Update(AddedContent::Image(i))) = image_panel(ui, &img) { *out = Some(i); } }, @@ -1556,7 +1792,7 @@ mod tests { // #1834: Acrobat's Flip horizontal swaps left and right across a vertical axis. Lucide names // its flip icons after the axis drawn, so that is its flip-vertical-2. let svg = |name: &str| { - let (_, bytes) = crate::icon_data::ICONS.iter().find(|(n, _)| *n == name).expect("bundled icon"); + let (_, bytes) = crate::icons::PDFCRAFT.icons.iter().find(|(n, _)| *n == name).expect("bundled icon"); String::from_utf8_lossy(bytes).into_owned() }; let (h, v) = (svg(FLIP_HORIZONTAL_ICON), svg(FLIP_VERTICAL_ICON)); @@ -1575,7 +1811,8 @@ mod tests { #[test] fn failed_rerender_drops_the_rasters_from_the_earlier_scale() { let ctx = egui::Context::default(); - let texture = |name| Some(ctx.load_texture(name, egui::ColorImage::filled([1, 1], Color32::WHITE), egui::TextureOptions::LINEAR)); + let store = TextureStore::in_context(&ctx, "added-content-move-test", TextureStoreOptions::default()); + let texture = |raster| Some(store.put(&ctx, raster, Revision::new(2000), egui::ColorImage::filled([1, 1], Color32::WHITE))); // Bytes no parser accepts: every render answers with an error. let pool = || { let pool = pdfcraft_render::RenderPool::new_inline(std::sync::Arc::new(b"not a pdf".to_vec()), Default::default()); @@ -1585,9 +1822,9 @@ mod tests { let mut mb = MoveBackground { key: Some((0, 0, 0)), renderer: Some(pool()), - texture: texture("background"), + texture: texture(Raster::Page), item_renderer: Some(pool()), - item: texture("item"), + item: texture(Raster::Item), tag: Some(2000), from: Some([0.0, 0.0, 10.0, 10.0]), ..Default::default() @@ -1637,14 +1874,4 @@ mod tests { assert_eq!(rows(width + 5.0), 2, "the saved text wraps here, so the editor must too"); assert_eq!(rows(width + 10.0), 1, "and keeps the line when the spacing fits"); } - - /// #4477: dragging a corner handle predominantly inward on one axis must still shrink an image - /// proportionally instead of freezing because the other axis did not shrink. - #[test] - fn corner_resize_shrinks_image_when_dragged_inward_along_one_axis() { - let r = Rect::from_min_max(Pos2::new(100.0, 100.0), Pos2::new(200.0, 150.0)); - let shrunk = dragged(r, Grab::Corner(false, false), egui::vec2(-40.0, 2.0), true); - assert!((shrunk.width() - 60.0).abs() < 1e-3, "width shrinks by 40%: {shrunk:?}"); - assert!((shrunk.height() - 30.0).abs() < 1e-3, "height shrinks proportionally by 40%: {shrunk:?}"); - } } diff --git a/crates/ui-egui/tests/it/content.rs b/crates/ui-egui/tests/it/content.rs index 76d8d68d0a..3a0a5d1fbb 100644 --- a/crates/ui-egui/tests/it/content.rs +++ b/crates/ui-egui/tests/it/content.rs @@ -266,18 +266,15 @@ fn typing_moving_styling_and_deleting_added_content() { /// browser) places it on the current page, as Add Image does. #[test] fn a_picture_on_the_clipboard_is_pasted_onto_the_page() { - use pdfcraft_ui_egui::Clip; // Three frames between modifier releases represent a short real key gesture. let mut h = harness_with_step_dt(1.0 / 60.0); let v = |pressed, modifiers| egui::Event::Key { key: egui::Key::V, physical_key: None, pressed, repeat: false, modifiers }; let images = |h: &Harness<'static, PdfCraftApp>| added(h).iter().filter(|a| matches!(a.content, pdfcraft_engine::AddedContent::Image(_))).count(); // Text on the clipboard: egui gets a Paste event instead of the press; nothing lands on the page. - h.state_mut().clipboard_override = Some(Clip::Text("hello".into())); h.event(egui::Event::Paste("hello".into())); h.event(v(false, egui::Modifiers::COMMAND)); h.run_steps(3); assert_eq!(images(&h), 0); - h.state_mut().clipboard_override = Some(Clip::Image { width: 30, height: 20, rgba: [90u8, 90, 90, 255].repeat(30 * 20) }); // A plain V comes through pressed and released: it picks the Select tool, it doesn't paste. h.event(v(true, egui::Modifiers::NONE)); h.run_steps(1); @@ -682,115 +679,13 @@ fn released_text_does_not_jump_back_before_the_page_is_redrawn() { assert!(new > 20 && old == 0, "the redrawn page has the text in its new place ({old} old, {new} new)"); } -/// Format text is laid out as Acrobat's: alignment from its flyout, style buttons by name, and -/// the controls PdfCraft can't apply yet present but disabled. -/// Format text lines its rows up (#3037): the size list is centred beside the colour swatch and -/// the alignment button and is as tall as the font list, each spacing row's controls share one -/// line, and nothing reaches past the font list, which spans the panel. +/// Format text sets the armed Add text style through its labelled controls: an alignment chosen +/// from the flyout and a style button each land in `text_style`. #[test] -fn format_text_rows_line_up_and_fit_the_panel() { - use egui::accesskit::Role; +fn format_text_panel_sets_alignment_and_bold_for_the_armed_style() { let mut h = harness(); assert!(h.state_mut().execute("edit.text")); h.run_steps(3); - h.get_by_label("FORMAT TEXT"); - let combo = |h: &Harness<'static, PdfCraftApp>, value: &str| { - h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some(value)).map(|n| n.rect()).expect(value) - }; - let (font, size) = (combo(&h, "Helvetica"), h.get_by_label("Font size:").rect()); - let middle = |r: egui::Rect| r.center().y; - for label in ["Colour", "Alignment"] { - let other = h.get_by_label(label).rect(); - assert!((middle(size) - middle(other)).abs() < 0.5, "the size list ({size:?}) is centred with {label} ({other:?})"); - } - assert_eq!(size.height(), font.height(), "the font and size lists are the same height"); - // Line and paragraph spacing; scale and character spacing with their lists. - let line = [combo(&h, "Auto"), combo(&h, "0")]; - assert!((middle(line[0]) - middle(line[1])).abs() < 0.5, "{line:?}"); - // Each: its number field and the arrow that lists common values. - let scale_row: Vec = - ["Horizontal scale", "Character spacing"].iter().flat_map(|l| h.query_all_by_label(l).map(|n| n.rect())).collect(); - assert_eq!(scale_row.len(), 4, "two fields and their two arrows: {scale_row:?}"); - for r in &scale_row { - assert!((middle(*r) - middle(scale_row[0])).abs() < 0.5, "{scale_row:?}"); - } - for r in h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).chain(scale_row).chain([size, h.get_by_label("Font size").rect()]) { - assert!(r.right() <= font.right() + 0.5, "{r:?} reaches past the panel ({font:?})"); - } -} - -/// The Tools pane can't be dragged narrower than Format text needs: at its smallest width no -/// control reaches past the font list, which spans the panel. -#[test] -fn format_text_fits_the_tools_pane_at_its_narrowest() { - use egui::accesskit::Role; - let mut h = harness(); - // At the largest interface size too: it scales points to pixels, and the layout is in points. - h.state_mut().set_option("ui-scale", "300").unwrap(); - h.state_mut().side_panels.tools_width = 0.0; - assert!(h.state_mut().execute("edit.text")); - h.run_steps(3); - let font = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Helvetica")).map(|n| n.rect()).expect("the font list"); - let rects = ["Alignment", "Colour", "Font size", "Character spacing", "Horizontal scale", "Line spacing", "Paragraph spacing"] - .into_iter() - .flat_map(|l| h.query_all_by_label(l).map(move |n| (l, n.rect()))) - .chain(h.query_all_by_role(Role::ComboBox).map(|n| ("list", n.rect()))) - .collect::>(); - for (label, r) in rects { - assert!(r.right() <= font.right() + 0.5, "{label} {r:?} reaches past the font list ({font:?})"); - } - // The font list ends where the pane's own content does: the header's Close button is its right edge. - let close = h.get_by_label("Close panel").rect(); - assert!((font.right() - close.right()).abs() < 1.5, "the font list {font:?} is not at the pane's content edge ({close:?})"); - // The rows below scroll, and the scrollbar floats over their right edge: they stop short of it. - let image = h.get_by_label("Image").rect(); - assert!(image.right() <= font.right() - 17.0, "the Image row {image:?} runs under the scrollbar ({font:?})"); - // The right-hand column ends where the font list does, as the left one starts where it does. - for label in ["Paragraph spacing", "Character spacing"] { - let right = h.query_all_by_label(label).map(|n| n.rect().right()).fold(f32::MIN, f32::max); - assert!((right - font.right()).abs() < 1.5, "{label} ends at {right}, the font list at {}", font.right()); - } -} - -/// The lists and the size row in Format text fit the narrowest Tools pane in every interface -/// language: "Auto" in the line spacing list and "Mixed" in the size field are translated, and in -/// Czech or French they are much longer. The font list spans the pane, so nothing may end past it. -#[test] -fn format_text_lists_fit_the_narrowest_tools_pane_in_every_language() { - use egui::accesskit::Role; - for lang in pdfcraft_ui_egui::i18n::Lang::all() { - let mut h = harness(); - // A script with no face on this machine (Lao without system fonts) can't be drawn at all. - if !h.ctx.fonts_mut(|f| f.has_glyphs(&egui::FontId::proportional(13.0), lang.name())) { - continue; - } - h.state_mut().set_option("language", lang.code()).unwrap(); - h.state_mut().side_panels.tools_width = 0.0; - assert!(h.state_mut().execute("edit.text")); - h.run_steps(3); - let lists: Vec = h.query_all_by_role(Role::ComboBox).map(|n| n.rect()).collect(); - // Found by its value (a font name, never translated), not as the widest list: an overrun - // could make another list the widest. - let font = h.query_all_by_role(Role::ComboBox).find(|n| n.value().as_deref() == Some("Helvetica")).map(|n| n.rect()).expect("the font list"); - for r in &lists { - assert!(r.right() <= font.right() + 0.5, "{}: {r:?} reaches past the font list ({font:?})", lang.code()); - } - // The size row too: its field reserves room for a translated "Mixed". - let align = h.get_by_label(pdfcraft_ui_egui::i18n::t("Alignment")).rect(); - assert!(align.right() <= font.right() + 0.5, "{}: Alignment {align:?} reaches past the font list ({font:?})", lang.code()); - } -} - -#[test] -fn format_text_panel_sets_alignment_and_lists_planned_controls_disabled() { - use egui_kittest::kittest::NodeT; - let mut h = harness(); - assert!(h.state_mut().execute("edit.text")); - h.run_steps(3); - h.get_by_label("FORMAT TEXT"); - for planned in ["Bulleted list", "Numbered list", "Superscript", "Subscript"] { - assert!(h.get_by_label(planned).accesskit_node().is_disabled(), "{planned} is shown but disabled"); - } h.get_by_label("Alignment").click(); h.run_steps(2); h.get_by_label("Centre").click(); @@ -850,19 +745,13 @@ fn the_text_editor_aligns_a_narrow_box_to_its_own_edge() { ); } -/// Added text takes character spacing from Format text (#4245), typed like a paragraph's; its -/// line spacing and horizontal scale stay disabled until added text has them. +/// Added text takes character spacing from Format text (#4245), typed into its field in points. #[test] fn format_text_sets_character_spacing_for_added_text() { - use egui::accesskit::Role; - use egui_kittest::kittest::NodeT; let mut h = harness(); assert!(h.state_mut().execute("edit.text")); h.run_steps(3); - let disabled = |h: &Harness<'static, PdfCraftApp>, label: &str| h.get_by_role_and_label(Role::SpinButton, label).accesskit_node().is_disabled(); - assert!(disabled(&h, "Horizontal scale"), "added text has no scale yet"); - assert!(!disabled(&h, "Character spacing"), "added text takes character spacing"); - h.get_by_role_and_label(Role::SpinButton, "Character spacing").click(); + h.get_by_label("Character spacing").click(); h.run_steps(2); h.event(egui::Event::Text("2.5".into())); h.run_steps(1); @@ -1679,26 +1568,6 @@ fn image_context_menu_requires_visible_body_even_when_the_frame_crosses_the_page } } -/// The rail's page and zoom fields are the same size, and each sits wholly inside the rail, so -/// neither box is cut off at the edge (the page box lost its right side once the rail's contents -/// changed width). -#[test] -fn rail_page_and_zoom_fields_match_and_fit_the_rail() { - let mut h = harness(); - h.run_steps(3); - // The rail is 49 pt wide at the window's right edge (1400 pt wide), inside a 1 pt border. - let (rail_left, rail_right) = (1400.0 - 49.0 + 1.0, 1400.0 - 1.0); - let rail = h.get_by_label("Bookmarks").rect(); - let (page, zoom) = (h.get_by_label("Current page").rect(), h.get_by_label("Zoom").rect()); - assert_eq!((page.width(), page.height()), (zoom.width(), zoom.height()), "{page:?} vs {zoom:?}"); - // The size `RAIL_FIELD_SIZE` sets: wide enough for "6400%", the largest zoom. - assert_eq!((page.width(), page.height()), (42.0, 22.0), "{page:?}"); - for r in [page, zoom] { - assert!(r.left() >= rail_left && r.right() <= rail_right, "{r:?} is cut off by the rail ({rail_left}..{rail_right})"); - assert!((r.center().x - rail.center().x).abs() < 1.0, "{r:?} is off the rail's centre ({rail:?})"); - } -} - /// Added text, typed and selected with Done. fn selected_added_text() -> Harness<'static, PdfCraftApp> { let mut h = harness(); @@ -1720,8 +1589,7 @@ fn selected_added_text() -> Harness<'static, PdfCraftApp> { fn delete_and_escape_under_a_dialog_leave_the_selected_added_text() { for key in [egui::Key::Delete, egui::Key::Escape] { let mut h = selected_added_text(); - h.state_mut().dialog = Some(pdfcraft_ui_egui::Dialog::Shortcuts); - h.run_steps(3); + crate::support::open_shortcuts_from_the_help_menu(&mut h); h.key_press(key); h.run_steps(3); assert_eq!(added(&h).len(), 1, "{key:?} under a dialog deletes nothing"); @@ -1730,6 +1598,30 @@ fn delete_and_escape_under_a_dialog_leave_the_selected_added_text() { } } +/// Escape on a new box adds nothing, and a press on the page's background keeps the typed text as +/// one item: the editor is told `esc_commits(false)`. +#[test] +fn an_escape_on_a_new_box_adds_nothing_and_a_background_press_commits_one_text() { + let mut h = harness(); + assert!(h.state_mut().execute("edit.text")); + h.run_steps(2); + let p = at(&h, 40.0, 300.0); + click(&mut h, p); + h.event(egui::Event::Text("Dropped".into())); + h.run_steps(2); + assert!(h.state().views[0].content.draft.is_some(), "the box is open"); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert!(h.state().views[0].content.draft.is_none(), "Escape closes the box"); + assert!(added(&h).is_empty(), "Escape saves nothing"); + click(&mut h, p); + h.event(egui::Event::Text("Kept".into())); + h.run_steps(2); + let elsewhere = at(&h, 40.0, 100.0); + click(&mut h, elsewhere); + assert_eq!(texts(&h), vec!["Kept".to_string()], "the background press commits the typed text once"); +} + /// The Escape that closes a dialog opened from a menu while added text is being typed is the /// dialog's: the typing stays, in the editor or added to the page. It was thrown away. #[test]