Boards: preview marker and highlighter strokes as they are drawn (#2505)

This commit is contained in:
ViktorBystrov72
2026-11-23 18:12:40 +05:00
committed by Bystrov Viktor
parent b828e6c75a
commit dbf0c59620
18 changed files with 364 additions and 70 deletions
+8
View File
@@ -119,6 +119,14 @@ pub struct BoardTool {
pub highlighter: Color,
}
impl BoardTool {
/// A board ink tool's current colour, stroke width and opacity.
pub fn ink_style(&self, highlighter: bool) -> (Color, f64, f32) {
let (weight, opacity) = if highlighter { HIGHLIGHTER } else { MARKER };
(if highlighter { self.highlighter } else { self.marker }, weight, opacity)
}
}
impl Default for BoardTool {
fn default() -> Self {
let first = BOARD_COLORS.first().map_or(Color::WHITE, |c| c.1);
+30 -11
View File
@@ -1,10 +1,10 @@
use super::connectors::{CAPS, make};
use super::{
AUTHOR_INK, Affine, AutoLayout, BlendMode, BoardItem, BoardShape, Color, Connector, Constraints, CrossAlign, Document, Effect, EffectKind, End,
EngineError, HConstraint, HIGHLIGHTER, INK, LayoutMode, MARKER, MainAlign, Node, NodeId, NodeKind, Paint, Result, SHAPE, STAMP_SIZE, STICKY,
STICKY_GAP, STICKY_PAD, Session, Shadow, Side, Sizing, StrokeAlign, StrokeCap, StrokeJoin, TextAlignH, TextAutoResize, TextData, VConstraint,
Value, VectorNetwork, author, bad, boolean, color_param, get, id, id_of, json, line_shade, num, num_or, parent_of, req_num, require, shape_of,
stamp_of, string, textedit,
EngineError, HConstraint, INK, LayoutMode, MainAlign, Node, NodeId, NodeKind, Paint, Result, SHAPE, STAMP_SIZE, STICKY, STICKY_GAP, STICKY_PAD,
Session, Shadow, Side, Sizing, StrokeAlign, StrokeCap, StrokeJoin, TextAlignH, TextAutoResize, TextData, VConstraint, Value, VectorNetwork,
author, bad, boolean, color_param, get, id, id_of, json, line_shade, num, num_or, parent_of, req_num, require, shape_of, stamp_of, string,
textedit,
};
/// A new layer at the top of `parent`, at `at` in it, made by `f`.
@@ -376,16 +376,14 @@ pub(super) fn ink_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "board.ink";
require(s, cmd)?;
let high = boolean(p, "highlighter").unwrap_or(false);
let color = color_param(cmd, p)?.unwrap_or(if high { s.tool.board.highlighter } else { s.tool.board.marker });
let (weight, opacity) = if high { HIGHLIGHTER } else { MARKER };
let (default_color, weight, opacity) = s.tool.board.ink_style(high);
let color = color_param(cmd, p)?.unwrap_or(default_color);
if get(p, "path").is_none() && get(p, "points").is_none() {
return Err(bad(cmd, "`path` or `points` is required"));
}
let page = s.page()?;
let select = boolean(p, "select").unwrap_or(true);
let mut q = json!({"type": "vector", "parent": page, "closed": false, "select": select, "name": if high { "Highlight" } else { "Ink" }, "props": {
"fills": [], "strokes": [color.to_css_hex()], "strokeWeight": weight, "strokeCap": "round", "strokeJoin": "round", "strokeAlign": "center",
}});
let mut q = json!({"type": "vector", "parent": page, "closed": false, "select": select, "name": if high { "Highlight" } else { "Ink" }});
for k in ["path", "points"] {
if let (Some(v), Some(o)) = (get(p, k), q.as_object_mut()) {
o.insert(k.into(), v.clone());
@@ -393,11 +391,32 @@ pub(super) fn ink_cmd(s: &mut Session, p: &Value) -> Result<Value> {
}
let made = crate::cmd::create::create(s, &q)?;
let id = made.get("id").and_then(id_of).ok_or_else(|| EngineError::Other("no stroke made".into()))?;
let n = s.doc_mut()?.get_mut(id)?;
style_ink(s.doc_mut()?.get_mut(id)?, (color, weight, opacity), high);
Ok(json!({"id": id}))
}
fn style_ink(n: &mut Node, (color, weight, opacity): (Color, f64, f32), high: bool) {
// Use the same eight-bit colour the ink command used to pass as a CSS hex string.
let [r, g, b, a] = color.to_rgba8();
n.fills.clear();
n.strokes = vec![Paint::solid(Color::from_rgba8(r, g, b, a))];
n.stroke.weight = weight;
n.stroke.cap_start = StrokeCap::Round;
n.stroke.cap_end = StrokeCap::Round;
n.stroke.join = StrokeJoin::Round;
n.stroke.align = StrokeAlign::Center;
n.opacity = opacity;
if high {
n.blend = BlendMode::Multiply;
}
n.board = Some(BoardItem::Ink);
Ok(json!({"id": id}))
}
/// Insert the live highlighter into the preview document so it blends with the actual backdrop.
pub(super) fn preview_highlighter(doc: &mut Document, page: NodeId, path: &str, style: (Color, f64, f32)) -> Result<()> {
let shape = crate::cmd::create::path_network("board.ink", path, None, None)?;
let mut network = shape.network;
network.regions.clear();
add(doc, page, NodeKind::Vector { network }, "Highlight", shape.offset, (shape.width, shape.height), |n| style_ink(n, style, true))?;
Ok(())
}
+28 -1
View File
@@ -1,7 +1,9 @@
use std::sync::atomic::{AtomicU64, Ordering};
use super::connectors::{CAPS, at_json, end_json, make, other_end, side_json};
use super::derived::{ends_now, route};
use super::edit::label_of;
use super::items::edit_text;
use super::items::{edit_text, preview_highlighter};
use super::{
BoardItem, Connector, Document, ERASER_PX, End, EngineError, Gesture, NodeId, Point, PointerEvent, Result, SHAPE, STICKY, Session, Side, ToolId,
id_of, is_board, json,
@@ -10,6 +12,7 @@ use super::{
/// How near (screen pixels) the pointer must be to the middle of an object's side for a connector
/// end to attach there, however small the object is on screen.
const ATTACH_PX: f64 = 10.0;
static NEXT_HIGHLIGHTER_GENERATION: AtomicU64 = AtomicU64::new(1);
/// Point `p` as fractions of box `b` (`None`: a box with no area).
fn part_at(b: figcraft_geom::Rect, p: Point) -> Option<[f64; 2]> {
@@ -71,6 +74,9 @@ impl Session {
Ok(())
}
ToolId::Marker | ToolId::Highlighter => {
if self.tool.tool == ToolId::Highlighter {
self.tool.highlighter_generation = NEXT_HIGHLIGHTER_GENERATION.fetch_add(1, Ordering::Relaxed);
}
self.tool.gesture = Gesture::Pencil { points: vec![ev.p()], pressure: vec![ev.pressure] };
Ok(())
}
@@ -266,6 +272,27 @@ impl Session {
self.commit_interaction()
}
/// Update the render-only document after the pointer extends a highlighter stroke.
pub(crate) fn highlighter_drag(&mut self, path: &str) -> Result<()> {
let ds = self.ds()?;
let (uid, page, source) = (ds.uid, ds.page, ds.doc.clone());
let mut doc = (*source).clone();
preview_highlighter(&mut doc, page, path, self.tool.board.ink_style(true))?;
self.tool.highlighter_preview = Some(crate::tools::HighlighterPreview { uid, page, source, doc: std::sync::Arc::new(doc) });
Ok(())
}
/// The canvas's preview of a live highlighter stroke on the current page and document.
pub fn highlighter_preview_doc(&self) -> Option<(std::sync::Arc<Document>, u64)> {
if self.tool.tool != ToolId::Highlighter || !matches!(&self.tool.gesture, Gesture::Pencil { points, .. } if points.len() >= 2) {
return None;
}
let preview = self.tool.highlighter_preview.as_ref()?;
let ds = self.ds().ok()?;
(preview.uid == ds.uid && preview.page == ds.page && std::sync::Arc::ptr_eq(&preview.source, &ds.doc))
.then(|| (preview.doc.clone(), self.tool.highlighter_generation))
}
/// A finished marker or highlighter stroke (page points).
pub(crate) fn ink_finish(&mut self, path: &str) -> Result<()> {
let high = self.tool.tool == ToolId::Highlighter;
+11
View File
@@ -587,10 +587,21 @@ pub struct PenPath {
pub undone: Vec<(Point, Vec2, Vec2)>,
}
/// A stroke composited by the canvas renderer while the real document stays unchanged.
#[derive(Clone, Debug)]
pub(crate) struct HighlighterPreview {
pub uid: u64,
pub page: NodeId,
pub source: std::sync::Arc<Document>,
pub doc: std::sync::Arc<Document>,
}
#[derive(Clone, Debug, Default)]
pub struct ToolState {
pub tool: ToolId,
pub(crate) gesture: Gesture,
pub(crate) highlighter_generation: u64,
pub(crate) highlighter_preview: Option<HighlighterPreview>,
pub overlay: Overlay,
pub pen: Option<PenPath>,
/// Tool to return to after a temporary tool (space → hand).
+5 -1
View File
@@ -445,7 +445,11 @@ impl Session {
Gesture::Pencil { points, pressure } => {
let (mut pts, mut pressure) = (points.clone(), pressure.clone());
pencil_add(&mut pts, &mut pressure, ev);
self.tool.overlay.pen = pts.iter().map(|p| [p.x, p.y]).collect();
if self.tool.tool != ToolId::Highlighter {
self.tool.overlay.pen = pts.iter().map(|p| [p.x, p.y]).collect();
} else if pts.len() >= 2 {
self.highlighter_drag(&super::pen::fitted_ink_path(&pts).to_svg())?;
}
self.tool.gesture = Gesture::Pencil { points: pts, pressure };
if let Ok(ds) = self.ds_mut() {
ds.revision += 1;
+1
View File
@@ -240,6 +240,7 @@ impl Session {
Gesture::Pencil { mut points, mut pressure } => {
self.tool.overlay.pen.clear();
self.tool.overlay.pen_color = None;
self.tool.highlighter_preview = None;
// The stroke ends where the button came up, even without a move to get there.
pencil_add(&mut points, &mut pressure, ev);
self.pencil_finish(&points, &pressure)?;
+1
View File
@@ -113,6 +113,7 @@ impl Session {
}
if self.tool.busy() {
self.tool.gesture = Gesture::None;
self.tool.highlighter_preview = None;
self.tool.overlay = Overlay::default();
return self.cancel_interaction();
}
+14 -11
View File
@@ -313,17 +313,7 @@ impl Session {
if points.len() < 2 {
return Ok(());
}
// Smooth: fit a curve through the samples, kept from shooting past them where the stroke
// turns back or runs nearly straight (#1741).
let mut poly = figcraft_geom::BezPath::new();
for (k, p) in points.iter().enumerate() {
if k == 0 {
poly.move_to(*p);
} else {
poly.line_to(*p);
}
}
let fitted = figcraft_geom::simplify_path(&poly, 0.75);
let fitted = fitted_ink_path(points);
let d = fitted.to_svg();
if matches!(self.tool.tool, ToolId::Marker | ToolId::Highlighter) {
return self.ink_finish(&d);
@@ -361,3 +351,16 @@ impl Session {
Ok(super::handles::pencil_color(doc, parent))
}
}
/// Fit a curve through the samples without overshooting when a stroke turns back or nearly
/// follows a straight line (#1741).
pub(super) fn fitted_ink_path(points: &[Point]) -> figcraft_geom::BezPath {
let mut poly = figcraft_geom::BezPath::new();
if let Some((first, rest)) = points.split_first() {
poly.move_to(*first);
for point in rest {
poly.line_to(*point);
}
}
figcraft_geom::simplify_path(&poly, 0.75)
}
@@ -89,6 +89,7 @@ impl Session {
}
self.tool.tool = t;
self.tool.gesture = Gesture::None;
self.tool.highlighter_preview = None;
self.tool.pick_only = false;
// The tool's cursor shows before the pointer moves.
self.tool.overlay =
@@ -119,6 +120,7 @@ impl Session {
/// as Escape does; the UI calls it when Dev Mode starts, where nothing may move.
pub fn drop_gesture(&mut self) -> Result<()> {
self.tool.gesture = Gesture::None;
self.tool.highlighter_preview = None;
self.cancel_interaction()
}
+1 -1
View File
@@ -87,7 +87,7 @@ impl FigApp {
figcraft_render::Work::Partial { pixels } => json!({"kind": "partial", "pixels": pixels}),
figcraft_render::Work::Full => json!({"kind": "full"}),
}),
"quality": if self.canvas.tex_coarse { "preview" } else { "refined" },
"quality": if self.canvas.shown_coarse() { "preview" } else { "refined" },
"previewLatencyMs": self.canvas.preview_latency_ms,
"refineLatencyMs": self.canvas.refine_latency_ms,
// The share of the canvas only the page colour covered last frame (no render reached it).
+75
View File
@@ -297,6 +297,81 @@ fn a_selected_connector_shows_its_ends_as_handles() {
}
}
fn drag_board_ink(u: &mut Ui) -> (Pos2, Pos2, egui::FullOutput) {
let zoom = u.app.session.ds().unwrap().view.zoom;
let start = u.app.to_screen(10.0 / zoom, 20.0 / zoom);
u.button(start, true);
for i in 1..=5 {
let point = u.app.to_screen((10.0 + 14.0 * f64::from(i)) / zoom, (20.0 + 8.0 * f64::from(i % 2)) / zoom);
u.frame(vec![Event::PointerMoved(point)]);
}
let end = u.app.to_screen(94.0 / zoom, 20.0 / zoom);
let frame = u.frame_output(vec![Event::PointerMoved(end)]);
(start, end, frame)
}
#[test]
fn board_marker_preview_keeps_the_stroke_width_when_zoomed_out() {
let mut u = board();
u.app.session.ds_mut().unwrap().view.zoom = 0.1;
u.app.run("tool.marker", json!({"color": "#3067A9"}));
u.frame(vec![]);
let (start, end, frame) = drag_board_ink(&mut u);
let preview = flat(&frame.shapes)
.into_iter()
.find_map(|shape| match shape {
egui::Shape::Path(path)
if !path.closed
&& path.points.len() >= 3
&& path.points.first().is_some_and(|p| p.distance(start) < 0.5)
&& path.points.last().is_some_and(|p| p.distance(end) < 0.5) =>
{
Some(path.stroke)
}
_ => None,
})
.expect("the stroke preview connects the sampled points");
u.button(end, false);
let ds = u.app.session.ds().unwrap();
let ink = ds.doc.nodes().find(|node| node.board == Some(BoardItem::Ink)).expect("a completed ink stroke");
let width = (ink.stroke.weight * ds.view.zoom) as f32;
assert!((preview.width - width).abs() < 0.01, "preview width {} at this zoom, committed width {width}", preview.width);
let expected = crate::theme::doc_c32(&u.ctx, ink.strokes[0].solid_color().unwrap());
assert_eq!(preview.color, egui::epaint::ColorMode::Solid(expected));
}
#[test]
fn board_highlighter_preview_multiplies_with_the_same_backdrop_as_the_committed_stroke() {
for background in ["#72C694", "#000000"] {
let mut u = board();
u.app.session.ds_mut().unwrap().view.zoom = 1.0;
u.app.run("page.setBackground", json!({"color": background}));
u.app.run("tool.highlighter", json!({"color": "#3067A9"}));
u.frame(vec![]);
let scale = f64::from(u.ctx.pixels_per_point()) * u.app.session.ds().unwrap().view.zoom;
let view = figcraft_render::View { origin: (0.0, 0.0), scale, width: 128, height: 64 };
let opts = figcraft_render::Options { background: figcraft_color::Color::from_hex(background), ..Default::default() };
let render = |u: &Ui| {
let ds = u.app.session.ds().unwrap();
figcraft_render::render_view(&u.app.canvas_document(ds).0, ds.page, &view, &opts).unwrap().data().to_vec()
};
let original = render(&u);
let undo = u.app.session.undo_labels(10);
let (_, end, _) = drag_board_ink(&mut u);
let preview = render(&u);
assert!(!u.app.session.doc().unwrap().nodes().any(|node| node.board == Some(BoardItem::Ink)));
assert_eq!(u.app.session.undo_labels(10), undo, "preview does not add undo entries");
u.button(end, false);
let committed = render(&u);
assert!(preview == committed, "preview and final ink should blend identically over {background}");
assert_eq!(committed == original, background == "#000000", "Multiply should preserve black and darken colour");
let (_, end, _) = drag_board_ink(&mut u);
u.app.session.escape().unwrap();
u.button(end, false);
assert!(render(&u) == committed, "Escape discards the second preview");
}
}
#[test]
fn the_board_grid_follows_its_settings() {
let mut u = board();
+92 -28
View File
@@ -59,6 +59,8 @@ pub struct CanvasState {
pub tex_coarse: bool,
/// The request the texture answers ([`crate::render_worker::Done::seq`]).
tex_seq: u64,
/// The drawn highlighter is separate from the stable texture and the page cache.
highlighter: Option<HighlighterTexture>,
/// Refined images of the files and pages shown before, newest first: switching back to one
/// shows its image at once while it renders again, instead of a blank canvas (and, where
/// renders are slow, a coarse preview).
@@ -109,6 +111,7 @@ impl Default for CanvasState {
tex_of: None,
tex_coarse: false,
tex_seq: 0,
highlighter: None,
kept: Vec::new(),
surround: None,
submitted: None,
@@ -144,12 +147,44 @@ struct Kept {
seq: u64,
}
struct HighlighterTexture {
texture: egui::TextureHandle,
view: figcraft_render::View,
of: (u64, NodeId),
generation: u64,
coarse: bool,
seq: u64,
}
impl CanvasState {
fn requested_highlighter(&self) -> Option<u64> {
self.submitted.as_ref().and_then(|job| job.highlighter_generation)
}
fn shown_highlighter(&self) -> Option<&HighlighterTexture> {
self.highlighter.as_ref().filter(|preview| Some(preview.generation) == self.requested_highlighter())
}
fn shown_texture(&self, shown: Option<(u64, NodeId)>) -> Option<(&egui::TextureHandle, &figcraft_render::View)> {
let shown = shown?;
if let Some(preview) = self.shown_highlighter().filter(|preview| preview.of == shown) {
return Some((&preview.texture, &preview.view));
}
(self.tex_of == Some(shown)).then(|| self.texture.as_ref().zip(self.tex_view.as_ref())).flatten()
}
pub(crate) fn shown_coarse(&self) -> bool {
self.shown_highlighter().map_or(self.tex_coarse, |preview| preview.coarse)
}
/// When the file or page shown is no longer the one the texture is of, set the texture aside
/// (if refined) and bring back the image kept for `shown`, if any. Images of files that are no
/// longer open (`open` says which are) are dropped every frame, not only on a switch: a
/// background tab can close while the file shown stays the same.
fn switch_texture(&mut self, shown: Option<(u64, NodeId)>, open: impl Fn(u64) -> bool) {
if self.highlighter.as_ref().is_some_and(|preview| Some(preview.generation) != self.requested_highlighter() || Some(preview.of) != shown) {
self.highlighter = None;
}
if shown.is_some() && self.tex_of != shown {
let back = self.kept.iter().position(|k| Some(k.of) == shown).map(|i| self.kept.remove(i));
let (texture, view, of) = (self.texture.take(), self.tex_view.take(), self.tex_of.take());
@@ -207,6 +242,16 @@ impl FigApp {
let (doc, pe, caret) = self.preedit_key()?;
(Arc::ptr_eq(&p.key.0, &doc) && p.key.1 == pe && p.key.2 == caret).then_some(p)
}
pub(crate) fn canvas_document(&self, ds: &figcraft_engine::DocState) -> (Arc<Document>, Option<u64>) {
if let Some(preedit) = self.preedit_view() {
(preedit.doc.clone(), None)
} else if let Some((doc, generation)) = self.session.highlighter_preview_doc() {
(doc, Some(generation))
} else {
(ds.doc.clone(), None)
}
}
}
impl FigApp {
@@ -319,35 +364,11 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
let shown = app.session.ds().map(|ds| (ds.uid, ds.page)).ok();
let docs = &app.session.docs;
app.canvas.switch_texture(shown, |uid| docs.iter().any(|d| d.uid == uid));
if let Some(done) = worker.poll()
&& shows(&app.canvas, &done, shown)
{
if !done.coarse {
app.canvas.render_work = Some(done.work);
app.ui.render_ms = done.ms;
}
// A pixel preview render is magnified with hard pixel edges.
let filter = if app.session.ds().ok().and_then(|d| d.view.pixel_preview_scale()) == Some(done.view.scale) {
egui::TextureOptions::NEAREST
} else {
egui::TextureOptions::LINEAR
};
match &mut app.canvas.texture {
Some(t) => t.set(done.image, filter),
None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", done.image, filter)),
}
let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0);
if done.coarse {
app.canvas.preview_latency_ms = latency;
} else {
app.canvas.refine_latency_ms = latency;
}
app.canvas.tex_view = Some(done.view);
app.canvas.tex_of = Some((done.uid, done.page));
app.canvas.tex_coarse = done.coarse;
app.canvas.tex_seq = done.seq;
if let Some(done) = worker.poll() {
accept_render(app, &ctx, done, shown);
}
if let Some(around) = worker.surround()
&& around.highlighter_generation.is_none()
&& shown == Some((around.uid, around.page))
{
let of = (around.uid, around.page);
@@ -364,7 +385,7 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
}
let painter = ui.painter_at(rect);
crate::theme::set_canvas_page(&ctx, bg);
let image = if let (Some(tex), Some(v), true) = (&app.canvas.texture, &app.canvas.tex_view, shown.is_some() && app.canvas.tex_of == shown) {
let image = if let Some((tex, v)) = app.canvas.shown_texture(shown) {
// Re-project the last render onto the current view.
let tl = app.to_screen(v.origin.0, v.origin.1);
let zoom = app.session.ds().map(|d| d.view.zoom).unwrap_or(1.0);
@@ -429,6 +450,49 @@ pub fn show(app: &mut FigApp, ui: &mut Ui, worker: &mut Worker) {
}
}
fn accept_render(app: &mut FigApp, ctx: &egui::Context, done: Done, shown: Option<(u64, NodeId)>) {
if !shows(&app.canvas, &done, shown) {
return;
}
if !done.coarse {
app.canvas.render_work = Some(done.work);
app.ui.render_ms = done.ms;
}
// A pixel preview render is magnified with hard pixel edges.
let filter = if app.session.ds().ok().and_then(|d| d.view.pixel_preview_scale()) == Some(done.view.scale) {
egui::TextureOptions::NEAREST
} else {
egui::TextureOptions::LINEAR
};
let latency = Some(done.at.elapsed().as_secs_f64() * 1000.0);
if done.coarse {
app.canvas.preview_latency_ms = latency;
} else {
app.canvas.refine_latency_ms = latency;
}
if let Some(generation) = done.highlighter_generation {
let texture = match app.canvas.highlighter.take() {
Some(p) if p.generation == generation => {
let mut texture = p.texture;
texture.set(done.image, filter);
texture
}
_ => ctx.load_texture("figcraft-highlighter-preview", done.image, filter),
};
app.canvas.highlighter =
Some(HighlighterTexture { texture, view: done.view, of: (done.uid, done.page), generation, coarse: done.coarse, seq: done.seq });
return;
}
match &mut app.canvas.texture {
Some(t) => t.set(done.image, filter),
None => app.canvas.texture = Some(ctx.load_texture("figcraft-canvas", done.image, filter)),
}
app.canvas.tex_view = Some(done.view);
app.canvas.tex_of = Some((done.uid, done.page));
app.canvas.tex_coarse = done.coarse;
app.canvas.tex_seq = done.seq;
}
/// The image's screen rect; align native-density renders to device pixels to avoid linear filtering
/// blending neighbouring texels. Stale and pixel-preview renders retain their original projection.
pub(super) fn presented_image_rect(tl: Pos2, view: &figcraft_render::View, zoom: f64, ppp: f32, pixel_preview: bool) -> Rect {
+16 -6
View File
@@ -490,12 +490,22 @@ fn pen_overlay(app: &FigApp, painter: &egui::Painter, zoom: f64) {
let ov = &app.session.tool.overlay;
if !ov.pen.is_empty() {
let pts: Vec<Pos2> = ov.pen.iter().map(|[x, y]| app.to_screen(*x, *y)).collect();
if app.session.tool.tool == ToolId::Pencil {
// The stroke it will make, in its colour and weight (at least a point when zoomed out):
// white over a dark page or frame, as the stroke will be (#1741).
let (default, weight) = figcraft_engine::tools::PENCIL_STROKE;
let color = ov.pen_color.unwrap_or(default);
painter.add(Shape::line(pts, stroke(doc_c32(painter.ctx(), color), ((weight * zoom) as f32).max(1.0))));
let ink = match app.session.tool.tool {
ToolId::Pencil => {
// The pencil's stroke can be white over a dark page or frame (#1741).
let (default, weight) = figcraft_engine::tools::PENCIL_STROKE;
Some((ov.pen_color.unwrap_or(default), weight))
}
ToolId::Marker => {
let (color, weight, opacity) = app.session.tool.board.ink_style(false);
Some((color.with_alpha(color.a * opacity), weight))
}
_ => None,
};
if let Some((color, weight)) = ink {
let width = (weight * zoom) as f32;
let width = if app.session.tool.tool == ToolId::Pencil { width.max(1.0) } else { width };
painter.add(Shape::line(pts, stroke(doc_c32(painter.ctx(), color), width)));
} else {
for [x0, y0, x1, y1] in &ov.pen_handles {
bezier_handle(painter, app.to_screen(*x0, *y0), app.to_screen(*x1, *y1), 3.5, Color32::WHITE);
+17 -9
View File
@@ -16,6 +16,7 @@ pub(super) struct JobKey {
fonts: u64,
proof: bool,
dots: Option<figcraft_render::Dots>,
pub(super) highlighter_generation: Option<u64>,
}
/// Whether a finished render goes on screen: an image of the file and page shown (`shown`), and
@@ -26,15 +27,20 @@ pub(crate) fn shows(c: &CanvasState, done: &Done, shown: Option<(u64, NodeId)>)
if shown != Some((done.uid, done.page)) {
return false;
}
let refined = !c.tex_coarse && c.tex_of == shown;
if done.coarse && refined && done.seq <= c.tex_seq {
let (refined, view, seq) = if let Some(generation) = done.highlighter_generation {
if c.requested_highlighter() != Some(generation) {
return false;
}
let current = c.shown_highlighter().filter(|p| Some(p.of) == shown);
(current.is_some_and(|p| !p.coarse), current.map(|p| &p.view), current.map_or(0, |p| p.seq))
} else {
(!c.tex_coarse && c.tex_of == shown, c.tex_view.as_ref(), c.tex_seq)
};
if done.coarse && refined && done.seq <= seq {
return false;
}
let refined_here = refined
&& c.tex_view
.as_ref()
.zip(c.want_view.as_ref())
.is_some_and(|(have, want)| have.scale.to_bits() == want.scale.to_bits() && covers(have, want));
let refined_here =
refined && view.zip(c.want_view.as_ref()).is_some_and(|(have, want)| have.scale.to_bits() == want.scale.to_bits() && covers(have, want));
!(done.coarse && refined_here)
}
@@ -59,8 +65,8 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma
} else {
(ds.view.zoom * f64::from(ppp), (rect.width() * ppp).ceil().max(1.0) as u32, (rect.height() * ppp).ceil().max(1.0) as u32)
};
// The edited text is drawn live (an IME composition included); the caret is an overlay.
let doc = app.preedit_view().map(|p| p.doc.clone()).unwrap_or_else(|| ds.doc.clone());
// Live text and highlighter previews must blend with the rest of the canvas.
let (doc, highlighter_generation) = app.canvas_document(ds);
let outlined = if ds.view.outlines_selection { ds.selection.clone() } else { vec![] };
let proof = ds.view.proof_srgb && !doc.color_profile.is_srgb();
let outline_extras = figcraft_render::Outline { hidden: ds.view.outline_hidden, bounds: ds.view.outline_bounds, light: false };
@@ -86,6 +92,7 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma
fonts: figcraft_text::layout_generation(),
proof,
dots,
highlighter_generation,
};
if let Some(previous) = &app.canvas.submitted {
let previous_origin = (previous.origin.0 as f64 / 1000.0, previous.origin.1 as f64 / 1000.0);
@@ -110,6 +117,7 @@ pub(super) fn request_render(app: &mut FigApp, worker: &mut Worker, ppp: f32, ma
proof,
dots,
uid: ds.uid,
highlighter_generation,
zoom_preview: ds.view.pixel_preview_scale().is_none(),
at: web_time::Instant::now(),
};
+6 -2
View File
@@ -70,6 +70,8 @@ pub struct Job {
pub dots: Option<figcraft_render::Dots>,
/// The document's [`figcraft_engine::DocState::uid`]: images of other files are never shown.
pub uid: u64,
/// A transient render belongs to this highlighter gesture, never to the page's stable image.
pub highlighter_generation: Option<u64>,
/// A coarse preview may come first when the zoom changes (not in pixel preview, whose pixels
/// are the point).
pub zoom_preview: bool,
@@ -87,6 +89,7 @@ pub struct Done {
/// What it is an image of ([`Job::uid`], [`Job::page`]).
pub uid: u64,
pub page: NodeId,
pub highlighter_generation: Option<u64>,
/// A coarse preview, refined by a later image unless a newer request replaced it.
pub coarse: bool,
/// [`Job::at`].
@@ -145,7 +148,7 @@ fn done(job: &Job, view: View, pix: &Pixmap, work: Work, ms: f64, coarse: bool)
if job.proof {
mark_outside_srgb(&mut image, pix, job.doc.color_profile);
}
Done { image, view, ms, work, uid: job.uid, page: job.page, coarse, at: job.at, seq: 0 }
Done { image, view, ms, work, uid: job.uid, page: job.page, highlighter_generation: job.highlighter_generation, coarse, at: job.at, seq: 0 }
}
/// The coarse image around the view is this many views wide and tall, centred on it.
@@ -257,6 +260,7 @@ struct Stepping {
fn same_settings(a: &Job, b: &Job) -> bool {
a.uid == b.uid
&& a.page == b.page
&& a.highlighter_generation == b.highlighter_generation
&& a.view.scale.to_bits() == b.view.scale.to_bits()
&& (a.view.width, a.view.height) == (b.view.width, b.view.height)
&& a.outline == b.outline
@@ -616,7 +620,7 @@ impl Worker {
{
break;
}
if refined_job {
if refined_job && job.highlighter_generation.is_none() {
// Asked before the send (and before this request counts as done), so `in_flight`
// holds until the surround thread is done with it. Without that thread (it failed
// to start) the page colour shows past the edge.
@@ -86,6 +86,7 @@ pub(super) fn job(doc: &Arc<Document>, page: NodeId, uid: u64, view: View) -> Jo
proof: false,
dots: None,
uid,
highlighter_generation: None,
zoom_preview: true,
at: Instant::now(),
}
@@ -376,6 +377,60 @@ fn drain(w: &mut Worker) -> Vec<(u64, bool)> {
got
}
#[test]
fn a_highlighter_render_delivered_after_escape_cannot_enter_the_page_cache() {
use figcraft_engine::tools::{PointerEvent, PointerKind};
let mut s = Session::new();
s.execute("file.newBoard", &json!({})).unwrap();
let mut app = crate::FigApp::new(s, Box::new(crate::NoServices));
app.canvas.rect = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(100.0, 64.0));
let ds = app.session.ds().unwrap();
let shown = Some((ds.uid, ds.page));
let ctx = egui::Context::default();
let mut worker = Worker::new(ctx.clone());
let queued = |w: &mut Worker| {
let start = std::time::Instant::now();
while w.in_flight() {
assert!(start.elapsed() < Duration::from_secs(10), "the render never finished");
std::thread::yield_now();
}
w.poll().expect("a finished render in the queue")
};
let submit = |app: &mut crate::FigApp, w: &mut Worker| super::request_render(app, w, 1.0, 256, None);
submit(&mut app, &mut worker);
let clean = queued(&mut worker);
let clean_seq = clean.seq;
super::accept_render(&mut app, &ctx, clean, shown);
let _ = worker.surround();
app.session.execute("tool.highlighter", &json!({})).unwrap();
app.session.pointer(&PointerEvent::at(PointerKind::Down, 10.0, 20.0, 1.0)).unwrap();
app.session.pointer(&PointerEvent::at(PointerKind::Move, 30.0, 20.0, 1.0)).unwrap();
submit(&mut app, &mut worker);
let active_preview = queued(&mut worker);
let generation = active_preview.highlighter_generation.expect("the stroke's generation");
super::accept_render(&mut app, &ctx, active_preview, shown);
assert_eq!(app.canvas.shown_highlighter().map(|p| p.generation), Some(generation));
assert_eq!(app.canvas.tex_seq, clean_seq, "the page's stable image stays separate during the stroke");
app.session.pointer(&PointerEvent::at(PointerKind::Move, 60.0, 20.0, 1.0)).unwrap();
submit(&mut app, &mut worker);
let late = queued(&mut worker);
assert_eq!(late.highlighter_generation, Some(generation));
assert!(worker.surround().is_none(), "a transient request does not enter the surround cache");
app.session.escape().unwrap();
submit(&mut app, &mut worker);
app.canvas.switch_texture(shown, |_| true);
super::accept_render(&mut app, &ctx, late, shown);
assert!(app.canvas.shown_highlighter().is_none(), "Escape also drops any preview already on screen");
assert_eq!(app.canvas.tex_seq, clean_seq, "the late preview must never replace the clean image");
let (uid, page) = shown.unwrap();
app.canvas.switch_texture(Some((uid, NodeId(page.0 + 1))), |_| true);
app.canvas.switch_texture(shown, |_| true);
assert_eq!(app.canvas.tex_seq, clean_seq, "the page cache must return the clean image");
}
#[test]
fn a_slow_first_render_gets_a_preview_beside_it_and_a_quick_one_none() {
// Slow: a render from scratch that runs past the threshold, then the preview, with as much
+1
View File
@@ -88,6 +88,7 @@ fn big_job(doc: &Arc<figcraft_doc::Document>, page: figcraft_doc::NodeId, scale:
proof: false,
dots: None,
uid: 0,
highlighter_generation: None,
zoom_preview: false,
at: web_time::Instant::now(),
}
+1
View File
@@ -238,6 +238,7 @@ fn a_finished_background_render_wakes_the_ui() {
proof: false,
dots: None,
uid: 0,
highlighter_generation: None,
zoom_preview: false,
at: web_time::Instant::now(),
});