From c92635f83e5f45f8be92fd5b78fabe3e2370198c Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Sat, 31 Oct 2026 12:24:46 +0100 Subject: [PATCH 1/5] Text selection: invert what lies under the highlight - Text selection: invert what lies under the highlight - Text selection: redraw the highlight when a display option changes - Text selection: invert the highlight from the canvas pixels already rendered - Text selection: adapt to the current main (Id::unique) - Text selection: keep main's Separations Preview state; the highlight's own render follows the proof setup Rebased onto current main as one commit; main had split the files this touched into modules. Review: in Preview, Bleed and Slug the inverted highlight is clipped to what each spread shows, as the canvas is. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/render.rs | 16 ++- crates/ui-egui/src/canvas/tests.rs | 82 +++++++++++ crates/ui-egui/src/canvas/text_overlay.rs | 168 +++++++++++++++------- crates/ui-egui/src/state.rs | 6 + 4 files changed, 222 insertions(+), 50 deletions(-) diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs index f33fc9ea0..55b168d1d 100644 --- a/crates/ui-egui/src/canvas/render.rs +++ b/crates/ui-egui/src/canvas/render.rs @@ -95,7 +95,7 @@ pub struct DisplayKey { highlight_custom_tracking: bool, } -fn display_key(app: &DesignApp) -> DisplayKey { +pub(super) fn display_key(app: &DesignApp) -> DisplayKey { let (ui, prefs) = (&app.ui, &app.session.prefs); DisplayKey { quality: ui.display_quality, @@ -318,6 +318,18 @@ fn patch_texture(app: &mut DesignApp, layout: &CanvasLayout, ppp: f64, doc_key: if let Some(tex) = app.canvas.texture.as_mut() { tex.set_partial([x0 as usize, y0 as usize], ci, egui::TextureOptions::LINEAR); } + // The same region in the canvas's own copy of its pixels. + if let Some(all) = app.canvas.pixels.as_mut() { + let all = std::sync::Arc::make_mut(all); + let (aw, pw) = (all.width as usize, img.width as usize); + for (row, src) in img.pixels.chunks_exact(pw * 4).enumerate() { + let start = ((y0 as usize + row) * aw + x0 as usize) * 4; + if let Some(dst) = all.pixels.get_mut(start..start + pw * 4) { + dst.copy_from_slice(src); + } + } + app.canvas.pixels_generation += 1; + } done(app); app.canvas.patches += 1; app.perf.render_ms = crate::now_ms() - t0; @@ -351,4 +363,6 @@ fn upload(app: &mut DesignApp, ctx: &egui::Context, mut img: designcraft_render: Some(tex) => tex.set(ci, egui::TextureOptions::LINEAR), None => app.canvas.texture = Some(ctx.load_texture("canvas", ci, egui::TextureOptions::LINEAR)), } + app.canvas.pixels = Some(std::sync::Arc::new(img)); + app.canvas.pixels_generation += 1; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 914777616..3c5e791b0 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1,6 +1,7 @@ use designcraft_geom::Unit; use egui_kittest::{Harness, kittest::Queryable}; +use super::text_overlay::inverse_under; use super::*; /// A place-cursor drag past its 3-point threshold but short of egui's drag distance previews @@ -3485,3 +3486,84 @@ fn leaving_parent_editing_for_the_left_page_of_a_spread_keeps_that_page_selected h.run_steps(3); assert_eq!(current_page(h.state()), Some(1)); } + +/// Selected text shows what lies under it inverted: paper turns black, black turns white, +/// and a half-covered pixel is half inverted. +#[test] +fn the_text_highlight_inverts_what_lies_under_it() { + let mask = [0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 128, 128, 128, 128, 255, 255, 255, 255]; + let under = [9, 9, 9, 255, 255, 255, 255, 255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0, 0]; + let out = inverse_under(&mask, &under, [80, 80, 80]); + assert_eq!(&out[0..4], &[0, 0, 0, 0], "outside the highlight: untouched"); + assert_eq!(&out[4..8], &[0, 0, 0, 255], "white paper turns black"); + assert_eq!(&out[8..12], &[255, 255, 255, 255], "black turns white"); + assert_eq!(&out[12..16], &[128, 128, 128, 128], "half covered: half the inverse"); + assert_eq!(&out[16..20], &[175, 175, 175, 255], "transparent: the inverse of the pasteboard"); +} + +/// White text on a black frame used to turn black on a black highlight. Now the highlight is +/// light there and the selected letters dark. +#[test] +fn selected_white_text_on_a_dark_fill_stays_readable() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({})).unwrap(); + let id = app + .run("frame.create", serde_json::json!({"rect": [72, 72, 400, 200], "content": "text", "text": "White text", "caret": true})) + .unwrap()["id"] + .as_u64() + .unwrap(); + app.run("edit.selectAll", serde_json::json!({})).unwrap(); + app.run("type.char", serde_json::json!({"attrs": {"size": 28, "fill": "[Paper]"}})).unwrap(); + app.run("object.fill", serde_json::json!({"ids": [id], "swatch": "[Black]"})).unwrap(); + let mut h = crate::test_window::open(app, vec2(900.0, 600.0)); + h.run_steps(6); + let app = &h.state().app; + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let canvas = app.session.layout().xf(designcraft_doc::SpreadRef::Doc(0)); + let (a, b) = (xf.to_screen(canvas * Point::new(76.0, 78.0)), xf.to_screen(canvas * Point::new(180.0, 98.0))); + let image = match h.render() { + Ok(image) => image, + // CI has a renderer: there a missing one is a failure, not a silent pass. + Err(e) if std::env::var_os("CI").is_some() => panic!("no offscreen renderer in CI: {e}"), + Err(e) => { + eprintln!("skipped: no offscreen renderer ({e})"); + return; + } + }; + let (mut light, mut dark) = (0, 0); + for y in a.y as u32..b.y as u32 { + for x in a.x as u32..b.x as u32 { + let p = image.get_pixel(x, y); + let l = (u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2])) / 3; + if l > 200 { + light += 1; + } else if l < 60 { + dark += 1; + } + } + } + assert!(light > dark, "a light highlight under the selected white text: {light} light, {dark} dark"); + assert!(dark > 0, "with the letters dark on it"); +} + +/// The highlight is drawn from a render of what lies under it: a display option that changes +/// that render (Overprint Preview here) draws it again instead of keeping the old pixels. +#[test] +fn the_text_highlight_follows_the_display_options() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({})).unwrap(); + app.run("frame.create", serde_json::json!({"rect": [72, 72, 400, 200], "content": "text", "text": "Some text", "caret": true})).unwrap(); + app.run("edit.selectAll", serde_json::json!({})).unwrap(); + let mut h = crate::test_window::open(app, vec2(900.0, 600.0)); + h.run_steps(6); + let cached = |h: &Harness<'_, crate::test_window::Window>| { + h.ctx.data(|d| d.get_temp::<(egui::Id, egui::TextureHandle)>(egui::Id::unique("inverse_sel_tex"))).map(|(k, _)| k) + }; + let before = cached(&h).expect("the highlight is drawn"); + h.run_steps(2); + assert_eq!(cached(&h), Some(before), "unchanged: the cached highlight is kept"); + h.state_mut().app.ui.overprint_preview = !h.state().app.ui.overprint_preview; + h.run_steps(2); + let after = cached(&h).expect("the highlight is drawn"); + assert_ne!(after, before, "a new display option: the highlight is drawn again"); +} diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs index cc6e1432d..30a00930b 100644 --- a/crates/ui-egui/src/canvas/text_overlay.rs +++ b/crates/ui-egui/src/canvas/text_overlay.rs @@ -1,6 +1,8 @@ use super::caret; use super::frames::{item_canvas_xf, layer_color, path_screen}; +use super::render::{display_key, screen_options}; use super::{Affine, CanvasLayout, Color32, DesignApp, Document, Point, Pos2, Rect, Stroke, Xf, compose, pos2}; +use crate::{ScreenMode, theme::Tokens}; pub(super) fn draw_text_selection( app: &DesignApp, @@ -38,8 +40,8 @@ pub(super) fn draw_text_selection( draw_cell_selection(app, painter, xf, doc, layout, &cs, ts, cell); return; } - let mut runs: Vec<(usize, Affine, Vec<[Point; 4]>, Vec<(usize, usize)>)> = Vec::new(); - for (fi, ft) in cs.frames.iter().enumerate() { + let mut runs: Vec<(Affine, Vec<[Point; 4]>)> = Vec::new(); + for ft in &cs.frames { let Some((a, _)) = item_canvas_xf(doc, layout, ft.frame) else { continue }; let Some(it) = doc.item(ft.frame) else { continue }; let m = a * doc.text_xf(it); @@ -73,8 +75,7 @@ pub(super) fn draw_text_selection( continue; } let mut quads = Vec::new(); - let mut glyphs = Vec::new(); - for (li, l) in ft.lines.iter().enumerate() { + for l in &ft.lines { let s = range.start.max(l.range.start); let e = range.end.min(l.range.end); if s > e || (s == e && !(l.range.end < range.end && e == l.range.end)) { @@ -91,18 +92,13 @@ pub(super) fn draw_text_selection( quads.push([Point::new(a, r.y0), Point::new(b, r.y0), Point::new(b, r.y1), Point::new(a, r.y1)]); } } - for (gi, g) in l.glyphs.iter().enumerate() { - if g.visible && g.len > 0 && g.byte >= s && g.byte < e { - glyphs.push((li, gi)); - } - } } if !quads.is_empty() { - runs.push((fi, m, quads, glyphs)); + runs.push((m, quads)); } } if !runs.is_empty() { - draw_inverse_highlight(app, painter, xf, doc, &cs, ts.story, &runs); + draw_inverse_highlight(app, painter, xf, doc, layout, ts.story, &runs); } if ts.is_caret() && let Some((fi, x, bl, asc, desc)) = compose::caret(&cs, ts.focus) @@ -172,24 +168,49 @@ fn draw_cell_selection( } } -/// InDesign draws selected text inverted: a black highlight with the selected glyphs in the -/// inverse of their colour (white for black text). The highlight and glyph outlines are -/// rasterised with `vello_cpu` into a small screen-space texture over the selection. +thread_local! { + /// Renders what lies under a text highlight, apart from the canvas renderer and its worker. + static HIGHLIGHT_RENDERER: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +/// The `w` × `h` premultiplied pixels of `img` from (`x0`, `y0`), the pasteboard colour `back` +/// where that reaches past the image. +fn crop(img: &designcraft_render::Rendered, x0: i64, y0: i64, w: u32, h: u32, back: [u8; 3]) -> Vec { + let mut out = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..i64::from(h) { + for x in 0..i64::from(w) { + let (sx, sy) = (x0 + x, y0 + y); + let inside = sx >= 0 && sy >= 0 && sx < i64::from(img.width) && sy < i64::from(img.height); + let px = inside.then(|| (sy as usize * img.width as usize + sx as usize) * 4).and_then(|i| img.pixels.get(i..i + 4)); + match px { + Some(p) => out.extend_from_slice(p), + None => out.extend_from_slice(&[back[0], back[1], back[2], 255]), + } + } + } + out +} + +/// InDesign draws selected text inverted: whatever lies under the highlight (paper, the frame's +/// fill, a placed image, the selected glyphs themselves) shows in its inverse colour. Black text +/// on white paper turns white on black, and white text on a dark fill turns dark on a light +/// highlight instead of vanishing into a black bar. The area under the selection is rendered from +/// the document into a small screen-space texture and inverted inside the highlight quads. fn draw_inverse_highlight( app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document, - cs: &compose::ComposedStory, + layout: &CanvasLayout, story: designcraft_doc::StoryId, - runs: &[(usize, Affine, Vec<[Point; 4]>, Vec<(usize, usize)>)], + runs: &[(Affine, Vec<[Point; 4]>)], ) { use designcraft_render::vello_cpu::{self, kurbo, peniko}; let ctx = painter.ctx(); let ppp = ctx.pixels_per_point(); let to_screen = |m: Affine, p: Point| xf.to_screen(m * p); let mut bbox = Rect::NOTHING; - for (_, m, quads, _) in runs { + for (m, quads) in runs { for q in quads { for p in q { bbox.extend_with(to_screen(*m, *p)); @@ -207,18 +228,38 @@ fn draw_inverse_highlight( ); let (w, h) = (((bbox.width() * ppp).round() as u32).clamp(1, 8192), ((bbox.height() * ppp).round() as u32).clamp(1, 8192)); let Some(st) = app.session.active() else { return }; + let preview = app.ui.screen_mode != ScreenMode::Normal; + let back = Tokens::get(ctx).pasteboard; + // Everything that changes the colours the canvas shows changes the highlight too: the display + // options the canvas texture is redrawn for (Rich Black, Overprint Preview, quality …) and + // the proof setup and pasteboard behind them. + let display = (format!("{:?}", display_key(app)), app.ui.proof_colors.then(|| format!("{:?}", app.ui.proof_setup)), back.to_array()); + // What the canvas shows under the highlight: cut from the canvas's own pixels when its texture + // is at this zoom (no second render; Preview mode's clipping included), else rendered here. + // The texture's pixel at the highlight's top left, kept in canvas space so scrolling (which + // only shifts the texture) reuses the highlight. + let from_canvas = + app.canvas.shown.zip(app.canvas.pixels.clone()).filter(|(sh, _)| (sh.zoom - xf.zoom).abs() < 1e-9 && xf.rot == 0).map(|(sh, px)| { + let c = xf.to_canvas(bbox.min); + let k = sh.zoom * ppp as f64; + (((c.x - sh.origin.x) * k).round() as i64, ((c.y - sh.origin.y) * k).round() as i64, px) + }); + let at = from_canvas.as_ref().map(|(x, y, _)| (*x, *y)); let key = egui::Id::unique(("inverse_sel", st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, story.0)) - .with((runs.iter().map(|r| r.2.len() + r.3.len() * 7919).sum::(), w, h)) - .with((bbox.min.x.to_bits(), bbox.min.y.to_bits(), xf.zoom.to_bits(), st.selection.text.map(|t| (t.anchor, t.focus)))); + .with(&display) + .with((runs.iter().map(|r| r.1.len()).sum::(), w, h, preview)) + .with((at, app.canvas.pixels_generation, xf.zoom.to_bits(), xf.rot, st.selection.text.map(|t| (t.anchor, t.focus)))) + .with(at.is_none().then(|| (bbox.min.x.to_bits(), bbox.min.y.to_bits()))); let cache_id = egui::Id::unique("inverse_sel_tex"); let cached: Option<(egui::Id, egui::TextureHandle)> = ctx.data(|d| d.get_temp(cache_id)); let tex = match cached { Some((k, t)) if k == key => t, _ => { let view = xf.affine(ppp as f64, bbox.min); + // How much of each pixel the highlight covers. let mut rc = vello_cpu::RenderContext::new_with(w as u16, h as u16, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() }); - rc.set_paint(peniko::Color::from_rgba8(0, 0, 0, 255)); - for (_, m, quads, _) in runs { + rc.set_paint(peniko::Color::from_rgba8(255, 255, 255, 255)); + for (m, quads) in runs { rc.set_transform(view * *m); for q in quads { let mut bp = kurbo::BezPath::new(); @@ -230,41 +271,70 @@ fn draw_inverse_highlight( rc.fill_path(&bp); } } - let db = designcraft_fonts::FontDb::global(); - for (fi, m, _, glyphs) in runs { - let Some(ft) = cs.frames.get(*fi) else { continue }; - for &(li, gi) in glyphs { - let Some(l) = ft.lines.get(li) else { continue }; - let Some(g) = l.glyphs.get(gi) else { continue }; - let Some(style) = cs.styles.get(g.style as usize) else { continue }; - let Some(c) = doc.resolve_color(&style.fill, style.fill_tint) else { continue }; - let [r, gg, b, _] = c.to_rgba8(1.0); - rc.set_paint(peniko::Color::from_rgba8(255 - r, 255 - gg, 255 - b, 255)); - let outline = db.outline(&g.face, g.gid); - let skew = - if style.skew != 0.0 { Affine::new([1.0, 0.0, -style.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY }; - let shatai = style.shatai_xf(g, l.baseline).unwrap_or(Affine::IDENTITY); - let mut ga = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy); - if ft.vertical - && let Some(turn) = g.vertical_xf(l.baseline) - { - ga = turn * ga; - } - rc.set_transform(view * *m * ga); - rc.fill_path(&outline); - } - } rc.flush(); - let mut pm = vello_cpu::Pixmap::new(w as u16, h as u16); + let mut mask = vello_cpu::Pixmap::new(w as u16, h as u16); let mut res = vello_cpu::Resources::new(); - rc.render(&mut pm, &mut res); - let ci = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], pm.data_as_u8_slice()); + rc.render(&mut mask, &mut res); + let under = match &from_canvas { + Some((x0, y0, px)) => crop(px, *x0, *y0, w, h, [back.r(), back.g(), back.b()]), + None => { + // Rendered with the canvas's own options and colours, on this thread only (a + // pool per frame of a drag would cost more than the render). + let placed: Vec = + layout.slots.iter().map(|s| designcraft_render::Placed { spread: s.spread, xf: s.xf }).collect(); + let opts = screen_options(app, layout, preview, ppp as f64); + let mut under = HIGHLIGHT_RENDERER.with(|r| { + let mut r = r.borrow_mut(); + r.get_or_insert_with(|| { + let mut r = designcraft_render::Renderer::new(); + r.threads = 0; + r + }) + .render(doc, &app.session.cache, &placed, (w, h), view, &opts) + }); + if app.ui.proof_colors { + designcraft_render::proof_view(&mut under, &app.ui.proof_setup); + } + under.pixels + } + }; + let pixels = inverse_under(mask.data_as_u8_slice(), &under, [back.r(), back.g(), back.b()]); + let ci = egui::ColorImage::from_rgba_premultiplied([w as usize, h as usize], &pixels); let t = crate::widgets::load_texture(ctx, "inverse_selection", ci, egui::TextureOptions::NEAREST); ctx.data_mut(|d| d.insert_temp(cache_id, (key, t.clone()))); t } }; - painter.image(tex.id(), bbox, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); + if app.ui.screen_mode == crate::ScreenMode::Normal { + painter.image(tex.id(), bbox, uv, Color32::WHITE); + } else { + // Preview, Bleed, Slug: only where each spread shows its content, as the canvas. + for slot in &layout.slots { + let r = super::page_decor::shown_area(app, doc, xf, slot); + painter.with_clip_rect(r.intersect(painter.clip_rect())).image(tex.id(), bbox, uv, Color32::WHITE); + } + } +} + +/// Premultiplied RGBA: the inverse of `under` (composited over `back` where it is transparent), +/// shown as far as `mask` (premultiplied white) covers each pixel. +pub(super) fn inverse_under(mask: &[u8], under: &[u8], back: [u8; 3]) -> Vec { + let mut out = vec![0u8; mask.len()]; + let under = under.as_chunks::<4>().0.iter().chain(std::iter::repeat(&[0u8; 4])); + for ((o, m), u) in out.as_chunks_mut::<4>().0.iter_mut().zip(mask.as_chunks::<4>().0).zip(under) { + let cover = u32::from(m[3]); + if cover == 0 { + continue; + } + let a = u32::from(u[3]); + for k in 0..3 { + let shown = (u32::from(u[k]) + u32::from(back[k]) * (255 - a) / 255).min(255); + o[k] = ((255 - shown) * cover / 255) as u8; + } + o[3] = cover as u8; + } + out } /// View → Show Hidden Characters: ¶ paragraph ends, » tabs, · spaces, ¬ forced line breaks, # end of story. diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 53a77a6c5..293a1b1ce 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -573,6 +573,8 @@ impl CanvasCache { patches: 0, separations: separations::Preview::default(), images: (0, f64::NEG_INFINITY), + pixels: None, + pixels_generation: 0, } } } @@ -609,6 +611,10 @@ pub struct CanvasCache { /// The [`designcraft_render::images::generation`] the canvas renders with, and when it took /// it (ms): finished background decodes are taken up in batches, one render for many. pub images: (u64, f64), + /// The pixels the canvas texture shows (full resolution, as uploaded), and a counter that + /// changes with them: a text highlight inverts what it covers from these, without rendering. + pub pixels: Option>, + pub pixels_generation: u64, } #[derive(Default, Clone, Copy, Debug, Serialize)] From d9c20c9f816723913e7b846b73cef570a24dcde7 Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:03:10 +0100 Subject: [PATCH 2/5] Text selection: keep the canvas pixels only while text is selected; no highlight render on the UI thread while a texture is on its way The copy is renewed on the worker when text gets selected. Meanwhile, and with Separations Preview on, a plain highlight is drawn. A repaint of an edit's regions now goes through Proof Colors like a full upload. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/render.rs | 19 ++++++++++++++++--- crates/ui-egui/src/canvas/text_overlay.rs | 15 +++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/canvas/render.rs b/crates/ui-egui/src/canvas/render.rs index 55b168d1d..9e4dcdb4e 100644 --- a/crates/ui-egui/src/canvas/render.rs +++ b/crates/ui-egui/src/canvas/render.rs @@ -150,6 +150,11 @@ pub(super) fn image_generation(seen: &mut (u64, f64), live: u64, now: f64, rende pub(super) fn render_texture(app: &mut DesignApp, ctx: &egui::Context, rect: Rect, xf: &Xf, layout: &CanvasLayout, preview: bool) { invalidate_on_display_change(app); let Some(st) = app.session.active() else { return }; + // The copy of the canvas's pixels serves the text highlight only: none without a text + // selection, so a canvas without one holds no second full-size image. + if st.selection.text.is_none() { + app.canvas.pixels = None; + } let ppp = ctx.pixels_per_point() as f64; let doc_key = (st.uid, std::sync::Arc::as_ptr(&st.doc) as u64, st.revision, preview); let editing_parents = st.editing_parents; @@ -194,7 +199,10 @@ pub(super) fn render_texture(app: &mut DesignApp, ctx: &egui::Context, rect: Rec x0 >= -0.5 && y0 >= -0.5 && x0 + rect.width() as f64 <= s.size.0 as f64 + 0.5 && y0 + rect.height() as f64 <= s.size.1 as f64 + 0.5 } }; - if app.canvas.shown.is_some_and(|s| covers(&s)) { + // Text just selected: the highlight needs the canvas's pixels (see `upload`), so the view is + // rendered again, on the worker, to keep a copy. + let needs_pixels = app.canvas.pixels.is_none() && app.session.active().is_some_and(|st| st.selection.text.is_some()); + if app.canvas.shown.is_some_and(|s| covers(&s)) && !needs_pixels { return; } let doc_changed = app.canvas.shown.is_none_or(|s| s.doc != doc_key); @@ -313,7 +321,10 @@ fn patch_texture(app: &mut DesignApp, layout: &CanvasLayout, ppp: f64, doc_key: * Affine::scale(sh.zoom) * Affine::translate((-sh.origin.x, -sh.origin.y)); let opts = screen_options(app, layout, preview, ppp); - let img = app.canvas.patcher.render(&new, &app.session.cache, &placed, ((x1 - x0) as u32, (y1 - y0) as u32), view, &opts); + let mut img = app.canvas.patcher.render(&new, &app.session.cache, &placed, ((x1 - x0) as u32, (y1 - y0) as u32), view, &opts); + // Proof Colors as for a full upload: the repainted region (and the highlight's copy of it) + // showed the unproofed colours until the next full render. + screen_post(app, &mut img); let ci = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); if let Some(tex) = app.canvas.texture.as_mut() { tex.set_partial([x0 as usize, y0 as usize], ci, egui::TextureOptions::LINEAR); @@ -363,6 +374,8 @@ fn upload(app: &mut DesignApp, ctx: &egui::Context, mut img: designcraft_render: Some(tex) => tex.set(ci, egui::TextureOptions::LINEAR), None => app.canvas.texture = Some(ctx.load_texture("canvas", ci, egui::TextureOptions::LINEAR)), } - app.canvas.pixels = Some(std::sync::Arc::new(img)); + // Kept only while text is selected (see `render_texture`). + let selecting = app.session.active().is_some_and(|st| st.selection.text.is_some()); + app.canvas.pixels = selecting.then(|| std::sync::Arc::new(img)); app.canvas.pixels_generation += 1; } diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs index 30a00930b..e8cf84b4e 100644 --- a/crates/ui-egui/src/canvas/text_overlay.rs +++ b/crates/ui-egui/src/canvas/text_overlay.rs @@ -244,6 +244,21 @@ fn draw_inverse_highlight( let k = sh.zoom * ppp as f64; (((c.x - sh.origin.x) * k).round() as i64, ((c.y - sh.origin.y) * k).round() as i64, px) }); + // Without the canvas's pixels the area would be rendered here, on the UI thread. That is + // done for a turned view (its texture never matches; cached until the view or selection + // changes), but not on every frame of a zoom or right after text is selected, when the worker + // is already bringing a texture with its pixels: meanwhile, and with Separations Preview on + // (which shows a plate, not the composite the canvas pixels hold), a plain highlight. + let waiting = from_canvas.is_none() && xf.rot == 0 && app.canvas.pending.is_some(); + if app.ui.separations.is_some() || waiting { + for (m, quads) in runs { + for q in quads { + let poly = q.map(|p| to_screen(*m, p)); + painter.add(egui::Shape::convex_polygon(poly.to_vec(), Color32::from_rgba_unmultiplied(80, 140, 255, 110), Stroke::NONE)); + } + } + return; + } let at = from_canvas.as_ref().map(|(x, y, _)| (*x, *y)); let key = egui::Id::unique(("inverse_sel", st.uid, st.revision, std::sync::Arc::as_ptr(&st.doc) as usize, story.0)) .with(&display) From e3b29cda79c82fe526038f8307790dc2011b01a0 Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:30:04 +0100 Subject: [PATCH 3/5] Effects dialog: a colour chip beside the shadow and glow colour, and in its menu Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/dialogs.rs | 2 +- crates/ui-egui/src/effects_dialog.rs | 56 +++++++++++++++++++++++----- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 336cf6409..03421678f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -6608,7 +6608,7 @@ fn link_toggle(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, key: &str, linked: /// A swatch menu with a colour chip per swatch (hidden swatches left out); returns the swatch /// picked. -fn swatch_menu(ui: &mut egui::Ui, doc: &designcraft_doc::Document, id: impl egui::AsIdSalt, current: &str, width: f32) -> Option { +pub(crate) fn swatch_menu(ui: &mut egui::Ui, doc: &designcraft_doc::Document, id: impl egui::AsIdSalt, current: &str, width: f32) -> Option { swatch_menu_with(ui, doc, id, current, width, None) } diff --git a/crates/ui-egui/src/effects_dialog.rs b/crates/ui-egui/src/effects_dialog.rs index a09b87498..650219bd2 100644 --- a/crates/ui-egui/src/effects_dialog.rs +++ b/crates/ui-egui/src/effects_dialog.rs @@ -337,15 +337,15 @@ fn swatch(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog, path: &[&str]) { } v.as_str().unwrap_or("[Black]").to_string() }; - let names: Vec = app - .session - .active() - .map_or_else(Vec::new, |st| st.doc.swatches.iter().filter(|w| !w.hidden || w.name == cur).map(|w| w.name.clone()).collect()); - craft_ui::ComboBox::from_id_salt(("fx_swatch", path.join("."))).selected_text(&cur).width(150.0).show_ui(ui, |ui| { - for n in names { - if ui.selectable_label(n == cur, &n).clicked() { - set(d, path, json!(n)); - } + let Some(doc) = app.session.active().map(|st| &st.doc) else { return }; + // The colour itself beside its name, and a chip per swatch in the menu, as the swatch menus + // elsewhere: a list of bare names hid what the shadow was coloured with. + ui.horizontal(|ui| { + let (c, g) = crate::widgets::swatch_colors(doc, &cur, 1.0); + let (r, _) = ui.allocate_exact_size(egui::vec2(16.0, 16.0), egui::Sense::hover()); + crate::widgets::paint_chip(ui.painter(), r, c, g); + if let Some(n) = crate::dialogs::swatch_menu(ui, doc, ("fx_swatch", path.join(".")), &cur, 128.0) { + set(d, path, json!(n)); } }); } @@ -935,6 +935,44 @@ mod tests { assert_eq!(fx.outer_glow.mode, designcraft_color::BlendMode::Normal); } + #[test] + fn the_shadow_colour_shows_its_swatch_beside_the_name() { + let (mut app, _) = app_with_frame(); + app.run("swatch.create", json!({"name": "Shade", "color": "#12ab34"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx, "en"); + let shade = crate::widgets::swatch_colors(&app.session.doc().unwrap().doc, "Shade", 1.0).0.unwrap(); + // Does the dialog, once faded in, paint a chip of the colour `c`? + let mut time = 0.0; + let mut painted = |app: &mut DesignApp, c: egui::Color32| { + let mut found = false; + for _ in 0..20 { + time += 0.1; + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + time: Some(time), + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| crate::dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + fn walk(s: &egui::epaint::Shape, c: egui::Color32) -> bool { + match s { + egui::epaint::Shape::Rect(r) => r.fill == c, + egui::epaint::Shape::Vec(v) => v.iter().any(|s| walk(s, c)), + _ => false, + } + } + found = out.shapes.iter().any(|s| walk(&s.shape, c)); + } + found + }; + open(&mut app, "dropShadow"); + assert!(!painted(&mut app, shade), "not the shadow's colour yet"); + set(app.ui.dialog.as_mut().unwrap(), &["dropShadow", "color"], json!("Shade")); + assert!(painted(&mut app, shade), "the chosen swatch's colour is shown, not only its name"); + assert_eq!(params(app.ui.dialog.as_ref().unwrap())["effects"]["dropShadow"]["color"], "Shade"); + } + #[test] fn offsets_follow_distance_and_angle_as_in_indesign() { let (mut app, _) = app_with_frame(); From a74f3ff5d3721898c081da02334480205ea29c09 Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:30:04 +0100 Subject: [PATCH 4/5] Effects panel: drop shadow Distance and Size have room for a measurement with its unit Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/panels/properties/object_panels.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/properties/object_panels.rs b/crates/ui-egui/src/panels/properties/object_panels.rs index 194fecc2e..a2756621d 100644 --- a/crates/ui-egui/src/panels/properties/object_panels.rs +++ b/crates/ui-egui/src/panels/properties/object_panels.rs @@ -548,9 +548,11 @@ pub fn effects_panel(app: &mut DesignApp, ui: &mut egui::Ui) { // Distance and Size in the document's unit, as in the Effects dialog: a bare `7` means the // same in both. let u = units(app); + // Room for a measurement with its unit (`35.278 mm`). + const MEASURE_W: f32 = 66.0; egui::Grid::new("dsg").num_columns(4).spacing(vec2(6.0, 4.0)).show(ui, |ui| { caption(ui, crate::i18n::tr(&app.ui.language, "Distance")); - if let Some(v) = measure(ui, "dsd", Some(ds.distance), u, 56.0) { + if let Some(v) = measure(ui, "dsd", Some(ds.distance), u, MEASURE_W) { let _ = app.run("object.dropShadow", json!({"on": true, "distance": v})); } caption(ui, crate::i18n::tr(&app.ui.language, "Angle")); @@ -577,7 +579,7 @@ pub fn effects_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let _ = app.run("object.dropShadow", json!({"on": true, "opacity": v / 100.0})); } caption(ui, crate::i18n::tr(&app.ui.language, "Size")); - if let Some(v) = measure(ui, "dss", Some(ds.size), u, 56.0) { + if let Some(v) = measure(ui, "dss", Some(ds.size), u, MEASURE_W) { let _ = app.run("object.dropShadow", json!({"on": true, "size": v})); } ui.end_row(); From dd41a9692a37ca9f455acb5e425817a6b614c4da Mon Sep 17 00:00:00 2001 From: PiMinusMax <121135695+PiMinusMax@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:36:38 +0100 Subject: [PATCH 5/5] Text highlight: the plain fill is clipped to the shown area, and a turned view uses it The plain highlight (waiting for the canvas's pixels, or with Separations Preview on) is clipped to each spread's shown area in Preview, Bleed and Slug, like the inverted one. A turned view, whose canvas pixels never match, draws the plain highlight instead of rendering what lies under the selection on the UI thread at every zoom or selection change. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/canvas/tests.rs | 67 +++++++++++++++++++++++ crates/ui-egui/src/canvas/text_overlay.rs | 44 ++++++++------- 2 files changed, 92 insertions(+), 19 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 3c5e791b0..c42abe16e 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -3567,3 +3567,70 @@ fn the_text_highlight_follows_the_display_options() { let after = cached(&h).expect("the highlight is drawn"); assert_ne!(after, before, "a new display option: the highlight is drawn again"); } + +/// The highlight's plain fill (painted at `h`'s last frame) and the rects it is clipped to. +fn plain_highlights(h: &Harness<'_, crate::test_window::Window>) -> Vec { + h.output() + .shapes + .iter() + .filter(|c| matches!(&c.shape, egui::Shape::Path(p) if p.fill == super::text_overlay::PLAIN_HIGHLIGHT)) + .map(|c| c.clip_rect) + .collect() +} + +/// A selected text frame that runs past the page's left edge, in a new document. +fn text_past_the_page_edge() -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", serde_json::json!({})).unwrap(); + let text = "Some text past the edge"; + app.run("frame.create", serde_json::json!({"rect": [-150, 72, 300, 200], "content": "text", "text": text, "caret": true})).unwrap(); + app.run("edit.selectAll", serde_json::json!({})).unwrap(); + app.run("type.char", serde_json::json!({"attrs": {"size": 28}})).unwrap(); + app +} + +/// In Preview the plain highlight (here with Separations Preview on) shows only on the page, as +/// the inverted one does: not on the pasteboard where the selection runs past the trim. +#[test] +fn the_plain_text_highlight_is_clipped_to_the_shown_area() { + let mut app = text_past_the_page_edge(); + app.ui.separations = Some(crate::separations::Separations::default()); + let mut h = crate::test_window::open(app, vec2(900.0, 600.0)); + h.run_steps(6); + assert!(plain_highlights(&h).iter().any(|c| c.left() < page_left(&h) - 1.0), "Normal: on the pasteboard too"); + h.state_mut().app.ui.screen_mode = ScreenMode::Preview; + h.run_steps(4); + let clips = plain_highlights(&h); + assert!(!clips.is_empty(), "the highlight is drawn"); + let left = page_left(&h); + assert!(clips.iter().all(|c| c.left() >= left - 0.5), "only on the page: {clips:?}, page from {left}"); +} + +/// The page's left edge on screen. +fn page_left(h: &Harness<'_, crate::test_window::Window>) -> f32 { + let app = &h.state().app; + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let canvas = app.session.layout().xf(designcraft_doc::SpreadRef::Doc(0)); + xf.to_screen(canvas * Point::new(0.0, 100.0)).x +} + +/// In a turned view the canvas's pixels never match, so the highlight is not rendered on the UI +/// thread: neither when text is selected nor on each zoom step, which get the plain highlight. +#[test] +fn a_turned_view_draws_the_plain_highlight_while_zooming() { + let mut h = crate::test_window::open(text_past_the_page_edge(), vec2(900.0, 600.0)); + let rendered = |h: &Harness<'_, crate::test_window::Window>| { + h.ctx.data(|d| d.get_temp::<(egui::Id, egui::TextureHandle)>(egui::Id::unique("inverse_sel_tex"))).is_some() + }; + h.state_mut().app.view_mut().unwrap().rotation = 1; + // What the unturned view drew when the window opened goes; a turned view adds nothing. + h.ctx.data_mut(|d| d.remove::<(egui::Id, egui::TextureHandle)>(egui::Id::unique("inverse_sel_tex"))); + h.run_steps(6); + assert!(!rendered(&h), "selected in a turned view: nothing rendered"); + for zoom in [1.0, 1.5, 2.0] { + h.state_mut().app.view_mut().unwrap().zoom *= zoom; + h.run_steps(2); + assert!(!plain_highlights(&h).is_empty(), "zoom ×{zoom}: the plain highlight"); + assert!(!rendered(&h), "zoom ×{zoom}: nothing rendered for it"); + } +} diff --git a/crates/ui-egui/src/canvas/text_overlay.rs b/crates/ui-egui/src/canvas/text_overlay.rs index e8cf84b4e..12d9b43ee 100644 --- a/crates/ui-egui/src/canvas/text_overlay.rs +++ b/crates/ui-egui/src/canvas/text_overlay.rs @@ -244,17 +244,26 @@ fn draw_inverse_highlight( let k = sh.zoom * ppp as f64; (((c.x - sh.origin.x) * k).round() as i64, ((c.y - sh.origin.y) * k).round() as i64, px) }); - // Without the canvas's pixels the area would be rendered here, on the UI thread. That is - // done for a turned view (its texture never matches; cached until the view or selection - // changes), but not on every frame of a zoom or right after text is selected, when the worker - // is already bringing a texture with its pixels: meanwhile, and with Separations Preview on - // (which shows a plate, not the composite the canvas pixels hold), a plain highlight. - let waiting = from_canvas.is_none() && xf.rot == 0 && app.canvas.pending.is_some(); - if app.ui.separations.is_some() || waiting { - for (m, quads) in runs { - for q in quads { - let poly = q.map(|p| to_screen(*m, p)); - painter.add(egui::Shape::convex_polygon(poly.to_vec(), Color32::from_rgba_unmultiplied(80, 140, 255, 110), Stroke::NONE)); + // Preview, Bleed, Slug: only where each spread shows its content, as the canvas. + let clips: Vec = if app.ui.screen_mode == crate::ScreenMode::Normal { + vec![painter.clip_rect()] + } else { + layout.slots.iter().map(|slot| super::page_decor::shown_area(app, doc, xf, slot).intersect(painter.clip_rect())).collect() + }; + // Without the canvas's pixels the area would be rendered here, on the UI thread. That is not + // done on a frame of a zoom or right after text is selected, when the worker is already + // bringing a texture with its pixels, nor in a turned view, whose texture never matches (every + // zoom or selection change would render again): there, and with Separations Preview on (which + // shows a plate, not the composite the canvas pixels hold), a plain highlight. + let waiting = from_canvas.is_none() && app.canvas.pending.is_some(); + if app.ui.separations.is_some() || waiting || xf.rot != 0 { + for clip in &clips { + let painter = painter.with_clip_rect(*clip); + for (m, quads) in runs { + for q in quads { + let poly = q.map(|p| to_screen(*m, p)); + painter.add(egui::Shape::convex_polygon(poly.to_vec(), PLAIN_HIGHLIGHT, Stroke::NONE)); + } } } return; @@ -321,17 +330,14 @@ fn draw_inverse_highlight( } }; let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - if app.ui.screen_mode == crate::ScreenMode::Normal { - painter.image(tex.id(), bbox, uv, Color32::WHITE); - } else { - // Preview, Bleed, Slug: only where each spread shows its content, as the canvas. - for slot in &layout.slots { - let r = super::page_decor::shown_area(app, doc, xf, slot); - painter.with_clip_rect(r.intersect(painter.clip_rect())).image(tex.id(), bbox, uv, Color32::WHITE); - } + for clip in &clips { + painter.with_clip_rect(*clip).image(tex.id(), bbox, uv, Color32::WHITE); } } +/// The highlight where the inverse of what lies under it isn't at hand. +pub(super) const PLAIN_HIGHLIGHT: Color32 = Color32::from_rgba_premultiplied(35, 60, 110, 110); + /// Premultiplied RGBA: the inverse of `under` (composited over `back` where it is transparent), /// shown as far as `mask` (premultiplied white) covers each pixel. pub(super) fn inverse_under(mask: &[u8], under: &[u8], back: [u8; 3]) -> Vec {