diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 42daecd2ba..84d4ce702f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -41,6 +41,7 @@ pub mod js; mod layers; pub mod links; mod live_scripts; +mod mark_picture; pub mod model3d; mod object_clip; pub mod ocr; @@ -81,6 +82,7 @@ pub use links::{ MAX_REMOTE_DOCUMENT_BYTES, RemoteDocumentPathError, read_remote_document, remote_document_path_is_absolute, resolve_remote_document_path, }; pub use live_scripts::{MAX_TIMER_RUNS, ScriptRun}; +pub use mark_picture::{MAX_MARK_PICTURE_SIDE, MarkPicture, mark_picture}; pub use pdfcraft_edit::strip_subset_tag; pub use rich_copy::RichCopy; pub use signature_image::{ImageSignaturePreview, SignatureImage}; diff --git a/crates/engine/src/mark_picture.rs b/crates/engine/src/mark_picture.rs new file mode 100644 index 0000000000..d104eed314 --- /dev/null +++ b/crates/engine/src/mark_picture.rs @@ -0,0 +1,175 @@ +//! The picture of a watermark or background taken from a file (Source ▸ File), for the dialogs' +//! preview: brought in the way OK brings it in, drawn alone on a page of its shape, and rendered +//! small, transparent where it draws nothing. + +use std::sync::Arc; + +use pdfcraft_cos::Object; +use pdfcraft_render::{PageRenderer, Pixels, RenderConfig, RenderRequest, RenderedPage, effective_scale}; + +use crate::{MarkFile, guard, mark_source}; + +/// The longest side [`mark_picture`] renders, in pixels, whatever it is asked for. +pub const MAX_MARK_PICTURE_SIDE: u32 = 2048; + +/// The longer side of the page the picture is drawn on, in points. Only its shape matters: the +/// picture is fitted to it, as a mark is fitted to the page it goes on. +const SHEET: f64 = 1000.0; + +/// A mark's picture, as [`mark_picture`] renders it. +#[derive(Clone, Debug, PartialEq)] +pub struct MarkPicture { + /// The picture's size in points, which a watermark or background fits to the page at its + /// scale (`picture` in `pdfcraft-edit`). + pub size: (f64, f64), + /// The raster's size in pixels. + pub width: u32, + pub height: u32, + /// Premultiplied RGBA8, row-major: transparent where the picture draws nothing. + pub rgba: Pixels, +} + +/// Render the picture `f` adds as a watermark or background, its longer side `max_side` pixels +/// (at most [`MAX_MARK_PICTURE_SIDE`]). It is brought in as OK brings it in (an image turned +/// upright by its EXIF orientation, a page of a PDF as a form, upright), so a file OK refuses is +/// refused here too. Never panics. +pub fn mark_picture(f: &MarkFile, max_side: u32) -> Result { + guard(|| render(f, max_side))? +} + +fn render(f: &MarkFile, max_side: u32) -> Result { + // Two pages of the picture's shape: the picture alone, on the renderer's white paper, and + // the picture over black. Between them they give its transparency. + let mut doc = pdfcraft_create::blank(SHEET, SHEET, 2).map_err(|e| e.to_string())?; + let src = mark_source(&mut doc, f).map_err(|e| e.to_string())?; + let (w, h) = src.size; + if !(w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0) { + return Err(format!("{}: the picture has no size", f.name)); + } + let k = SHEET / w.max(h); + let (pw, ph) = ((w * k).max(1.0), (h * k).max(1.0)); + let media = Object::Array(vec![0.into(), 0.into(), Object::Real(pw), Object::Real(ph)]); + for page in pdfcraft_model::pages(&doc) { + doc.update_dict(page.obj, |d| d.set(b"MediaBox".to_vec(), media.clone())).map_err(|e| e.to_string())?; + } + let black = pdfcraft_edit::Background { color: [0.0; 3], opacity: 1.0, source: None, scale: 1.0, replace_backdrop: false }; + pdfcraft_edit::add_background(&mut doc, &[1], &black, false).map_err(|e| e.to_string())?; + let whole = pdfcraft_edit::Watermark { source: Some(src), scale: 1.0, opacity: 1.0, rotation: 0.0, ..Default::default() }; + pdfcraft_edit::add_watermark(&mut doc, &[0, 1], &whole, false).map_err(|e| e.to_string())?; + let bytes = Arc::new(pdfcraft_cos::write_full(&doc, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())?); + + let side = max_side.clamp(1, MAX_MARK_PICTURE_SIDE) as f32; + let scale = effective_scale(pw as f32, ph as f32, side / pw.max(ph) as f32); + let mut renderer = PageRenderer::new(bytes, RenderConfig::default()); + let mut page = |n: usize| -> Result { + let out = renderer.render(RenderRequest { page: n, scale, ..Default::default() }); + match out.error { + Some(e) => Err(e), + None => Ok(out), + } + }; + let (on_white, on_black) = (page(0)?, page(1)?); + if (on_white.width, on_white.height) != (on_black.width, on_black.height) || on_white.rgba.len() != on_black.rgba.len() { + return Err("the picture rendered at two sizes".into()); + } + Ok(MarkPicture { size: src.size, width: on_black.width, height: on_black.height, rgba: unpaper(&on_white.rgba, &on_black.rgba) }) +} + +/// The picture with its transparency, from its renders on white and over black. Where it lets +/// `1 − a` of what is behind it through, it is that much lighter on white than over black, and +/// over black it is itself, premultiplied. +fn unpaper(on_white: &[u8], on_black: &[u8]) -> Pixels { + let (white, _) = on_white.as_chunks::<4>(); + let (black, _) = on_black.as_chunks::<4>(); + let words = white + .iter() + .zip(black) + .map(|(&[wr, wg, wb, _], &[br, bg, bb, _])| { + let a = 255 - wr.saturating_sub(br).max(wg.saturating_sub(bg)).max(wb.saturating_sub(bb)); + u32::from_ne_bytes([br.min(a), bg.min(a), bb.min(a), a]) + }) + .collect::>(); + Pixels::from(words) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn png(w: u32, h: u32, px: impl Fn(u32, u32) -> [u8; 4]) -> Vec { + let data: Vec = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| px(x, y)).collect(); + let img = craft_image_codecs::Image::from_u8(w, h, craft_image_codecs::ChannelLayout::Rgba, data).unwrap(); + craft_image_codecs::encode(&img, craft_image_codecs::Format::Png, &Default::default()).unwrap() + } + + fn file(name: &str, bytes: Vec, page: usize) -> MarkFile { + MarkFile { name: name.into(), bytes: Arc::new(bytes), page } + } + + /// The pixel at (`x`, `y`) of the picture, premultiplied RGBA. + fn at(p: &MarkPicture, x: u32, y: u32) -> [u8; 4] { + let i = (y * p.width + x) as usize * 4; + p.rgba[i..i + 4].try_into().unwrap() + } + + #[test] + fn an_image_keeps_its_size_colours_and_transparency() { + // 40 × 20 pixels: opaque red on the left, nothing on the right. + let bytes = png(40, 20, |x, _| if x < 20 { [255, 0, 0, 255] } else { [0, 0, 0, 0] }); + let p = mark_picture(&file("half.png", bytes, 0), 80).unwrap(); + assert_eq!(p.size, (40.0, 20.0), "40 × 20 px at 72 dpi, as OK lays it out"); + assert_eq!((p.width, p.height), (80, 40)); + assert_eq!(at(&p, 10, 20), [255, 0, 0, 255], "the red half is opaque red"); + assert_eq!(at(&p, 70, 20), [0, 0, 0, 0], "the empty half lets the page through"); + } + + #[test] + fn a_pdf_page_is_transparent_where_it_draws_nothing_and_upright() { + // 200 × 100, turned a quarter (/Rotate 90): shown 100 wide and 200 tall. A white box + // on the left half of the unturned page, nothing on the right. + let content = "1 1 1 rg 0 0 100 100 re f"; + let pdf = format!( + "%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Rotate 90 /Contents 4 0 R >> endobj +4 0 obj << /Length {} >> +stream +{content} +endstream +endobj +trailer << /Root 1 0 R >> +%%EOF", + content.len() + ); + let p = mark_picture(&file("stamp.pdf", pdf.clone().into_bytes(), 0), 100).unwrap(); + assert_eq!(p.size, (100.0, 200.0), "the page as displayed"); + assert_eq!((p.width, p.height), (50, 100)); + // Turned clockwise, the unturned left half is the top half. + assert_eq!(at(&p, 25, 25), [255, 255, 255, 255], "painted white stays opaque white"); + assert_eq!(at(&p, 25, 75), [0, 0, 0, 0], "what the page leaves unpainted is transparent"); + assert!(mark_picture(&file("stamp.pdf", pdf.into_bytes(), 3), 100).is_err(), "a page the file doesn't have"); + } + + #[test] + fn what_ok_refuses_is_refused_and_sizes_are_capped() { + assert!(mark_picture(&file("x.png", b"not an image".to_vec(), 0), 100).is_err()); + assert!(mark_picture(&file("x.png", Vec::new(), 0), 100).is_err()); + assert!(mark_picture(&file("x.pdf", b"%PDF-1.7 junk".to_vec(), 0), 100).is_err()); + let bytes = png(4, 2, |_, _| [0, 0, 255, 255]); + let p = mark_picture(&file("blue.png", bytes.clone(), 0), u32::MAX).unwrap(); + assert_eq!(p.width, MAX_MARK_PICTURE_SIDE); + let p = mark_picture(&file("blue.png", bytes, 0), 0).unwrap(); + assert_eq!((p.width, p.height), (1, 1)); + } + + #[test] + fn transparency_comes_from_the_two_backdrops() { + // Opaque white, nothing, half-transparent black, half-transparent red: (128, 0, 0, 128) + // premultiplied lets 127 of white through. + let white = [255, 255, 255, 255, 255, 255, 255, 255, 127, 127, 127, 255, 255, 127, 127, 255]; + let black = [255, 255, 255, 255, 0, 0, 0, 255, 0, 0, 0, 255, 128, 0, 0, 255]; + let px = unpaper(&white, &black); + assert_eq!(&px[..], &[255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 128, 128, 0, 0, 128]); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0bbc06d291..43d0a248ce 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4534,6 +4534,49 @@ fn update_previews_on_the_page_without_the_marks_it_replaces() { assert_eq!((doc.edit_generation(), doc.dirty, doc.can_undo()), (generation, dirty, Some("Add watermark")), "the document is unchanged"); } +/// A picture behind the page shows only where the page has nothing of its own: the pages on a +/// transparent sheet are clear where they are bare and opaque where they paint, with the marks an +/// Update replaces taken away and the others kept. +#[test] +fn the_pages_on_glass_are_clear_only_where_they_paint_nothing() { + let (mut s, id) = session_with(1); + let yellow = Background { color: [1.0, 1.0, 0.0], ..Background::default() }; + s.apply(id, Edit::AddBackground { pages: vec![0], settings: yellow, replace: false, file: None }).unwrap(); + let red = Watermark { text: "SECRET".into(), color: [1.0, 0.0, 0.0], opacity: 1.0, ..Watermark::default() }; + s.apply(id, Edit::AddWatermark { pages: vec![0], settings: red, replace: false, file: None }).unwrap(); + let doc = s.get(id).unwrap(); + let alpha = |p: &pdfcraft_render::RenderedPage, x: u32, y: u32| p.rgba[(((300 - y) * p.width + x) * 4 + 3) as usize]; + let opaque_reds = |p: &pdfcraft_render::RenderedPage| { + p.rgba.as_chunks::<4>().0.iter().filter(|[r, g, b, a]| *r > 200 && *g < 80 && *b < 80 && *a == 255).count() + }; + + let page = doc.pages_on_glass(Some(MarkKind::Background), false).unwrap().render_page(0, 1.0).unwrap(); + assert_eq!(alpha(&page, 5, 5), 0, "bare paper, the background taken away, is clear"); + assert!(opaque_reds(&page) > 50, "the watermark stays, opaque"); + + let page = doc.pages_on_glass(None, false).unwrap().render_page(0, 1.0).unwrap(); + assert_eq!(page.rgba[(((300 - 5) * page.width + 5) * 4) as usize..][..4], [255, 255, 0, 255], "kept, the background paints the page"); +} + +/// With the white backdrops a background replaces taken away, a page's own white fill goes +/// clear on the sheet, so the picture behind shows where OK shows it; kept, the fill stays. +#[test] +fn the_pages_on_glass_lose_the_white_backdrop_a_background_replaces() { + let mut s = Session::new(); + let id = s.open("a.pdf", None, Arc::new(backdrop_pdf(None)), None).unwrap(); + let doc = s.get(id).unwrap(); + let at = |p: &pdfcraft_render::RenderedPage, x: u32, y: u32| { + let i = (((p.height - 1 - y) * p.width + x) * 4) as usize; + [p.rgba[i], p.rgba[i + 1], p.rgba[i + 2], p.rgba[i + 3]] + }; + + let page = doc.pages_on_glass(Some(MarkKind::Background), true).unwrap().render_page(0, 1.0).unwrap(); + assert_eq!(at(&page, 5, 5)[3], 0, "the white backdrop is taken away: bare paper is clear"); + + let page = doc.pages_on_glass(Some(MarkKind::Background), false).unwrap().render_page(0, 1.0).unwrap(); + assert_eq!(at(&page, 5, 5), [255, 255, 255, 255], "kept, the white backdrop paints the page"); +} + /// #5785: Update of one header and footer previews the page without that one alone, so a second /// header and footer on the same page, which OK keeps, is still drawn in the preview. #[test] diff --git a/crates/engine/src/text_preview.rs b/crates/engine/src/text_preview.rs index c961de4532..c0dd1f6f47 100644 --- a/crates/engine/src/text_preview.rs +++ b/crates/engine/src/text_preview.rs @@ -210,6 +210,35 @@ impl Document { })? } + /// Every page on a transparent sheet, as a mark placed behind the page content would find + /// it: without the marks of `without` when it names a kind (what Update replaces), and with + /// the white backdrops a background replaces taken away when `replace_backdrops`. Clear + /// where a page paints nothing, so a preview can draw the mark over white paper and these + /// pages over it. Read-only, like [`Self::text_edit_preview`]. + pub fn pages_on_glass(&self, without: Option, replace_backdrops: bool) -> Result { + guard(|| { + let editor = self.editor.as_ref().ok_or("the document can't be read")?; + let mut cos = editor.cos.clone(); + let all: Vec = (0..pdfcraft_model::pages(&cos).len()).collect(); + if let Some(kind) = without { + pdfcraft_edit::remove_marks(&mut cos, &all, kind).map_err(|e| e.to_string())?; + } + if replace_backdrops { + // A background that paints nothing, added as OK adds one: the backdrops go the same way. + let clear = pdfcraft_edit::Background { opacity: 0.0, replace_backdrop: true, ..Default::default() }; + pdfcraft_edit::add_background(&mut cos, &all, &clear, false).map_err(|e| e.to_string())?; + } + let bytes = Arc::new(pdfcraft_cos::write_incremental(&cos, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())?); + Ok(UnmarkedPages { + bytes, + config: RenderConfig { transparent: true, ..self.config.clone() }, + parsed: None, + #[cfg(test)] + builds: 0, + }) + })? + } + /// An added item alone, on a transparent page: what follows the pointer while it is dragged, /// so the page under its first place doesn't come along. Read-only, like /// [`Self::added_content_preview`]. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 57b51c42de..e5784c0223 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -12,6 +12,7 @@ pub(super) mod convert_colours_ui; pub(crate) mod duplicate_field; pub(super) mod hairlines_ui; pub(crate) mod host; +pub(super) mod marks_picture; pub(super) mod marks_ui; pub(crate) mod page_dialogs; pub(crate) mod page_props; diff --git a/crates/ui-egui/src/dialogs/marks_picture.rs b/crates/ui-egui/src/dialogs/marks_picture.rs new file mode 100644 index 0000000000..9c5ec10852 --- /dev/null +++ b/crates/ui-egui/src/dialogs/marks_picture.rs @@ -0,0 +1,245 @@ +//! Source ▸ File's picture in the watermark and background preview: rendered off the UI thread +//! the way OK brings the file in ([`pdfcraft_engine::mark_picture`]), laid out where OK puts it, +//! and drawn on top of the page or behind it. + +use std::sync::{Arc, Mutex}; + +use craft::host::queue::{JobQueue, Priority}; +use egui::emath::Rot2; +use egui::{Color32, Rect, pos2, vec2}; +use pdfcraft_engine::{DocId, MarkKind, UnmarkedPages}; + +/// Pixels along the longer side of the picture as rendered for the preview, whose page is at +/// most 190 points across: sharp on a screen of more than twice that density. +pub(super) const PICTURE_SIDE: u32 = 512; + +/// The picture as the engine rendered it, checked: made on a job, uploaded on the UI thread. +pub(super) struct Rendered { + picture: pdfcraft_engine::MarkPicture, + pixels: [usize; 2], +} + +impl Rendered { + /// A raster that doesn't add up, or is larger than asked for, is refused, never uploaded. + pub(super) fn new(picture: pdfcraft_engine::MarkPicture) -> Result { + let [w, h] = [picture.width, picture.height].map(|v| v as usize); + // A pixel over for rounding. + let side = PICTURE_SIDE as usize + 1; + if w == 0 || h == 0 || w > side || h > side { + return Err(format!("the picture came back {w}×{h} pixels")); + } + if w.checked_mul(h).and_then(|n| n.checked_mul(4)) != Some(picture.rgba.len()) { + return Err("the picture came back incomplete".into()); + } + Ok(Self { picture, pixels: [w, h] }) + } +} + +/// The picture, uploaded. +#[derive(Clone)] +pub(super) struct Picture { + tex: egui::TextureHandle, + /// Its size in points, which OK fits to the page. + size: (f64, f64), +} + +impl Picture { + pub(super) fn upload(ctx: &egui::Context, r: Rendered) -> Self { + let image = crate::canvas::texture_image(r.pixels, r.picture.rgba); + let tex = ctx.load_texture("mark-file-picture", image, egui::TextureOptions::LINEAR); + Self { tex, size: r.picture.size } + } +} + +/// The file (by identity) and page (0-based) a picture is rendered for. +#[derive(Clone)] +pub(super) struct FileKey { + pub(super) bytes: Arc>, + pub(super) page: usize, +} + +impl PartialEq for FileKey { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.bytes, &other.bytes) && self.page == other.page + } +} + +impl Eq for FileKey {} + +impl std::hash::Hash for FileKey { + fn hash(&self, h: &mut H) { + Arc::as_ptr(&self.bytes).hash(h); + self.page.hash(h); + } +} + +/// Where the preview draws the picture: over the page; behind its content, over white paper and +/// under the page on a transparent sheet ([`Glass`]), which covers it wherever the page paints; +/// or not at all, because the page's own backdrop will hide it after OK. +#[derive(Clone, Copy)] +pub(super) enum Layer { + Over, + Behind(egui::TextureId), + Hidden, +} + +/// A picture mark as OK draws it: its scale relative to the page, its turn (degrees +/// counter-clockwise), its offset from the page centre (points, right and up) and its opacity. +#[derive(Clone, Copy)] +pub(super) struct PictureMark<'a> { + pub(super) picture: &'a Picture, + pub(super) scale: f64, + pub(super) rotation: f64, + pub(super) offset: [f64; 2], + pub(super) opacity: f64, +} + +impl<'a> PictureMark<'a> { + /// Laid out on the page drawn as `page`, at `s` pixels a point, where `picture` in + /// `pdfcraft-edit` puts it: fitted to the page at its scale, centred plus its offset, turned. + fn place(self, page: Rect, s: f32) -> Placed<'a> { + let finite = |v: f64| if v.is_finite() { v } else { 0.0 }; + let (w, h) = (f64::from(page.width() / s), f64::from(page.height() / s)); + let (sw, sh) = (self.picture.size.0.max(0.01), self.picture.size.1.max(0.01)); + let k = (w / sw).min(h / sh) * if self.scale.is_finite() && self.scale > 0.0 { self.scale } else { 1.0 }; + let centre = page.center() + vec2(finite(self.offset[0]) as f32 * s, -finite(self.offset[1]) as f32 * s); + Placed { + picture: self.picture, + rect: Rect::from_center_size(centre, vec2((sw * k) as f32 * s, (sh * k) as f32 * s)), + // Counter-clockwise on the page is clockwise-negative on screen. + turn: Rot2::from_angle(-(finite(self.rotation) as f32).to_radians()), + opacity: if self.opacity.is_finite() { self.opacity.clamp(0.0, 1.0) as f32 } else { 1.0 }, + } + } + + /// Draws the mark on the page drawn as `page` at `s` pixels a point, with `painter`, kept to + /// the page: OK crops a mark at the page edge. + pub(super) fn paint(self, painter: &egui::Painter, page: Rect, s: f32, layer: Layer) { + let painter = painter.with_clip_rect(painter.clip_rect().intersect(page)); + let placed = self.place(page, s); + match layer { + Layer::Over => { + painter.add(placed.mesh()); + } + Layer::Behind(glass) => { + let full = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + let mut paper = egui::Mesh::default(); + paper.add_colored_rect(page, Color32::WHITE); + painter.add(paper); + painter.add(placed.mesh()); + let mut sheet = egui::Mesh::with_texture(glass); + sheet.add_rect_with_uv(page, full, Color32::WHITE); + painter.add(sheet); + } + Layer::Hidden => {} + } + } +} + +/// A picture laid out on the preview's page: its rectangle before the turn, turned about its centre. +struct Placed<'a> { + picture: &'a Picture, + rect: Rect, + turn: Rot2, + opacity: f32, +} + +impl Placed<'_> { + /// The picture drawn over the page. + fn mesh(&self) -> egui::Mesh { + let mut mesh = egui::Mesh::with_texture(self.picture.tex.id()); + mesh.add_rect_with_uv(self.rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE.gamma_multiply(self.opacity)); + mesh.rotate(self.turn, self.rect.center()); + mesh + } +} + +/// What a sheet render is for: the document version, whether Update takes its marks away and +/// whether the white backdrops go, the page and the scale (×1000) it is drawn at. +type GlassKey = (DocId, u64, bool, bool, usize, u32); +/// The pages a sheet is made from: a [`GlassKey`] without its page and scale. +type GlassVersion = (DocId, u64, bool, bool); + +/// The page shown on a transparent sheet ([`pdfcraft_engine::Document::pages_on_glass`]), drawn +/// over a picture behind the page so the picture shows only where the page paints nothing. The +/// pages are made once per document version and Update choice; only the page shown is kept. +pub(super) struct Glass { + pages: Option<(GlassVersion, Option>>)>, + renders: JobQueue>, + shown: Option<(GlassKey, egui::TextureHandle)>, + failed: Option, +} + +impl Glass { + pub(super) fn new(renders: JobQueue>) -> Self { + Self { pages: None, renders, shown: None, failed: None } + } + + /// `page` of `doc` on the sheet at `scale` pixels a point, without its marks of `without` + /// and, with `replace_backdrops`, its white backdrop: `None` while it renders, or when it + /// can't be. + pub(super) fn texture( + &mut self, + ctx: &egui::Context, + doc: &pdfcraft_engine::Document, + without: Option, + replace_backdrops: bool, + page: usize, + scale: f32, + ) -> Option { + let version = (doc.id, doc.edit_generation(), without.is_some(), replace_backdrops); + if self.pages.as_ref().map(|p| p.0) != Some(version) { + self.renders.reprioritize(|_, _| None); + self.shown = None; + self.failed = None; + self.pages = Some((version, doc.pages_on_glass(without, replace_backdrops).ok().map(|p| Arc::new(Mutex::new(p))))); + } + let want = (version.0, version.1, version.2, version.3, page, glass_scale(scale)?); + while let Some(done) = self.renders.try_recv() { + match done.result { + Ok(image) if done.key == want => { + self.shown = Some((want, ctx.load_texture("marks-preview-glass", image, egui::TextureOptions::LINEAR))) + } + Err(_) if done.key == want => self.failed = Some(want), + _ => {} + } + } + if let Some((key, tex)) = &self.shown + && *key == want + { + return Some(tex.id()); + } + let pages = self.pages.as_ref()?.1.clone()?; + if self.failed != Some(want) && !self.renders.contains(&want) { + self.renders.reprioritize(|_, _| None); + self.renders.submit(want, Priority::VISIBLE, move |cancel| { + if cancel.is_cancelled() { + return Err("cancelled".to_string()); + } + let mut pages = pages.lock().map_err(|_| "the pages are unavailable".to_string())?; + let out = pages.render_page(page, scale).map_err(|e| e.to_string())?; + Ok(crate::canvas::texture_image([out.width as usize, out.height as usize], out.rgba)) + }); + } + #[cfg(target_arch = "wasm32")] + self.renders.run_inline(1); + None + } +} + +/// `scale` ×1000 for a [`GlassKey`], or `None` when it is not a positive, finite size a page +/// can be rendered at. +fn glass_scale(scale: f32) -> Option { + (scale.is_finite() && scale > 0.0).then_some((scale * 1000.0) as u32).filter(|k| *k > 0) +} + +#[cfg(test)] +mod tests { + #[test] + fn a_sheet_is_rendered_only_at_a_positive_finite_scale() { + assert_eq!(super::glass_scale(1.5), Some(1500)); + for bad in [0.0, -1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1e-6] { + assert_eq!(super::glass_scale(bad), None, "{bad}"); + } + } +} diff --git a/crates/ui-egui/src/dialogs/marks_ui.rs b/crates/ui-egui/src/dialogs/marks_ui.rs index b257e08a21..6544ee85ff 100644 --- a/crates/ui-egui/src/dialogs/marks_ui.rs +++ b/crates/ui-egui/src/dialogs/marks_ui.rs @@ -26,6 +26,7 @@ use craft::ui::text::TextField; use egui::{Color32, CornerRadius, Rect, pos2, vec2}; use pdfcraft_engine::{Backdrop, Background, DocId, Edit, FontFamily, HeaderFooter, MarkKind, Watermark}; +use super::marks_picture::{FileKey, Glass, Layer, PICTURE_SIDE, Picture, PictureMark, Rendered}; use crate::PdfCraftApp; /// How far a watermark may be moved from the page centre, in points. @@ -455,17 +456,21 @@ fn behind(color: [f64; 3], opacity: f64) -> Color32 { rgb32(color.map(|c| 1.0 - a * (1.0 - c))) } -/// The preview's tint for a background colour on a page whose own backdrop is `found` (`None` -/// when it has none, or the check hasn't reached it): no colour where the page will still hide -/// the background after OK, because a picture covers it (a scan) or it keeps its white backdrop -/// with Replace unticked. -fn background_tint(d: &MarksDraft, found: Option) -> Color32 { - let hidden = match found { +/// Whether a page whose own backdrop is `found` (`None` when it has none, or the check hasn't +/// reached it) will still hide the background after OK: a picture covers it (a scan), or it keeps +/// its white backdrop with Replace unticked. +fn backdrop_hides(d: &MarksDraft, found: Option) -> bool { + match found { Some(Backdrop::Image) => true, Some(Backdrop::Fill) => !d.bg.replace_backdrop, None => false, - }; - if hidden { Color32::WHITE } else { behind(d.bg.color, d.bg.opacity) } + } +} + +/// The preview's tint for a background colour on a page whose own backdrop is `found`: no colour +/// where the page will still hide it ([`backdrop_hides`]). +fn background_tint(d: &MarksDraft, found: Option) -> Color32 { + if backdrop_hides(d, found) { Color32::WHITE } else { behind(d.bg.color, d.bg.opacity) } } /// The page (0-based) the preview shows: `current` when OK applies to it (`pages`), otherwise the @@ -946,6 +951,12 @@ pub struct MarksPreview { unmarked: Option, pictures: HashMap, failed: HashSet, + /// Source ▸ File's picture: its render, and the picture of the file and page last rendered + /// (or why there is none). + files: JobQueue>, + file: Option<(FileKey, Result)>, + /// The page shown on a transparent sheet, drawn over a file's picture behind the page. + glass: Glass, } fn queue( @@ -961,10 +972,13 @@ impl MarksPreview { Self { kind, backdrops: queue(jobs.clone(), wake.clone(), "marks-backdrops"), - renders: queue(jobs, wake, "marks-preview"), + renders: queue(jobs.clone(), wake.clone(), "marks-preview"), unmarked: None, pictures: HashMap::new(), failed: HashSet::new(), + files: queue(jobs.clone(), wake.clone(), "marks-picture"), + file: None, + glass: Glass::new(queue(jobs, wake, "marks-preview-glass")), } } @@ -1082,6 +1096,53 @@ impl MarksPreview { } } +impl MarksPreview { + /// `page` on a transparent sheet at the preview's size, without the marks Update replaces and, + /// with `replace_backdrops`, its white backdrop: `None` while it renders, or when it can't be. + fn glass_page( + &mut self, + ctx: &egui::Context, + doc: &pdfcraft_engine::Document, + replace: bool, + replace_backdrops: bool, + page: usize, + ) -> Option { + let size = doc.info.pages.get(page)?; + let scale = PREVIEW_SIDE * ctx.pixels_per_point() / size.width.max(size.height).max(1.0); + self.glass.texture(ctx, doc, replace.then_some(self.kind), replace_backdrops, page, scale) + } + + /// Source ▸ File's picture of the draft's file and page, rendered as OK brings it in + /// ([`pdfcraft_engine::mark_picture`]): `None` without a file, while it renders, or when it + /// can't be drawn. + fn file_picture(&mut self, ctx: &egui::Context, d: &MarksDraft) -> Option { + let file = mark_file(d)?; + let want = FileKey { bytes: Arc::clone(&file.bytes), page: file.page }; + while let Some(done) = self.files.try_recv() { + if done.key == want { + self.file = Some((done.key, done.result.map(|r| Picture::upload(ctx, r)))); + } + } + let shown = self.file.as_ref().is_some_and(|(k, _)| *k == want); + if !shown && !self.files.contains(&want) { + // Only the file and page shown now is worth rendering. + self.files.reprioritize(|_, _| None); + self.files.submit(want.clone(), Priority::VISIBLE, move |cancel| { + if cancel.is_cancelled() { + return Err("cancelled".to_string()); + } + pdfcraft_engine::mark_picture(&file, PICTURE_SIDE).and_then(Rendered::new) + }); + } + #[cfg(target_arch = "wasm32")] + self.files.run_inline(1); + match &self.file { + Some((k, Ok(picture))) if *k == want => Some(picture.clone()), + _ => None, + } + } +} + /// The picture of `page` from the page thumbnails, with the pages next to it asked for ahead. fn thumbnail_picture(ctx: &egui::Context, source: &impl ThumbSource, page: usize, near: &[usize]) -> PreviewState { let ppp = ctx.pixels_per_point(); @@ -1101,10 +1162,26 @@ fn thumbnail_picture(ctx: &egui::Context, source: &impl ThumbSource, page } } +/// Where the preview draws Source ▸ File's picture: over the page; behind it, on the page's +/// transparent sheet from `sheet`; or nowhere, when the page's own backdrop hides it after OK. +/// `None` while the sheet renders or when it can't be, so the preview shows the file's name +/// frame instead of nothing. +fn file_layer(on_top: bool, behind: bool, sheet: impl FnOnce() -> Option) -> Option { + if on_top { + Some(Layer::Over) + } else if behind { + sheet().map(Layer::Behind) + } else { + Some(Layer::Hidden) + } +} + /// The marks laid out on the preview's page: what the preview closure drew over the picture, and /// `over` over them, the picture of what OK keeps drawn over an updated header and footer. -fn overlay(kind: MarkKind, d: &MarksDraft, size: (f64, f64), over: Option) -> SharedOverlay { +/// `file` is Source ▸ File's picture, once rendered, and where it goes. +fn overlay(kind: MarkKind, d: &MarksDraft, size: (f64, f64), over: Option, file: Option<(Picture, Layer)>) -> SharedOverlay { let hf = d.hf.clone(); + let (bg_scale, bg_opacity) = (d.bg.scale, d.bg.opacity); let (wm, fit, use_file) = (d.wm.clone(), d.fit, d.use_file); let file_name = d.file.as_ref().map(|f| f.0.clone()); let (page_w, page_h) = (size.0.max(1.0), size.1.max(1.0)); @@ -1141,6 +1218,16 @@ fn overlay(kind: MarkKind, d: &MarksDraft, size: (f64, f64), over: Option { + if let Some((picture, layer)) = &file { + let mark = match kind { + MarkKind::Background => PictureMark { picture, scale: bg_scale, rotation: 0.0, offset: [0.0; 2], opacity: bg_opacity }, + _ => PictureMark { picture, scale: wm.scale, rotation: wm.rotation, offset: wm.offset, opacity: wm.opacity }, + }; + mark.paint(p, r, s, *layer); + } + } + // Until the picture arrives, or when the file can't be drawn: a frame with its name. MarkKind::Watermark if use_file => { if let Some(name) = &file_name { p.rect_stroke(r.shrink(6.0), CornerRadius::ZERO, egui::Stroke::new(1.0, Color32::GRAY), egui::StrokeKind::Inside); @@ -1371,7 +1458,17 @@ impl PdfCraftApp { (kind == MarkKind::Background && !d.use_file).then(|| DataColor::new(background_tint(d, d.backdrops.found(doc, target).flatten()))); let pager = PanePager { shown: target + 1, count, shown_label: None, back: back.is_some(), next: next.is_some(), unit: PagerUnit::Page }; - let overlay = size.map(|size| overlay(kind, d, size, over)); + // A background, or a watermark that appears behind the page, shows where the page paints + // nothing, unless the page's own backdrop will hide it; a watermark on top covers the page. + let behind = if kind == MarkKind::Background { !backdrop_hides(d, d.backdrops.found(doc, target).flatten()) } else { d.wm.behind }; + let on_top = kind != MarkKind::Background && !d.wm.behind; + let replace_backdrops = kind == MarkKind::Background && d.bg.replace_backdrop; + // Lazy: no picture, no sheet render. + let file = match preview.file_picture(ctx, d) { + Some(p) => file_layer(on_top, behind, || preview.glass_page(ctx, doc, d.replace, replace_backdrops, target)).map(|layer| (p, layer)), + None => None, + }; + let overlay = size.map(|size| overlay(kind, d, size, over, file)); if let Some(dialog) = self.dialogs.get_mut_by_id::(id) { for (key, value) in refill.iter().flat_map(DialogFields::iter) { dialog.set_field(key, value.clone()); @@ -1619,6 +1716,22 @@ mod tests { assert_eq!(background_tint(&d, None), colour, "unticked changes nothing without a backdrop"); } + #[test] + fn a_picture_behind_a_page_whose_sheet_is_missing_shows_the_file_name_frame() { + let sheet = egui::TextureId::Managed(7); + assert!(matches!(file_layer(true, true, || None), Some(Layer::Over)), "a watermark on top needs no sheet"); + assert!(matches!(file_layer(false, true, || Some(sheet)), Some(Layer::Behind(t)) if t == sheet)); + assert!(file_layer(false, true, || None).is_none(), "a sheet rendering, or failed, leaves the name frame"); + let mut asked = false; + let hidden = file_layer(false, false, || { + asked = true; + None + }); + assert!(matches!(hidden, Some(Layer::Hidden)), "the page's own backdrop still hides the picture"); + assert!(!asked, "a hidden picture renders no sheet"); + // With no picture to place, `overlay` takes its name-frame arm. + } + #[test] fn the_watermark_edit_carries_the_offset() { let mut d = MarksDraft::default(); diff --git a/crates/ui-egui/tests/it/marks.rs b/crates/ui-egui/tests/it/marks.rs index cdf109f6ec..6286a662ab 100644 --- a/crates/ui-egui/tests/it/marks.rs +++ b/crates/ui-egui/tests/it/marks.rs @@ -821,3 +821,231 @@ fn update_previews_the_page_without_the_marks_it_replaces() { let page = wait_for_preview(&mut h, "the page without the old header", |i| count(i, blue) == 0).image; assert!(at(&page, 0.5, 0.75) == yellow && count(&page, red) > 200, "the background and watermark stay"); } + +/// A one-page PDF of `w` × `h` points painted with `content`: a file to take a mark from. +fn picture_pdf(w: u32, h: u32, content: &str) -> Vec { + format!( + "%PDF-1.7 +1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj +2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj +3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 {w} {h}] /Contents 4 0 R >> endobj +4 0 obj << /Length {} >> +stream +{content} +endstream +endobj +trailer << /Root 1 0 R >> +%%EOF", + content.len() + ) + .into_bytes() +} + +/// Every mesh painted last frame, with the clip it was painted under. +fn clipped_meshes(h: &Rig) -> Vec<(egui::Rect, Arc)> { + fn append(shape: &egui::Shape, clip: egui::Rect, out: &mut Vec<(egui::Rect, Arc)>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| append(shape, clip, out)), + egui::Shape::Mesh(m) => out.push((clip, m.clone())), + _ => {} + } + } + let mut out = Vec::new(); + h.output().shapes.iter().for_each(|s| append(&s.shape, s.clip_rect, &mut out)); + out +} + +fn is_red(c: egui::Color32) -> bool { + c.r() > 200 && c.g() < 60 && c.b() < 60 +} + +/// The marks painted last frame from a red file: meshes whose uploaded picture is mostly red, +/// with their clip. +fn red_marks(h: &Rig) -> Vec<(egui::Rect, Arc)> { + let uploads = h.uploads.0.lock().unwrap(); + clipped_meshes(h).into_iter().filter(|(_, m)| uploads.get(&m.texture_id).is_some_and(|i| count(i, is_red) * 2 > i.pixels.len())).collect() +} + +/// Opens `command`'s dialog on `pdf` and picks `file` as its Source ▸ File. +fn open_with_file(command: &str, file: Vec, pdf: Vec) -> Rig { + let files = Arc::new(craft::host::ScriptedFiles::answering([craft::host::Picked::Contents(vec![("stamp.pdf".into(), file)])])); + let mut h = harness_with_files(pdf, files); + assert!(h.execute(command)); + // The dialog grows once it has looked at the page's backdrop; click after it settles. + h.steps(6); + h.get_by_role_and_label(egui::accesskit::Role::RadioButton, "File").click(); + h.steps(2); + h.get_by_label("Browse…").click(); + h.steps(3); + h +} + +/// Steps until the preview shows its page and `ready` accepts what was painted on it. +fn wait_for(h: &mut Rig, what: &str, ready: impl Fn(&Rig, egui::Rect) -> Option) -> (egui::Rect, T) { + for _ in 0..200 { + h.steps(1); + if let Some(page) = preview_picture(h).map(|p| p.rect) + && let Some(found) = ready(h, page) + { + return (page, found); + } + } + panic!("the preview never showed {what}"); +} + +/// The one mark from a red file painted last frame, with its clip. +fn one_mark(h: &Rig, _: egui::Rect) -> Option<(egui::Rect, Arc)> { + match &red_marks(h)[..] { + [mark] => Some(mark.clone()), + _ => None, + } +} + +#[test] +fn a_mark_from_a_file_previews_its_picture_where_ok_puts_it() { + // A watermark from a 200 × 100 page painted red, at half the page, moved 30 pt right and + // 20 pt up, half opaque (#2817 item 14). + let mut h = open_with_file("edit.watermark", picture_pdf(200, 100, "1 0 0 rg 0 0 200 100 re f"), content_fixture()); + let settings = [("file.scale", 50.0), ("wm.rotation", 0.0), ("wm.offset.0", 30.0), ("wm.offset.1", 20.0), ("wm.opacity", 50.0)]; + for (field, value) in settings { + set_field(&mut h, MarkKind::Watermark, field, json!(value)); + } + let (page, (_, mark)) = wait_for(&mut h, "the file's picture", one_mark); + // Fitted to the 300 × 400 page: 1.5 × the picture, half of that is 150 × 75 pt. + let s = page.width() / 300.0; + let r = mark.calc_bounds(); + near(r.width(), 150.0 * s, "width"); + near(r.height(), 75.0 * s, "height"); + near(r.center().x, page.center().x + 30.0 * s, "moved right"); + near(r.center().y, page.center().y - 20.0 * s, "moved up"); + assert!(mark.vertices.iter().all(|v| v.color.a() > 50 && v.color.a() < 200), "half opaque"); + // Turned a quarter counter-clockwise: the picture's top-left corner comes to the bottom left. + set_field(&mut h, MarkKind::Watermark, "wm.rotation", json!(90.0)); + let upright = |h: &Rig, p: egui::Rect| one_mark(h, p).filter(|(_, m)| m.calc_bounds().height() > m.calc_bounds().width()); + let (page, (_, mark)) = wait_for(&mut h, "the turned picture", upright); + let r = mark.calc_bounds(); + near(r.width(), 75.0 * s, "turned, width"); + near(r.height(), 150.0 * s, "turned, height"); + near(r.center().x, page.center().x + 30.0 * s, "turned about its centre, across"); + near(r.center().y, page.center().y - 20.0 * s, "turned about its centre, down"); + let corner = mark.vertices.iter().find(|v| v.uv == egui::pos2(0.0, 0.0)).map(|v| v.pos).unwrap(); + near(corner.x, r.left(), "top-left corner, across"); + near(corner.y, r.bottom(), "top-left corner, down"); +} + +/// OK crops a mark at the page edge, so the preview keeps it to the page too, not to the pane +/// around it. +#[test] +fn a_mark_from_a_file_is_kept_to_the_page() { + let mut h = open_with_file("edit.watermark", picture_pdf(100, 100, "1 0 0 rg 0 0 100 100 re f"), content_fixture()); + // Page 2 turns landscape, so the pane around it is wider or taller than the page itself. + show_page(&mut h, 1); + // Pushed past the page's right and top edges, whichever way they face on screen. + for (field, value) in [("file.scale", 30.0), ("wm.rotation", 0.0), ("wm.offset.0", 140.0), ("wm.offset.1", 190.0)] { + set_field(&mut h, MarkKind::Watermark, field, json!(value)); + } + let (page, (clip, mark)) = wait_for(&mut h, "the file's picture", one_mark); + let mark = mark.calc_bounds(); + assert!(!page.expand(1.0).contains_rect(mark), "the mark crosses the page's edge: {mark:?} on {page:?}"); + assert!(page.expand(0.5).contains_rect(clip), "the mark is clipped at the page edge: clip {clip:?}, page {page:?}"); +} + +/// What the preview shows at `at` once last frame's meshes are painted in order: each mesh's +/// texture (white for the default one) times its vertex colours, premultiplied, inside its clip. +fn shown_at(h: &Rig, at: egui::Pos2) -> egui::Color32 { + let uploads = h.uploads.0.lock().unwrap(); + let mut out = [0.0f32; 4]; + for (clip, m) in clipped_meshes(h) { + if !clip.contains(at) { + continue; + } + for t in m.indices.as_chunks::<3>().0 { + let [a, b, c] = t.map(|i| m.vertices[i as usize]); + let cross = |u: egui::Vec2, v: egui::Vec2| u.x * v.y - u.y * v.x; + let area = cross(b.pos - a.pos, c.pos - a.pos); + if area.abs() < 1e-6 { + continue; + } + let wb = cross(at - a.pos, c.pos - a.pos) / area; + let wc = cross(b.pos - a.pos, at - a.pos) / area; + let wa = 1.0 - wb - wc; + if wa < -1e-4 || wb < -1e-4 || wc < -1e-4 { + continue; + } + let uv = a.uv.to_vec2() * wa + b.uv.to_vec2() * wb + c.uv.to_vec2() * wc; + let texel = match uploads.get(&m.texture_id) { + Some(i) if m.texture_id != egui::TextureId::default() => { + let pick = |f: f32, n: usize| ((f * n as f32) as usize).min(n - 1); + i.pixels[pick(uv.y, i.size[1]) * i.size[0] + pick(uv.x, i.size[0])] + } + _ => egui::Color32::WHITE, + }; + let tint = |k: usize| { + let ch = |v: &egui::epaint::Vertex| f32::from(v.color.to_array()[k]) / 255.0; + ch(&a) * wa + ch(&b) * wb + ch(&c) * wc + }; + let src: [f32; 4] = std::array::from_fn(|k| f32::from(texel.to_array()[k]) / 255.0 * tint(k)); + out = std::array::from_fn(|k| src[k] + out[k] * (1.0 - src[3])); + break; + } + } + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + egui::Color32::from_rgba_premultiplied(byte(out[0]), byte(out[1]), byte(out[2]), byte(out[3])) +} + +/// The point `(x, y)` points from the bottom left of the 300-point-wide page drawn as `page`. +fn on_page(page: egui::Rect, x: f32, y: f32) -> egui::Pos2 { + let s = page.width() / 300.0; + egui::pos2(page.left() + x * s, page.bottom() - y * s) +} + +/// Whether the preview of the page shown, settled, has the red picture behind it, at its middle. +fn shows_behind(h: &mut Rig) -> bool { + // Frames for the backdrop check, the picture and the page's sheet, then what the last one painted. + h.steps(8); + let (page, ()) = wait_for(h, "the page", |_, _| Some(())); + is_red(shown_at(h, page.center())) +} + +/// A background from a file shows where OK lets it show, as a colour does: through the page's +/// white, but not on a page whose own white backdrop stays (Replace unticked) or on a scan. +#[test] +fn a_background_from_a_file_previews_only_where_ok_lets_it_show() { + let mut h = open_with_file("edit.background", picture_pdf(100, 100, "1 0 0 rg 0 0 100 100 re f"), backdrop_fixture()); + set_field(&mut h, MarkKind::Background, "file.scale", json!(50.0)); + set_field(&mut h, MarkKind::Background, "bg.opacity", json!(100.0)); + // 150 × 150 pt in the middle of the 300 × 400 page. + let (page, ()) = wait_for(&mut h, "the picture behind page 1", |h, page| is_red(shown_at(h, page.center())).then_some(())); + assert!(is_red(shown_at(&h, on_page(page, 150.0, 140.0))), "inside, near the bottom edge"); + assert_eq!(shown_at(&h, on_page(page, 150.0, 110.0)), egui::Color32::WHITE, "below it"); + assert_eq!(shown_at(&h, on_page(page, 45.0, 45.0)), egui::Color32::BLACK, "the page's black square, outside it"); + // Unticked, page 1 keeps its white backdrop, which hides the background. + h.get_by_label(REPLACE).click(); + h.steps(2); + assert!(!shows_behind(&mut h), "page 1 keeps its backdrop"); + h.get_by_label(REPLACE).click(); + h.steps(2); + assert!(shows_behind(&mut h), "ticked again, it shows"); + show_page(&mut h, 1); + assert!(!shows_behind(&mut h), "a picture covers page 2"); + show_page(&mut h, 2); + assert!(shows_behind(&mut h), "page 3 is bare paper"); +} + +/// A picture behind the page shows only where the page paints nothing, as after OK: an opaque +/// blue box on the page stays blue over it, not blue times the picture (black over red), and +/// bare paper shows the picture. +#[test] +fn a_picture_behind_the_page_is_covered_where_the_page_paints() { + let page = picture_pdf(300, 400, "0 0 1 rg 100 150 100 100 re f"); + let mut h = open_with_file("edit.watermark", picture_pdf(100, 100, "1 0 0 rg 0 0 100 100 re f"), page); + // Fitted to the page's width: 300 × 300 pt from 50 pt up to 350. + let settings = [("file.scale", json!(100.0)), ("wm.rotation", json!(0.0)), ("wm.opacity", json!(100.0)), ("wm.behind", json!("behind"))]; + for (field, value) in settings { + set_field(&mut h, MarkKind::Watermark, field, value); + } + let (page, ()) = wait_for(&mut h, "the picture behind the page", |h, page| is_red(shown_at(h, on_page(page, 40.0, 320.0))).then_some(())); + let blue = shown_at(&h, on_page(page, 150.0, 200.0)); + assert!(blue.b() > 200 && blue.r() < 60 && blue.g() < 60, "the blue box stays blue over the picture: {blue:?}"); + assert_eq!(shown_at(&h, on_page(page, 150.0, 20.0)), egui::Color32::WHITE, "below the picture, white paper"); +} diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml index c25597f8b7..8a296a057c 100644 --- a/parity/acrobat-features.toml +++ b/parity/acrobat-features.toml @@ -2532,8 +2532,8 @@ milestone = "M7" status = "shipped" commands = ["edit.watermark"] tools = ["doc_watermark"] -evidence = ["crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/automation/tests/it/automation.rs::pdf_watermark_uses_visible_source_crop_through_tools"] -notes = "an image or a page of a PDF (source CropBox clipped to MediaBox, #7687), scaled relative to the page, rotated, with opacity, behind or on top; the dialog's preview shows its frame and file name over the page, not the picture itself" +evidence = ["crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/automation/tests/it/automation.rs::pdf_watermark_uses_visible_source_crop_through_tools", "crates/engine/src/mark_picture.rs::an_image_keeps_its_size_colours_and_transparency", "crates/engine/src/mark_picture.rs::a_pdf_page_is_transparent_where_it_draws_nothing_and_upright", "crates/ui-egui/tests/it/marks.rs::a_mark_from_a_file_previews_its_picture_where_ok_puts_it"] +notes = "an image or a page of a PDF (source CropBox clipped to MediaBox, #7687), scaled relative to the page, rotated, with opacity, behind or on top; the dialog previews the picture itself over the page's own thumbnail where OK puts it (scale, turn, offset, opacity), brought in and rendered off the UI thread the way OK brings it in, with its own transparency; behind the page it multiplies the page's picture on a grid of 2-pixel cells (exact over white and black content, darker than the result over coloured content); a frame and the file name until it arrives, or when the file can't be drawn" [[feature]] id = "edit.watermark-update-remove" @@ -2568,8 +2568,8 @@ milestone = "M7" status = "shipped" commands = ["edit.background"] tools = ["doc_background", "doc_backdrops"] -evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/automation/tests/it/backdrop.rs::a_background_shows_on_a_page_that_paints_its_own_white_backdrop", "crates/ui-egui/tests/it/marks.rs::the_background_dialog_offers_to_replace_a_white_backdrop_and_warns_about_scans", "crates/ui-egui/tests/it/marks.rs::the_background_preview_follows_the_replace_checkbox", "crates/edit/src/backdrop_tests.rs::content_that_is_not_a_page_backdrop_is_left_alone", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks", "crates/ui-egui/tests/it/marks.rs::update_previews_the_page_without_the_marks_it_replaces", "crates/engine/src/tests.rs::update_previews_on_the_page_without_the_marks_it_replaces"] -notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page. A page that paints its own opaque white backdrop (browsers' Save as PDF, print drivers) used to hide the background entirely; the dialog now offers to replace that fill (on by default; Remove turns it back on, after edits and redactions too, unless the operators before it changed or it would no longer be painted first, and then says which pages keep it off). The replaced copy's tag holds no page content or reference, so text a redaction or Remove Hidden Information takes off such a page leaves the file. Our own choice: Acrobat's behaviour on such pages has not been observed. Still hidden: scanned pages (warned), backdrops drawn inside a form XObject, by a non-rectangular path, or in a named colour space, and white fills drawn translucent, through a soft mask, a non-Normal blend mode or a transfer function (TR/TR2) as the graphics state stands after every gs, which are real content and stay. The dialog previews a colour as a tint of the page's own thumbnail (opaque pictures on the page are tinted there too, not in the result), a file as its frame and name; a page that will still hide the background (a scan, or a white backdrop with Replace unticked) previews without the colour; Update previews on the page without the backgrounds it replaces, not tinting the old one" +evidence = ["crates/ui-egui/tests/it/marks.rs::watermark_and_background_dialogs", "crates/engine/src/tests.rs::headers_footers_watermarks_and_backgrounds_show_update_and_remove", "crates/engine/src/tests.rs::backgrounds_and_watermarks_from_files", "crates/ui-egui/tests/it/marks.rs::backgrounds_and_watermarks_from_a_file", "crates/organize/src/tests.rs::a_page_becomes_a_form_xobject_upright", "crates/automation/tests/it/backdrop.rs::a_background_shows_on_a_page_that_paints_its_own_white_backdrop", "crates/ui-egui/tests/it/marks.rs::the_background_dialog_offers_to_replace_a_white_backdrop_and_warns_about_scans", "crates/ui-egui/tests/it/marks.rs::the_background_preview_follows_the_replace_checkbox", "crates/edit/src/backdrop_tests.rs::content_that_is_not_a_page_backdrop_is_left_alone", "crates/ui-egui/tests/it/marks.rs::the_preview_shows_the_page_the_range_selects_under_the_marks", "crates/ui-egui/tests/it/marks.rs::update_previews_the_page_without_the_marks_it_replaces", "crates/engine/src/tests.rs::update_previews_on_the_page_without_the_marks_it_replaces", "crates/ui-egui/tests/it/marks.rs::a_mark_from_a_file_previews_its_picture_where_ok_puts_it", "crates/ui-egui/tests/it/marks.rs::a_background_from_a_file_previews_only_where_ok_lets_it_show"] +notes = "colour, or a picture from a file (an image or a page of a PDF) scaled relative to the page. A page that paints its own opaque white backdrop (browsers' Save as PDF, print drivers) used to hide the background entirely; the dialog now offers to replace that fill (on by default; Remove turns it back on, after edits and redactions too, unless the operators before it changed or it would no longer be painted first, and then says which pages keep it off). The replaced copy's tag holds no page content or reference, so text a redaction or Remove Hidden Information takes off such a page leaves the file. Our own choice: Acrobat's behaviour on such pages has not been observed. Still hidden: scanned pages (warned), backdrops drawn inside a form XObject, by a non-rectangular path, or in a named colour space, and white fills drawn translucent, through a soft mask, a non-Normal blend mode or a transfer function (TR/TR2) as the graphics state stands after every gs, which are real content and stay. The dialog previews a colour as a tint of the page's own thumbnail, and a file's picture multiplied into it where OK puts it, on a grid of 2-pixel cells (opaque pictures on the page are tinted there too, not in the result); a frame and the file name until the picture arrives, or when the file can't be drawn; a page that will still hide the background (a scan, or a white backdrop with Replace unticked) previews without the colour or picture; Update previews on the page without the backgrounds it replaces, not tinting the old one" [[feature]] id = "edit.background-update-remove"