diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 796a7d1dc3..a234e14868 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -68,6 +68,7 @@ mod single_instance; mod system_fonts; mod tablet; mod window_frame; +mod window_system; mod windows_alt_codes; #[cfg(windows)] mod windows_cores; @@ -91,7 +92,6 @@ use craft::ui::shell::embed; use craft::window::Prefix; use craft::window::policy::{TitleBarPref, decide_for}; use craft::window::restore::Store; -use craft::window::system::SystemWindows; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::file_access::{self, AutomationRoots}; @@ -117,20 +117,9 @@ const MIN_SIZE: [f32; 2] = [800.0, 500.0]; /// framework maximizes the window when its default size would not fit the current screen. fn restore_main_window(window: &winit::window::Window, store: &Store, legacy: Option, wayland: bool) { use craft::behavior::placement::{Defaults, Placement, place}; - use craft::behavior::{Monitor, MonitorKey}; use winit::dpi::{LogicalSize, PhysicalPosition}; - let handles: Vec<_> = window.available_monitors().collect(); - let monitors: Vec<_> = handles - .iter() - .map(|monitor| { - let size = monitor.size(); - let size = [size.width, size.height]; - let position = monitor.position(); - Monitor::new(MonitorKey::new(monitor.name().unwrap_or_default(), size), [position.x, position.y], size, monitor.scale_factor() as f32) - }) - .collect(); - let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor)); + let (monitors, home) = window_system::monitor_layout(window).unwrap_or_default(); let defaults = Defaults::new(DEFAULT_SIZE, MIN_SIZE).with_no_position(wayland); let saved = store.get(craft::window::restore::MAIN).or_else(|| { let old = legacy?; @@ -896,9 +885,11 @@ fn main() -> std::process::ExitCode { if let Some(window) = &winit_window { restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland); } - let spec = main_window_spec(shell_info, Arc::new(SystemWindows), host_services::open_link) - .placement(Arc::new(Mutex::new(placement))) - .frame(decision); + // A pen or a finger in contact counts as the primary button (`windows_stylus`). + let spec = + main_window_spec(shell_info, Arc::new(window_system::DesktopWindows::new(winit_window.as_ref())), host_services::open_link) + .placement(Arc::new(Mutex::new(placement))) + .frame(decision); let spec = match start_pen(&winit_window) { Some(pen) => spec.pen(pen), None => spec, diff --git a/apps/vectorcraft/src/window_system.rs b/apps/vectorcraft/src/window_system.rs new file mode 100644 index 0000000000..4c7975a561 --- /dev/null +++ b/apps/vectorcraft/src/window_system.rs @@ -0,0 +1,249 @@ +//! The desktop's monitors for window and popup placement: where each one is, its size and scale, and on Windows the +//! part the taskbar leaves free. + +use std::panic::AssertUnwindSafe; +use std::sync::{Arc, Mutex, PoisonError, Weak}; +use std::time::{Duration, Instant}; + +use craft::behavior::{Monitor, MonitorKey}; +use craft::window::system::{HeldButtons, WindowSystem}; +use winit::window::Window; + +use crate::windows_stylus::ContactWindows; + +/// How long one listing of the monitors is used. Placement asks for the monitors several times a frame; a display +/// that is added, removed or moved shows up in the first listing after this. +const RELIST_AFTER: Duration = Duration::from_secs(1); + +/// The monitors in physical desktop pixels, and the index of the one showing `window` (else the primary one). +/// `None` when winit stops on a display that went away while it was being listed (Windows). +pub(super) fn monitor_layout(window: &Window) -> Option<(Vec, Option)> { + let listing = std::panic::catch_unwind(AssertUnwindSafe(|| { + let handles: Vec<_> = window.available_monitors().collect(); + let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor)); + let monitors = handles + .iter() + .map(|handle| { + let size = handle.size(); + let size = [size.width, size.height]; + let position = handle.position(); + let monitor = Monitor::new( + MonitorKey::new(handle.name().unwrap_or_default(), size), + [position.x, position.y], + size, + handle.scale_factor() as f32, + ); + match work_px(&monitor) { + Some((pos, size)) => monitor.with_work_px(pos, size), + None => monitor, + } + }) + .collect(); + (monitors, home) + })); + listing.map_err(|_| log::debug!("a display went away while the monitors were listed")).ok() +} + +/// The work area of the monitor whose top-left pixel is `monitor`'s, from `GetMonitorInfo`. winsafe comes with the +/// wgpu renderer, which every desktop package builds with. +#[cfg(all(windows, feature = "wgpu"))] +fn work_px(monitor: &Monitor) -> Option<([i32; 2], [u32; 2])> { + use winsafe::{HMONITOR, POINT, co}; + let [x, y] = monitor.pos_px; + let info = HMONITOR::MonitorFromPoint(POINT { x, y }, co::MONITOR::DEFAULTTONULL).GetMonitorInfo().ok()?; + let work = info.rcWork; + from_edges(work.left, work.top, work.right, work.bottom) +} + +/// Other platforms report no work area. +#[cfg(not(all(windows, feature = "wgpu")))] +fn work_px(_: &Monitor) -> Option<([i32; 2], [u32; 2])> { + None +} + +/// The top-left corner and size of the pixel rectangle with these edges; `None` for an empty or inverted one. +#[cfg(any(all(windows, feature = "wgpu"), test))] +fn from_edges(left: i32, top: i32, right: i32, bottom: i32) -> Option<([i32; 2], [u32; 2])> { + let width = u32::try_from(right.checked_sub(left)?).ok().filter(|w| *w > 0)?; + let height = u32::try_from(bottom.checked_sub(top)?).ok().filter(|h| *h > 0)?; + Some(([left, top], [width, height])) +} + +/// The platform's window services with a pen or a finger in contact counted as the primary button +/// ([`ContactWindows`]), and the monitors listed through winit. On macOS no monitors are listed: winit +/// gives each display's position in that display's own scale, so the pixel areas of displays with different scales +/// overlap and placement could pick the wrong one. Elsewhere monitors with different scales are not listed either +/// ([`one_scale`]). +pub(super) struct DesktopWindows { + list: Box Option> + Send + Sync>, + now: Box Instant + Send + Sync>, + /// The last listing that succeeded, and when it was made. + listed: Mutex)>>, +} + +impl DesktopWindows { + /// Lists the monitors of `window`'s desktop; none without a window, and none on macOS. + pub(super) fn new(window: Option<&Arc>) -> Self { + let window = if cfg!(target_os = "macos") { Weak::new() } else { window.map_or_else(Weak::new, Arc::downgrade) }; + Self::with(move || window.upgrade().and_then(|window| monitor_layout(&window)).map(|(monitors, _)| monitors), Instant::now) + } + + /// Lists the monitors with `list` (`None` when a listing fails), timed by `now`. + fn with(list: impl Fn() -> Option> + Send + Sync + 'static, now: impl Fn() -> Instant + Send + Sync + 'static) -> Self { + Self { list: Box::new(list), now: Box::new(now), listed: Mutex::default() } + } +} + +impl WindowSystem for DesktopWindows { + fn desktop_pointer(&self) -> Option<[f32; 2]> { + ContactWindows.desktop_pointer() + } + + fn buttons_held(&self) -> Option { + ContactWindows.buttons_held() + } + + fn discard_marked_text(&self) -> bool { + ContactWindows.discard_marked_text() + } + + fn command_held(&self) -> Option { + ContactWindows.command_held() + } + + fn warp_pointer(&self, to: [f32; 2]) -> bool { + ContactWindows.warp_pointer(to) + } + + /// The monitors of the last listing, listed again once [`RELIST_AFTER`] has passed. A listing that fails keeps + /// the last one, and the next call lists again. + fn monitors(&self) -> Vec { + let now = (self.now)(); + let mut listed = self.listed.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((at, monitors)) = listed.as_ref() + && now.saturating_duration_since(*at) < RELIST_AFTER + { + return monitors.clone(); + } + match (self.list)().map(one_scale) { + Some(monitors) => { + *listed = Some((now, monitors.clone())); + monitors + } + None => listed.as_ref().map(|(_, monitors)| monitors.clone()).unwrap_or_default(), + } + } +} + +/// `monitors` when they all have one scale, else none. The framework finds the monitor a palette window is on by +/// testing the window's corner, in the window's own points, at each monitor's scale, so with mixed scales a palette +/// on one monitor can be matched to another and its popups kept in that monitor's work area. Without a listing, +/// popups stay within the span of the app's windows and dialogs reopen where they were saved. +fn one_scale(monitors: Vec) -> Vec { + let mixed = monitors.windows(2).any(|pair| pair[0].scale != pair[1].scale); + if mixed { Vec::new() } else { monitors } +} + +#[cfg(test)] +mod tests { + use super::*; + use craft::behavior::placement::{Defaults, Placement, place}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + fn monitor(name: &str, pos: [i32; 2], size: [u32; 2], scale: f32) -> Monitor { + Monitor::new(MonitorKey::new(name, size), pos, size, scale) + } + + /// A clock the test moves. + fn clock() -> (Arc>, impl Fn() -> Instant + Send + Sync + 'static) { + let time = Arc::new(Mutex::new(Instant::now())); + let read = Arc::clone(&time); + (time, move || *read.lock().unwrap()) + } + + fn advance(time: &Mutex, by: Duration) { + let mut now = time.lock().unwrap(); + *now += by; + } + + /// The monitors come from the desktop listing, which runs once per [`RELIST_AFTER`] however often placement asks, + /// and a display that changed shows up in the next listing. + #[test] + fn monitors_are_listed_once_a_second_and_follow_display_changes() { + let listings = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&listings); + let (time, now) = clock(); + let system = DesktopWindows::with( + move || { + let n = count.fetch_add(1, Ordering::SeqCst); + let mut monitors = vec![monitor("A", [0, 0], [1920, 1080], 1.0)]; + if n > 0 { + monitors.push(monitor("B", [1920, 0], [2560, 1440], 1.0)); + } + Some(monitors) + }, + now, + ); + let names = |monitors: Vec| monitors.into_iter().map(|m| m.key.name).collect::>(); + assert_eq!(names(system.monitors()), ["A"]); + assert_eq!(names(system.monitors()), ["A"]); + advance(&time, RELIST_AFTER - Duration::from_millis(1)); + assert_eq!(names(system.monitors()), ["A"]); + assert_eq!(listings.load(Ordering::SeqCst), 1, "calls within the reuse time share one listing"); + advance(&time, Duration::from_millis(1)); + assert_eq!(names(system.monitors()), ["A", "B"], "the added display shows up in the next listing"); + assert_eq!(listings.load(Ordering::SeqCst), 2); + } + + /// A listing that fails (a display went away while it was listed) keeps the last monitors, and the next call + /// lists again instead of waiting for the reuse time. + #[test] + fn a_failed_listing_keeps_the_last_monitors() { + let listings = Arc::new(AtomicUsize::new(0)); + let count = Arc::clone(&listings); + let (time, now) = clock(); + let system = + DesktopWindows::with(move || (count.fetch_add(1, Ordering::SeqCst) == 0).then(|| vec![monitor("A", [0, 0], [1920, 1080], 1.0)]), now); + assert_eq!(system.monitors().len(), 1); + advance(&time, RELIST_AFTER); + assert_eq!(system.monitors().len(), 1, "the failed listing keeps the last one"); + assert_eq!(system.monitors().len(), 1); + assert_eq!(listings.load(Ordering::SeqCst), 3, "each call after a failed listing lists again"); + } + + /// A dialog saved on a monitor that is no longer connected (or at a place no monitor shows) reopens with its whole + /// frame inside a connected monitor's work area, clear of the taskbar. + #[test] + fn a_dialog_saved_off_every_monitor_opens_inside_a_work_area() { + let (_, now) = clock(); + let system = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [1920, 1080], 1.0).with_work_px([0, 0], [1920, 1040])]), now); + let mut saved = Placement::new([600.0, 400.0], 1.0); + saved.position_px = Some([3000, 900]); + let placed = place(Some(&saved), &system.monitors(), None, &Defaults::new([600.0, 400.0], [200.0, 100.0])); + let [x, y] = placed.position_px.expect("the dialog keeps a position"); + let [width, height] = placed.normal.size; + let frame = egui::Rect::from_min_size(egui::pos2(x as f32, y as f32), egui::vec2(width, height)); + let work = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1920.0, 1040.0)); + assert!(work.contains_rect(frame), "{frame:?} is inside {work:?}"); + } + + /// Monitors with different scales are not listed, so a palette's popups on a scale-2 monitor beside a scale-1 one + /// are not kept in the other monitor's work area; monitors that share a scale are listed. + #[test] + fn monitors_with_mixed_scales_are_not_listed() { + let (_, now) = clock(); + let mixed = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [1920, 1080], 1.0), monitor("B", [1920, 0], [3840, 2160], 2.0)]), now); + assert!(mixed.monitors().is_empty(), "mixed scales list no monitors"); + let (_, now) = clock(); + let shared = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [3840, 2160], 1.5), monitor("B", [3840, 0], [3840, 2160], 1.5)]), now); + assert_eq!(shared.monitors().len(), 2, "one scale lists every monitor"); + } + + #[test] + fn work_area_edges_give_corner_and_size() { + assert_eq!(from_edges(-1920, -200, 0, 840), Some(([-1920, -200], [1920, 1040]))); + assert_eq!(from_edges(0, 0, 0, 1040), None, "no width"); + assert_eq!(from_edges(100, 0, 0, 1040), None, "inverted"); + assert_eq!(from_edges(i32::MIN, 0, i32::MAX, 10), None, "overflowing width"); + } +} diff --git a/apps/vectorcraft/src/windows_stylus.rs b/apps/vectorcraft/src/windows_stylus.rs index 4213398df4..155441ae7d 100644 --- a/apps/vectorcraft/src/windows_stylus.rs +++ b/apps/vectorcraft/src/windows_stylus.rs @@ -28,13 +28,20 @@ //! converted to radians. `POINTER_PEN_INFO` has no field for an airbrush pen's finger wheel, which //! comes from the tablet driver's Wintab interface instead, when it has one //! ([`crate::windows_wintab`]). +//! +//! The window host reads the mouse buttons Windows reports down ([`ContactWindows`]) to release a +//! press whose release the window never received. A pen or a finger in contact is not a mouse +//! button there, so [`msg_hook`] also notes each pointer in contact, and [`ContactWindows`] reports +//! the primary button down while one is. Otherwise the press of a pen stroke is released on its +//! first move. #![cfg_attr(not(windows), allow(dead_code))] use std::cell::Cell; -use std::sync::OnceLock; +use std::sync::{Mutex, OnceLock, PoisonError}; -use craft::behavior::PointerSample; +use craft::behavior::{Monitor, PointerSample}; use craft::ui::runtime::pen::PenSource; +use craft::window::system::{HeldButtons, SystemWindows, WindowSystem}; /// `POINTER_MESSAGE_FLAG_SECONDBUTTON` (`winuser.h`): in the high word of a pointer message's /// `wParam`, a pen in contact with its barrel button pressed. @@ -44,6 +51,8 @@ const POINTER_MESSAGE_FLAG_SECONDBUTTON: usize = 0x0020; const POINTER_MESSAGE_FLAG_INRANGE: usize = 0x0002; /// `POINTER_MESSAGE_FLAG_CANCELED` (`winuser.h`): the pointer's input was canceled. const POINTER_MESSAGE_FLAG_CANCELED: usize = 0x8000; +/// `POINTER_MESSAGE_FLAG_INCONTACT` (`winuser.h`): a pen or a finger touching the surface. +const POINTER_MESSAGE_FLAG_INCONTACT: usize = 0x0004; /// `PEN_FLAG_INVERTED` and `PEN_FLAG_ERASER` (`winuser.h`), in `POINTER_PEN_INFO::penFlags`. const PEN_FLAG_INVERTED: u32 = 0x0002; const PEN_FLAG_ERASER: u32 = 0x0004; @@ -67,6 +76,8 @@ const WM_POINTERDOWN: u32 = 0x0246; const WM_POINTERUP: u32 = 0x0247; const WM_POINTERENTER: u32 = 0x0249; const WM_POINTERLEAVE: u32 = 0x024A; +/// `WM_POINTERCAPTURECHANGED` (`winuser.h`): another window took the pointer's capture. +const WM_POINTERCAPTURECHANGED: u32 = 0x024C; /// A pen's tilt along x and y and its barrel rotation, in radians. type Pose = ([f32; 2], f32); @@ -81,6 +92,84 @@ thread_local! { /// The pen source [`msg_hook`] writes, once [`start`] has made it. static FEED: OnceLock = OnceLock::new(); +/// The ids of the pointers in contact (pens and fingers), from [`msg_hook`]. +static CONTACTS: Mutex> = Mutex::new(Vec::new()); + +/// The running platform's window services ([`SystemWindows`]), with the primary button reported +/// down while a pen or a finger is in contact. +pub struct ContactWindows; + +impl WindowSystem for ContactWindows { + fn desktop_pointer(&self) -> Option<[f32; 2]> { + SystemWindows.desktop_pointer() + } + + fn buttons_held(&self) -> Option { + let in_contact = !CONTACTS.lock().unwrap_or_else(PoisonError::into_inner).is_empty(); + with_contact(SystemWindows.buttons_held(), in_contact) + } + + fn discard_marked_text(&self) -> bool { + SystemWindows.discard_marked_text() + } + + fn command_held(&self) -> Option { + SystemWindows.command_held() + } + + fn warp_pointer(&self, to: [f32; 2]) -> bool { + SystemWindows.warp_pointer(to) + } + + fn monitors(&self) -> Vec { + SystemWindows.monitors() + } +} + +/// The buttons `held` with the primary one added while a pointer is `in_contact`; `None` where the +/// platform tells nothing. +fn with_contact(held: Option, in_contact: bool) -> Option { + held.map(|mut held| { + if in_contact { + held.insert(HeldButtons::PRIMARY); + } + held + }) +} + +/// The pointer a message with this `wParam` is about, and whether it is now in contact: a pointer +/// that goes down or moves with `POINTER_MESSAGE_FLAG_INCONTACT` and no cancel is; one that hovers, +/// is canceled, goes up, leaves or loses its capture to another window is not. `None` for any other +/// message. +fn contact_update(message: u32, wparam: usize) -> Option<(u32, bool)> { + let id = (wparam & 0xffff) as u32; + let flags = wparam >> 16; + match message { + WM_POINTERDOWN | WM_POINTERUPDATE => Some((id, flags & POINTER_MESSAGE_FLAG_INCONTACT != 0 && flags & POINTER_MESSAGE_FLAG_CANCELED == 0)), + WM_POINTERUP | WM_POINTERLEAVE | WM_POINTERCAPTURECHANGED => Some((id, false)), + _ => None, + } +} + +/// Notes in `contacts` the pointer that a message with this `wParam` puts in or out of contact +/// ([`contact_update`]). A mouse message that a mouse made (`from_mouse`) ends every contact, so a +/// contact whose end went to another window does not hold the primary button for the mouse. +/// A pointer goes into contact only when `watched` returns true: the thread's hook that sees its +/// sent leave and capture change is installed. Otherwise a later message of the contact tries +/// again. Returns whether the message put a pointer in contact. +fn follow_contact(contacts: &mut Vec, message: u32, wparam: usize, from_mouse: impl FnOnce() -> bool, watched: impl FnOnce() -> bool) -> bool { + match contact_update(message, wparam) { + Some((id, true)) if !contacts.contains(&id) && watched() => { + contacts.push(id); + return true; + } + Some((id, false)) => contacts.retain(|c| *c != id), + None if MOUSE_MESSAGES.contains(&message) && !contacts.is_empty() && from_mouse() => contacts.clear(), + _ => {} + } + false +} + /// The canvas's pen source, which [`msg_hook`] writes before winit handles each message. pub fn start() -> PenSource { FEED.get_or_init(PenSource::default).clone() @@ -99,6 +188,12 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { let Some(msg) = (unsafe { msg.cast::().as_ref() }) else { return false; }; + // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. + let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); + // The contact's sent leave and capture change come through the thread's hook, so a contact is + // noted only once the hook is installed. + let watched = || crate::windows_wintab::hook_sent_messages(msg.time); + follow_contact(&mut CONTACTS.lock().unwrap_or_else(PoisonError::into_inner), msg.message, msg.wParam.0, from_mouse, watched); let Some(pen) = FEED.get() else { return false; }; @@ -119,8 +214,6 @@ pub fn msg_hook(msg: *const std::ffi::c_void) -> bool { let pose = pen_pose(info.penMask, info.tiltX, info.tiltY, info.rotation); Some(pen_sample(info.pressure, info.penMask, info.penFlags, in_contact, pose, wheel)) }; - // SAFETY: `GetMessageExtraInfo` reads the extra information of the thread's last message. - let from_mouse = || is_mouse(unsafe { GetMessageExtraInfo() }.0 as u32); if let Some(sample) = feed_update(msg.message, msg.wParam.0, read_pen, from_mouse) { // The barrel goes first: the contact's press reads it with the sample. pen.set_barrel(sample.is_some() && (msg.wParam.0 >> 16) & POINTER_MESSAGE_FLAG_SECONDBUTTON != 0); @@ -188,9 +281,13 @@ fn sent_forgets_wheel(message: u32, wparam: usize, pen: Option) -> bool { /// A message Windows sent to a window procedure of the thread, from the Wintab reader's hook on /// them ([`crate::windows_wintab`]): a pen leaving the window starts the wheel readings afresh, as -/// [`msg_hook`] does for the messages it sees. +/// [`msg_hook`] does for the messages it sees, and a pointer that leaves it or loses its capture is +/// no longer in contact. #[cfg(windows)] pub fn sent_message(message: u32, wparam: usize) { + if matches!(message, WM_POINTERLEAVE | WM_POINTERCAPTURECHANGED) { + follow_contact(&mut CONTACTS.lock().unwrap_or_else(PoisonError::into_inner), message, wparam, || false, || true); + } if sent_forgets_wheel(message, wparam, WHEEL_PEN.get()) { crate::windows_wintab::forget(); } @@ -334,6 +431,71 @@ mod tests { assert_eq!(pen_sample(2000, PEN_MASK_PRESSURE, 0, false, UPRIGHT, None).pressure, 0.0); } + #[test] + fn a_pointer_in_contact_holds_the_primary_button() { + assert_eq!(with_contact(Some(HeldButtons::NONE), true), Some(HeldButtons::PRIMARY), "a pen stroke while no mouse button is down"); + assert_eq!(with_contact(Some(HeldButtons::NONE), false), Some(HeldButtons::NONE)); + let held = with_contact(Some(HeldButtons::SECONDARY), true).unwrap_or_default(); + assert!(held.contains(HeldButtons::PRIMARY) && held.contains(HeldButtons::SECONDARY), "the mouse's own buttons stay"); + assert_eq!(with_contact(None, true), None, "a platform that tells nothing still tells nothing"); + } + + #[test] + fn a_pen_stroke_is_in_contact_from_its_down_to_its_up() { + let flags = |f: usize| (f << 16) | 7; + let touching = flags(POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_INCONTACT); + let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") }; + let follow = |contacts: &mut Vec, message: u32, wparam: usize| follow_contact(contacts, message, wparam, no_mouse, || true); + let mut contacts = vec![]; + follow(&mut contacts, WM_POINTERUPDATE, flags(POINTER_MESSAGE_FLAG_INRANGE)); + assert!(contacts.is_empty(), "a hovering pen is in no contact"); + assert!(follow(&mut contacts, WM_POINTERDOWN, touching), "the pen goes into contact"); + assert_eq!(contacts, [7], "the pen touches down"); + assert!(!follow(&mut contacts, WM_POINTERUPDATE, touching), "it is already in contact"); + assert_eq!(contacts, [7], "and stays in contact while it moves"); + follow(&mut contacts, WM_POINTERDOWN, (POINTER_MESSAGE_FLAG_INCONTACT << 16) | 9); + follow(&mut contacts, WM_POINTERUP, flags(POINTER_MESSAGE_FLAG_INRANGE)); + assert_eq!(contacts, [9], "the pen goes up and a finger stays down"); + follow(&mut contacts, WM_POINTERUPDATE, ((POINTER_MESSAGE_FLAG_INCONTACT | POINTER_MESSAGE_FLAG_CANCELED) << 16) | 9); + assert!(contacts.is_empty(), "a canceled contact ends"); + follow(&mut contacts, WM_POINTERDOWN, touching); + follow(&mut contacts, WM_POINTERLEAVE, 7); + assert!(contacts.is_empty(), "a pointer that leaves the window ends its contact"); + follow(&mut contacts, WM_POINTERDOWN, touching); + follow(&mut contacts, WM_POINTERCAPTURECHANGED, 7); + assert!(contacts.is_empty(), "a pointer whose capture another window took ends its contact"); + + // WM_LBUTTONDOWN. + follow(&mut contacts, WM_POINTERDOWN, touching); + follow_contact(&mut contacts, 0x0201, 0, || false, || true); + assert_eq!(contacts, [7], "a mouse message Windows made from the pen keeps the contact"); + follow_contact(&mut contacts, 0x0201, 0, || true, || true); + assert!(contacts.is_empty(), "a press of the mouse ends a contact whose end never arrived"); + // WM_KEYDOWN. + follow(&mut contacts, WM_POINTERDOWN, touching); + follow_contact(&mut contacts, 0x0100, 0, || -> bool { panic!("not a mouse message") }, || true); + assert_eq!(contacts, [7]); + } + + #[test] + fn a_contact_is_noted_only_while_its_end_can_arrive() { + let touching = ((POINTER_MESSAGE_FLAG_INRANGE | POINTER_MESSAGE_FLAG_INCONTACT) << 16) | 7; + let no_mouse = || -> bool { panic!("a pointer message is not a mouse message") }; + let mut contacts = vec![]; + assert!(!follow_contact(&mut contacts, WM_POINTERDOWN, touching, no_mouse, || false), "the hook did not install"); + assert!(contacts.is_empty(), "a contact whose leave could not arrive is not noted"); + assert!(follow_contact(&mut contacts, WM_POINTERUPDATE, touching, no_mouse, || true), "the next move tries again"); + assert_eq!(contacts, [7]); + let asked = std::cell::Cell::new(false); + follow_contact(&mut contacts, WM_POINTERUPDATE, touching, no_mouse, || { + asked.set(true); + true + }); + assert!(!asked.get(), "a pointer already in contact does not install the hook again"); + follow_contact(&mut contacts, WM_POINTERUP, 7, no_mouse, || -> bool { panic!("an up is not a contact") }); + assert!(contacts.is_empty()); + } + #[test] fn mouse_messages_from_a_pen_or_a_touch_are_told_apart() { assert!(is_mouse(0), "a mouse"); diff --git a/apps/vectorcraft/src/windows_wintab.rs b/apps/vectorcraft/src/windows_wintab.rs index 31da32a1ff..50ccff2af8 100644 --- a/apps/vectorcraft/src/windows_wintab.rs +++ b/apps/vectorcraft/src/windows_wintab.rs @@ -625,7 +625,7 @@ fn message(message: u32, wparam: usize, lparam: isize) -> Message { } #[cfg(windows)] -pub use win::{forget, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; +pub use win::{forget, hook_sent_messages, msg_hook, pen_wheel, set_wheel_used, wheel_pen}; #[cfg(windows)] #[allow(unsafe_code)] @@ -758,8 +758,9 @@ mod win { /// The thread's hook on the messages Windows sends to its windows' procedures, which winit's /// message hook does not see: another app becoming the active one (`WM_ACTIVATEAPP`, sent to a /// top-level window of the app, ) - /// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE` - /// () go to + /// closes the context ([`deactivate`]), and a pointer's `WM_POINTERENTER`, `WM_POINTERLEAVE` + /// () and + /// `WM_POINTERCAPTURECHANGED` go to /// [`crate::windows_stylus::sent_message`]. The hook sees them whichever of the app's windows /// they are sent to (). unsafe extern "system" fn call_wnd_proc(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { @@ -1089,6 +1090,13 @@ mod win { settle(); } + /// Installs [`call_wnd_proc`] for a pointer that went into contact at the message time `time`, + /// so the pointer's sent `WM_POINTERLEAVE` and `WM_POINTERCAPTURECHANGED` reach + /// [`crate::windows_stylus::sent_message`] whether or not a context opens ([`hook_thread`]). + pub fn hook_sent_messages(time: u32) -> bool { + hook_thread(time) + } + /// The pen whose leaving starts the readings afresh, for a message of the pen with the pointer /// id `pen` ([`Readings::owner_or`]). pub fn wheel_pen(pen: u32) -> u32 { diff --git a/crates/engine/src/plugin_events.rs b/crates/engine/src/plugin_events.rs index 4a85763667..eda96e8c5d 100644 --- a/crates/engine/src/plugin_events.rs +++ b/crates/engine/src/plugin_events.rs @@ -68,6 +68,53 @@ type Recipient = (String, String, u64); #[cfg(test)] std::thread_local! { pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// How many [`EventPluginsHeld`] this thread holds. + static EVENT_PLUGINS_HELD: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// The thread whose test has events plug-ins installed in the process-wide registry, if any. +#[cfg(test)] +static EVENT_PLUGINS_OWNER: std::sync::Mutex> = std::sync::Mutex::new(None); +#[cfg(test)] +static EVENT_PLUGINS_FREED: std::sync::Condvar = std::sync::Condvar::new(); + +/// Held by a test that installs events plug-ins in the process-wide registry. Every such plug-in +/// reacts to every session's changes and spends handlers of every session's frame budget +/// ([`MAX_FRAME_HANDLERS`]), so when tests run as threads of one process, another test's plug-ins +/// would take the handlers a test counts on. A thread waits while another thread holds one; the +/// guards one thread holds count as one, until the last of them is dropped. +#[cfg(test)] +pub(crate) struct EventPluginsHeld { + /// Dropped on the thread that made it. + _thread: std::marker::PhantomData<*const ()>, +} + +#[cfg(test)] +pub(crate) fn hold_event_plugins() -> EventPluginsHeld { + if EVENT_PLUGINS_HELD.with(std::cell::Cell::get) == 0 { + let me = std::thread::current().id(); + let mut owner = EVENT_PLUGINS_OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + while owner.is_some_and(|t| t != me) { + owner = EVENT_PLUGINS_FREED.wait(owner).unwrap_or_else(std::sync::PoisonError::into_inner); + } + *owner = Some(me); + } + EVENT_PLUGINS_HELD.with(|n| n.set(n.get() + 1)); + EventPluginsHeld { _thread: std::marker::PhantomData } +} + +#[cfg(test)] +impl Drop for EventPluginsHeld { + fn drop(&mut self) { + let last = EVENT_PLUGINS_HELD.with(|n| { + n.set(n.get() - 1); + n.get() == 0 + }); + if last { + *EVENT_PLUGINS_OWNER.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None; + EVENT_PLUGINS_FREED.notify_all(); + } + } } /// The recipient `p` is. @@ -836,6 +883,7 @@ mod tests { use serde_json::json; use vectorcraft_plugins::wat as tpl; let id = "test.events.nested"; + let _held = hold_event_plugins(); let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.allow_plugin_grants_from_requests(); diff --git a/crates/engine/src/tests/plugin_events.rs b/crates/engine/src/tests/plugin_events.rs index f7ac63e770..0b0a4ba4ee 100644 --- a/crates/engine/src/tests/plugin_events.rs +++ b/crates/engine/src/tests/plugin_events.rs @@ -12,12 +12,33 @@ fn run(s: &mut Session, cmd: &str, p: Value) -> Value { s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) } -/// A session with a 400 × 200 document that takes `grant` from requests. -fn session() -> Session { +/// A session that holds [`crate::plugin_events::hold_event_plugins`] while it lives. +struct Held { + s: Session, + _held: crate::plugin_events::EventPluginsHeld, +} + +impl std::ops::Deref for Held { + type Target = Session; + fn deref(&self) -> &Session { + &self.s + } +} + +impl std::ops::DerefMut for Held { + fn deref_mut(&mut self) -> &mut Session { + &mut self.s + } +} + +/// A session with a 400 × 200 document that takes `grant` from requests. The plug-ins its test +/// installs are the only events plug-ins installed while it lives. +fn session() -> Held { + let held = crate::plugin_events::hold_event_plugins(); let mut s = Session::new(); s.execute("file.new", &json!({"width": 400, "height": 200})).unwrap(); s.allow_plugin_grants_from_requests(); - s + Held { s, _held: held } } fn rect(s: &mut Session, x: f64) -> NodeId { diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 8fc2876981..da4411eb94 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -802,7 +802,7 @@ fn a_placed_items_file_binds_the_exact_id_of_the_image_placed() { /// it became is named by a fresh wrapper. #[test] fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() { - let base = folder("stale-relative"); + let base = folder("stale-relative-move"); let a = base.join("main/a.png"); std::fs::write(&a, gray_png(4, 4)).unwrap(); let mut s = session(); diff --git a/crates/render/src/brush_fx.rs b/crates/render/src/brush_fx.rs index 1660ae6caa..96db25a357 100644 --- a/crates/render/src/brush_fx.rs +++ b/crates/render/src/brush_fx.rs @@ -61,6 +61,8 @@ pub(crate) struct BrushCache { /// (frame stamp, document address) the library was last validated for. checked: (u64, usize), lib: HashMap>, + /// Whether brush art or an opacity mask there has a visible plug-in effect. + plugins: bool, /// The names and art of the document's patterns and symbols ([`definitions`]) when the library /// was last validated, the art held weakly as the pattern tiles hold theirs. definitions: Vec<(String, Weak)>, @@ -78,6 +80,7 @@ impl Default for BrushCache { key: 0, checked: (0, 0), lib: HashMap::new(), + plugins: false, definitions: Vec::new(), entries: FrameCache::new(lru::BRUSH_BUDGET, 512), #[cfg(test)] @@ -113,6 +116,7 @@ impl BrushCache { for b in vectorcraft_brush::library(doc) { self.lib.entry(b.name.clone()).or_insert_with(|| Arc::new(b)); } + self.plugins = self.lib.values().any(|b| b.art().into_iter().any(crate::holds_plugin_effect)); } /// [`Self::key`] for the brush library `doc` holds (checked once a frame, `stamp`). @@ -121,6 +125,11 @@ impl BrushCache { self.key } + /// Whether brush art has a visible plug-in effect, valid after [`Self::library_key`] for the frame. + pub(crate) fn has_plugins(&self) -> bool { + self.plugins + } + /// [`Self::library_key`] checked now, between frames: `doc` may be the document of the last /// frame, edited in place. pub(crate) fn library_key_now(&mut self, doc: &Document, stamp: u64) -> u64 { diff --git a/crates/render/src/frame.rs b/crates/render/src/frame.rs index 49e252d206..0c58cdf1b4 100644 --- a/crates/render/src/frame.rs +++ b/crates/render/src/frame.rs @@ -1,3 +1,5 @@ +use std::hash::{DefaultHasher, Hash, Hasher}; + use super::options::{AntiAlias, RenderOptions}; use super::threads::single_threaded_context; use super::{ @@ -224,6 +226,8 @@ pub(crate) struct Frame<'a> { /// Size of one of this frame's pixels in document units. pub(crate) px: f64, pub(crate) opts: &'a RenderOptions, + /// The order-independent fingerprint of `opts.hidden`, shared by this frame's raster lookups. + pub(crate) hidden_inputs: u64, /// What colours paint as: screen colours, or one ink plane of a CMYK document (see [`ink`]). pub(crate) ink: Ink, /// Document → pixels of the output being drawn: `view` itself, except while an export draws @@ -236,6 +240,15 @@ pub(crate) struct Frame<'a> { } impl Frame<'_> { + /// Hash the hidden objects once for the options a frame draws with. + pub(crate) fn hidden_inputs(opts: &RenderOptions) -> u64 { + let mut hidden: Vec<_> = opts.hidden.iter().collect(); + hidden.sort_unstable(); + let mut h = DefaultHasher::new(); + hidden.hash(&mut h); + h.finish() + } + pub(crate) fn reject_patch(&self) -> bool { self.patch.is_some_and(|hit| { hit.set(true); diff --git a/crates/render/src/fx/entries.rs b/crates/render/src/fx/entries.rs index 64c1cf5ad9..d28412ab8c 100644 --- a/crates/render/src/fx/entries.rs +++ b/crates/render/src/fx/entries.rs @@ -221,19 +221,25 @@ pub(crate) struct Reads { /// Pattern paints: the pattern definitions. Their art can hold anything, so content painted /// with a pattern reads everything else too. pub(super) patterns: bool, - /// Symbol instances and type with inline graphics: the symbols' art. Symbol art can hold - /// anything, so content that shows a symbol reads everything else too. + /// Symbol instances, type with inline graphics, pattern art and brush art: the symbols' art. + /// Symbol art can hold anything, so content that shows a symbol reads everything else too. pub(super) symbols: bool, - /// Images and placed documents: their pixels and files, and the options and the layer's Dim - /// Images they are drawn with. + /// Images, placed documents, symbol art, pattern art and brush art: their pixels and files, + /// and the options and the layer's Dim Images they are drawn with. pub(super) images: bool, - /// Brushed strokes: the brush library. + /// Placed documents, symbol art and brushed strokes: the global bitmap generation while + /// progressive previews are on. Symbol and brush art can hold placed documents. Pattern tiles + /// draw with progressive previews off. + pub(super) placed_documents: bool, + /// Brushed strokes, symbol art and pattern art: the brush library. Brush art can hold + /// anything, so content that uses a brushed stroke reads everything else too. pub(super) brushes: bool, /// Type: the fonts, whether overprinting shows ([`crate::proof::overprints`]) and the /// substitution highlights. pub(super) text: bool, /// Plug-in effects on its objects: the plug-ins installed. Those in the symbol and pattern art - /// it shows are found with the document's inputs ([`DocInputs`]). + /// it shows are found with the document's inputs ([`DocInputs`]). Those in brush art are found + /// with the brush library ([`crate::brush_fx::BrushCache`]). pub(super) plugins: bool, } @@ -243,13 +249,24 @@ impl Reads { Self::of_all(std::iter::once(n)) } - /// What the content of `nodes` reads together. A pattern's art can hold anything, as a - /// symbol's can, so content painted with a pattern reads everything else too (#1723). + /// What the content of `nodes` reads together. Pattern, symbol and brush art can hold anything, + /// so content showing any of them reads the other document resources too (#1723). Progressive bitmap + /// readiness follows content that holds placed documents, shows symbol art or uses brushed + /// strokes. Pattern tiles draw with progressive previews off. pub(crate) fn of_all<'a>(nodes: impl Iterator) -> Self { let mut reads = Self::default(); nodes.for_each(|n| reads.add(n)); - if reads.symbols || reads.patterns { - return Self { patterns: true, symbols: true, images: true, brushes: true, text: true, plugins: reads.plugins }; + reads.placed_documents |= reads.symbols || reads.brushes; + if reads.symbols || reads.patterns || reads.brushes { + return Self { + patterns: true, + symbols: true, + images: true, + placed_documents: reads.placed_documents, + brushes: true, + text: true, + plugins: reads.plugins, + }; } reads } @@ -280,7 +297,11 @@ impl Reads { } match &c.kind { NodeKind::SymbolInstance { .. } => self.symbols = true, - NodeKind::Image(_) | NodeKind::PlacedDocument(_) => self.images = true, + NodeKind::Image(_) => self.images = true, + NodeKind::PlacedDocument(_) => { + self.images = true; + self.placed_documents = true; + } NodeKind::Text(t) => { self.text = true; self.symbols |= t.runs.iter().any(|r| r.inline.is_some()); diff --git a/crates/render/src/fx/pixels.rs b/crates/render/src/fx/pixels.rs index d57c34a315..b742d5718f 100644 --- a/crates/render/src/fx/pixels.rs +++ b/crates/render/src/fx/pixels.rs @@ -1,10 +1,10 @@ use super::bounds::{apply_carrying, item_effects, item_raster}; -use super::entries::{Content, DocInputs, Drawn, FX_RASTER_BUDGET, Inputs, ItemGeom, KeptImage, Made, Reads, feather_outline}; +use super::entries::{Content, DocInputs, Drawn, FX_RASTER_BUDGET, Inputs, ItemGeom, KeptImage, Made, Reads, feather_outline, raster_bytes}; #[cfg(test)] use super::raster::RASTERIZED; use super::raster::{ DRAG_PIXEL_BUDGET, PIXEL_BUDGET, PixelEntry, ViewCrop, content_changing, doc_raster_ppi, drag_scale, draw_placed, draw_scaled, filter_region, - filter_region_within, hard_edged, image_size, linear_key, looks_around, pan_margin, + filter_region_within, hard_edged, image_size, linear_key, looks_around, pan_margin, panned_exactly_whole, }; use super::{ Affine, AppearanceItem, Arc, BezPath, Channels, DefaultHasher, Document, FillRule, Frame, GeomContext, Hash, Hasher, Ink, Node, PixelFx, @@ -69,14 +69,18 @@ impl Renderer { /// raster holds at most [`PIXEL_BUDGET`] pixels and [`crate::MAX_RASTER_SIDE`] a side: content /// over the budget is cropped to the view (content with a [`Kept`] image to its window) when /// every effect only looks nearby, and content still over either limit is rendered at a lower - /// resolution. A whole raster at full resolution is cached while the object, the - /// zoom and what the content reads ([`Inputs`]) stay the same (panning only moves it), and - /// while interacting after the content only moved ([`Self::move_pixel_content`]). A cropped or - /// lower-resolution raster is cached while the object, the zoom and what the content reads stay - /// the same and a pan keeps the view inside the rect it was made for ([`PixelEntry::view`]): the - /// view, and for a raster cropped to it that is made again at the same zoom and rotation, outside - /// a drag and for content without a [`Kept`] image, the view with [`pan_margin`] around it. A - /// lower-resolution one is kept resampled to the view's pixels ([`Self::resampled`]). + /// resolution. A raster of the whole content is cached while the object, the zoom and what the + /// content reads ([`Inputs`]) stay the same (panning only moves it, and at a lower resolution + /// only by whole view and output pixels with the same output linear coefficients and the same + /// raster origin, scale and size as a fresh render, [`PixelEntry::pan`]), and at full resolution + /// while interacting after the content only moved ([`Self::move_pixel_content`]). One at a + /// lower resolution draws through its copy resampled + /// to the view's pixels ([`Self::draw_kept`]). A cropped raster is cached while the object, the + /// zoom and what the content reads stay the same and a pan keeps the view inside the rect it + /// was made for ([`PixelEntry::view`]): the view, and for a raster cropped to it that is made + /// again at the same zoom and rotation, outside a drag and for content without a [`Kept`] image, + /// the view with [`pan_margin`] around it. A cropped one at a lower resolution is kept + /// resampled to the view's pixels ([`Self::resampled`]). /// While dragging, content without such a raster to draw renders within [`DRAG_PIXEL_BUDGET`] /// pixels and is not cached, except content cropped to the view whose raster can move: its /// raster covers the view with [`pan_margin`] around it, and the drag's later frames move it with @@ -156,8 +160,14 @@ impl Renderer { Some(m) if !fits => full.intersect(room.inflate(m, m)), _ => full, }; - let (x0, y0) = (region.x0.floor(), region.y0.floor()); - let (rw, rh) = ((region.x1 - x0).max(1.0), (region.y1 - y0).max(1.0)); + // The origin and the sizes, rounded to 2^-20 device pixels, keep the raster's place, dimensions + // and filter scale stable across whole-pixel pans that leave rounding error in the view. Origin + // ties round to even steps, so whole-pixel shifts round alike across zero. Origins of 2^32 pixels + // or more in magnitude are kept as they are. Size fractions round ties away from zero. + let snap_origin = |v: f64| if v.abs() < 4_294_967_296.0 { (v * 1_048_576.0).round_ties_even() / 1_048_576.0 } else { v }; + let round_size = |v: f64| v.trunc() + (v.fract() * 1_048_576.0).round() / 1_048_576.0; + let (x0, y0) = (snap_origin(region.x0).floor(), snap_origin(region.y0).floor()); + let (rw, rh) = (round_size((region.x1 - x0).max(1.0)), round_size((region.y1 - y0).max(1.0))); // (vello_cpu panics drawing near `u16::MAX` pixels a side.) let side = f64::from(crate::MAX_RASTER_SIDE); let k = (PIXEL_BUDGET / (rw * rh)).sqrt().min(side / rw).min(side / rh).min(1.0); @@ -173,11 +183,13 @@ impl Renderer { let (aw, ah) = (around.width().ceil() + 1.0, around.height().ceil() + 1.0); (DRAG_PIXEL_BUDGET / (aw * ah)).sqrt().min(side / aw).min(side / ah).min(1.0) }); - // The cached raster: of the whole content at full size at this zoom, else of this view (and - // the margin around it). + // The cached raster: of the whole content at this zoom (at full size, or at a lower + // resolution when an effect looks anywhere in the object), else of this view (and the margin + // around it). + let entire = fits || margin.is_none(); let whole = fits && k >= 1.0; self.stats.view_sized += usize::from(!whole); - let in_view = (!whole).then(|| ViewCrop::of(f.view, room)); + let in_view = (!entire).then(|| ViewCrop::of(f.view, room)); let stamp = self.stamp; let channels = match f.ink.base() { Ink::Cmy => effects::pixel::Channels::CmyPlane, @@ -197,7 +209,18 @@ impl Renderer { }); let interacting = f.opts.interacting; let in_place = |e: &PixelEntry| match e.view { - None => whole, + None => e.pan.map_or(whole, |(pan, output_pan, output_linear)| { + let p = f.view * e.anchor; + entire + && panned_exactly_whole(pan, f.view) + && output_linear == linear_key(f.output) + && panned_exactly_whole(output_pan, f.output) + && e.k.to_bits() == k.to_bits() + && f64::from(e.image.width()) == w + && f64::from(e.image.height()) == h + && (p.x + e.rel.0).round() == x0 + && (p.y + e.rel.1).round() == y0 + }), Some(v) => !whole && (e.valid.is_some() || v.serves(f.view, screen)), }; // A raster a drag kept draws during a drag, while what the frame shows of the content lies @@ -229,7 +252,7 @@ impl Renderer { if e.image_left_out { self.image_left_out = self.image_left_out.map(|_| true); } - draw_scaled(ctx, image, at, k); + self.draw_kept(ctx, f, key, screen, (image, at, k)); return; } // During a drag, content without a raster to draw renders within the drag's budget (#2558). @@ -368,6 +391,10 @@ impl Renderer { Some((image, x, y)) => (image, x, y, 1.0), None => (image, x0, y0, k), }; + // A raster of the whole content at a lower resolution is kept whole for pans, and drawn + // through its copy resampled to the view's pixels ([`Self::draw_kept`]). + let low = key.is_some() && in_view.is_none() && k < 1.0 && content.kept.is_none_or(|k| k.shared) && !drag_keep; + let mut kept_low = None; // A cancelled export drew part of the content: that raster isn't kept for later frames. if !vectorcraft_doc::cancel::is_cancelled() && let Some(((key, made), inputs)) = key.zip(made).zip(inputs) @@ -386,8 +413,10 @@ impl Renderer { rel, k, image: image.clone(), - view: in_view, + view: (!whole && !low).then(|| ViewCrop::of(f.view, room)), valid, + pan: low.then(|| (f.view.translation(), f.output.translation(), linear_key(f.output))), + shown: None, made, inputs, moved, @@ -395,8 +424,8 @@ impl Renderer { image_left_out, stamp, }; - self.pixel_fx.insert(key, entry); - self.trim_fx_rasters(FX_RASTER_BUDGET); + self.keep_pixel_content(key, entry); + kept_low = low.then_some(key); } // An image over the limits was drawn at a frame's resolution: its raster is kept. The // placements of a copied image each draw their own (`Kept::shared`). @@ -406,7 +435,66 @@ impl Renderer { *kept.image.borrow_mut() = Some(KeptImage::Raster(image.clone(), place, failed, image_left_out)); if f.view == call { draw_scaled(ctx, image, (x0, y0), k) } else { draw_placed(ctx, image, call * place) } } - None => draw_scaled(ctx, image, (x0, y0), k), + None => self.draw_kept(ctx, f, kept_low, screen, (image, (x0, y0), k)), + } + } + + /// Keep `entry` for `key` and trim the cache, deferring trimming for a whole raster at a lower + /// resolution until [`Self::draw_kept`] draws it. + fn keep_pixel_content(&mut self, key: (usize, usize, Ink), entry: PixelEntry) { + let low = entry.pan.is_some(); + self.pixel_fx.insert(key, entry); + if !low { + self.trim_fx_rasters(FX_RASTER_BUDGET); + } + } + + /// Draw `(image, at, k)` as [`draw_scaled`] draws `image` at `at`, `1 / k` device pixels a + /// pixel. When it is the raster kept for `key` of the whole content at a lower resolution + /// ([`PixelEntry::pan`]), in the frame `f` onto `screen`, its copy resampled to the device + /// pixels of a frame through the same view ([`PixelEntry::shown`]) is drawn instead, made again + /// for a frame it does not serve. A copy that alone exceeds [`FX_RASTER_BUDGET`] is not made; + /// the raster draws scaled. When the cache exceeds its budget, [`Self::trim_fx_rasters`] + /// replaces a frame's whole rasters with their view copies before it evicts that frame's + /// entries, least recently drawn frames first. + /// A raster that covers none of `screen`'s pixels draws scaled. + fn draw_kept( + &mut self, + ctx: &mut RenderContext, + f: &Frame, + key: Option<(usize, usize, Ink)>, + screen: Rect, + (image, at, k): (std::sync::Arc, (f64, f64), f64), + ) { + let Some((key, e)) = key.and_then(|key| self.pixel_fx.get(&key).filter(|e| e.pan.is_some()).map(|e| (key, e))) else { + return draw_scaled(ctx, image, at, k); + }; + let p = f.view * e.anchor; + if let Some((_, copy, rel)) = e.shown.as_ref().filter(|(v, ..)| v.serves(f.view, screen)) { + draw_scaled(ctx, copy.clone(), ((p.x + rel.0).round(), (p.y + rel.1).round()), 1.0); + return; + } + let covered = Rect::new(at.0, at.1, at.0 + f64::from(image.width()) / k, at.1 + f64::from(image.height()) / k).intersect(screen); + let (w, h) = (covered.x1.ceil() - covered.x0.floor(), covered.y1.ceil() - covered.y0.floor()); + if w * h * 4.0 > FX_RASTER_BUDGET as f64 { + if let Some(e) = self.pixel_fx.get_mut(&key) { + e.shown = None; + } + self.trim_fx_rasters(FX_RASTER_BUDGET); + return draw_scaled(ctx, image, at, k); + } + match self.resampled(f, image.clone(), at, k, screen) { + Some((copy, x, y)) => { + if let Some(e) = self.pixel_fx.get_mut(&key) { + e.shown = Some((ViewCrop::of(f.view, screen), copy.clone(), (x - p.x, y - p.y))); + } + self.trim_fx_rasters(FX_RASTER_BUDGET); + draw_scaled(ctx, copy, (x, y), 1.0); + } + None => { + self.trim_fx_rasters(FX_RASTER_BUDGET); + draw_scaled(ctx, image, at, k); + } } } @@ -512,26 +600,38 @@ impl Renderer { } /// The inputs a raster of `n`'s content, which reads `reads`, is drawn with in frame `f`: the - /// color settings, the edge smoothing, whether dashed strokes draw as solid lines, the document's raster effects resolution (which a - /// Rasterize or De-Interlace anywhere in the content follows), the knockout `n` inherits and, - /// while `n` holds the isolated group, isolation mode; the pattern definitions, symbols and - /// brush library it reads; for images and placed documents their pixels and files, the - /// layer's Dim Images and the options they are drawn with (with + /// color settings, the render mode ([`crate::RenderOptions::precise`]), the edge smoothing mode, + /// the hidden objects and the instance left out during symbol editing, whether guides and + /// template layers are left out, the guide color and style, whether Layer Options show on + /// screen, whether dashed strokes draw as solid lines, + /// the document's raster effects resolution (which a Rasterize or De-Interlace anywhere in the + /// content follows), the knockout `n` inherits and, while `n` holds the isolated group, + /// isolation mode; the pattern definitions, symbols and brush library it reads; for images and + /// placed documents their pixels and files, the layer's Dim Images, whether images show in + /// Outline mode ([`Self::shows_outline_images`]) and the options they are drawn with (with /// [`crate::RenderOptions::kept_images_only`], also which pixels and undecodable notes the - /// image store holds); for type the fonts and the hyphenation exceptions, whether overprinting shows - /// ([`crate::proof::overprints`]) and Document Setup's substitution highlights; and the - /// plug-ins installed, with the names of the document's swatches and patterns and its pattern - /// definitions (a plug-in's painted pieces can name them), when an object in it has a plug-in - /// effect, and when it shows symbol or pattern art and an object in the document's symbol or - /// pattern art has one. + /// image store holds); for content that holds placed documents, shows symbol art or uses + /// brushed strokes, whether placed documents draw from background bitmaps + /// ([`crate::placed_document::progressive_bitmaps`]) and, when progressive previews are on, + /// how many bitmaps are ready ([`crate::placed_document::generation`]); for type the fonts and the + /// hyphenation exceptions, whether overprinting shows ([`crate::proof::overprints`]) and + /// Document Setup's substitution highlights; and the plug-ins installed, with the names of the + /// document's swatches and patterns and its pattern definitions (a plug-in's painted pieces + /// can name them), when an object in the content has a plug-in effect, when it uses brushed + /// strokes and an object in the document's brush art has one, and when it shows symbol or + /// pattern art and an object in the document's symbol or pattern art has one. pub(crate) fn raster_inputs(&mut self, f: &Frame, n: &Node, reads: Reads) -> Inputs { let doc = self.doc_inputs(f.doc); let mut h = DefaultHasher::new(); - (doc.cms, f.opts.anti_alias.threshold(), self.knockout, f.doc.raster_effects_ppi.to_bits()).hash(&mut h); - // Cached effects on containers can include paths made into guides. - f.opts.hide_guides.hash(&mut h); + (doc.cms, f.opts.precise, std::mem::discriminant(&f.opts.anti_alias), self.knockout, f.doc.raster_effects_ppi.to_bits()).hash(&mut h); + // Cached effects on containers can include paths made into guides, drawn in the guide + // color and style, template layers, and sublayers drawn as their Layer Options show them. + let o = f.opts; + (o.hide_guides, o.guide, o.hide_templates, o.skip_templates, o.dim_templates).hash(&mut h); // Cached effects can include dashed strokes drawn as solid lines. f.opts.solid_dashes.hash(&mut h); + f.hidden_inputs.hash(&mut h); + f.opts.isolated.and_then(|_| f.doc.symbol_edit.as_ref()?.instance).hash(&mut h); if let Some((isolated, path)) = self.isolation_path(f) && n.id != isolated && path.contains(&n.id) @@ -547,12 +647,20 @@ impl Renderer { if reads.images { let o = f.opts; (doc.images, self.dim_images.map(f32::to_bits), o.smooth_images, o.image_mips, o.trace_views, o.progressive_placed).hash(&mut h); + self.shows_outline_images(f).hash(&mut h); o.trace_source.as_deref().hash(&mut h); o.mark_undecoded_images.hash(&mut h); // With only kept pixels drawn, a raster is made again once the store holds more pixels // or notes an image as undecodable. o.kept_images_only.then(|| crate::images::store().added()).hash(&mut h); } + if reads.placed_documents { + let progressive = crate::placed_document::progressive_bitmaps(f); + progressive.hash(&mut h); + if f.opts.progressive_placed { + crate::placed_document::generation().hash(&mut h); + } + } if reads.brushes { self.brushes.library_key(f.doc, self.stamp).hash(&mut h); } @@ -566,7 +674,7 @@ impl Renderer { // Color bitmap glyphs are sampled as images are (`draw_glyph_image`). (vectorcraft_text::layout_inputs(), crate::proof::overprints(f.opts), highlights, o.smooth_images).hash(&mut h); } - if reads.plugins || (doc.plugins && (reads.symbols || reads.patterns)) { + if reads.plugins || (reads.brushes && self.brushes.has_plugins()) || (doc.plugins && (reads.symbols || reads.patterns)) { (effects::plugin_revision(), doc.names, doc.patterns).hash(&mut h); } Inputs { reads, key: h.finish(), _doc: doc } @@ -621,27 +729,46 @@ impl Renderer { d } - /// Drop the least recently drawn shadow and filtered-content rasters beyond `budget` bytes - /// ([`FX_RASTER_BUDGET`]). + /// Trim the shadow and filtered-content entries to `budget` bytes ([`FX_RASTER_BUDGET`]), one + /// frame stamp at a time from the least recently drawn: replace that stamp's whole rasters that + /// have view copies with those copies, then, while the entries still exceed the budget, evict + /// that stamp's entries, reduced ones included. pub(super) fn trim_fx_rasters(&mut self, budget: usize) { - let shadows = self.shadows.iter().map(|(k, e)| (e.stamp, false, *k, e.bytes())); - let pixels = self.pixel_fx.iter().map(|(k, e)| (e.stamp, true, *k, e.bytes())); - let mut all: Vec<_> = shadows.chain(pixels).collect(); - let mut total: usize = all.iter().map(|e| e.3).sum(); + let mut total: usize = self.shadows.values().map(|e| e.bytes()).sum::() + self.pixel_fx.values().map(|e| e.bytes()).sum::(); if total <= budget { return; } + let shadows = self.shadows.iter().map(|(k, e)| (e.stamp, false, *k)); + let pixels = self.pixel_fx.iter().map(|(k, e)| (e.stamp, true, *k)); + let mut all: Vec<_> = shadows.chain(pixels).collect(); all.sort_unstable_by_key(|e| e.0); - for (_, pixel, key, bytes) in all { - if total <= budget { - break; + for group in all.chunk_by(|a, b| a.0 == b.0) { + for &(_, pixel, key) in group { + if total <= budget { + return; + } + if pixel + && let Some(e) = self.pixel_fx.get_mut(&key).filter(|e| e.pan.is_some()) + && let Some((view, copy, rel)) = e.shown.take() + { + total -= raster_bytes(&e.image); + e.image = copy; + e.k = 1.0; + e.rel = rel; + e.view = Some(view); + e.pan = None; + } } - if pixel { - self.pixel_fx.remove(&key); - } else { - self.shadows.remove(&key); + for &(_, pixel, key) in group { + if total <= budget { + return; + } + if pixel { + total -= self.pixel_fx.remove(&key).map_or(0, |e| e.bytes()); + } else { + total -= self.shadows.remove(&key).map_or(0, |e| e.bytes()); + } } - total -= bytes; } } diff --git a/crates/render/src/fx/raster.rs b/crates/render/src/fx/raster.rs index 02bf918089..99723f215e 100644 --- a/crates/render/src/fx/raster.rs +++ b/crates/render/src/fx/raster.rs @@ -90,16 +90,32 @@ pub(crate) struct PixelEntry { pub(super) rel: (f64, f64), pub(super) k: f64, pub(crate) image: std::sync::Arc, - /// For a raster of the content's whole reach at full size, `None`: it draws after a pan too. - /// For one cropped to the view, or made at a lower resolution, the view and the rect it was - /// made for: it draws only there, so dragging other art over the object keeps it (a wide blur, - /// or any blur zoomed in, reaches past the pixel budget). + /// For a raster of the content's whole reach at full size, or at a lower resolution with its + /// pans kept in [`Self::pan`], `None`: it draws after a pan too. For one cropped to the view, + /// or another raster made at a lower resolution (of an image kept for one placement, or kept + /// by a drag), the view and the rect it was made for: it draws only there, so dragging other + /// art over the object keeps it (a wide blur, or any blur zoomed in, reaches past the pixel + /// budget). pub(super) view: Option, /// For a raster a drag's frame kept of content cropped to the view, the device pixels (against /// the anchor's view position) whose pixels the effects decided with all they look at: the /// drag's later frames move the raster with its object while what they show of it lies within /// ([`Renderer::move_pixel_content`]). `None` for other rasters. pub(super) valid: Option, + /// For a raster of the content's whole reach made at a lower resolution than the view's, the + /// pans of the view and output it was made through, and the output's linear coefficients: it + /// draws when both grids pan by whole pixels ([`panned_exactly_whole`]), the output's linear + /// coefficients stay the same, its rounded origin matches a fresh render's floored origin, + /// its scale is bit-identical to a fresh render's, and its size matches a fresh render's. + /// `None` for other rasters. + pub(super) pan: Option<(Vec2, Vec2, [u64; 4])>, + /// For such a raster, its pixels resampled to the device pixels of the last frame that drew it, + /// the view and rect they were made for, and their top-left against the anchor's view position: + /// a frame they serve copies them ([`Renderer::draw_kept`]). Copies that alone exceed the cache + /// budget are not made. When the cache exceeds its budget, [`Renderer::trim_fx_rasters`] + /// goes through the frames least recently drawn first, and replaces a frame's whole rasters + /// with their view copies before it evicts that frame's entries. + pub(super) shown: Option<(ViewCrop, std::sync::Arc, (f64, f64))>, pub(super) made: Made, /// What the content read when the raster was made, with the channels the effects ran on and, /// under De-Interlace, the raster resolution. @@ -121,10 +137,28 @@ pub(crate) struct PixelEntry { impl PixelEntry { /// The bytes it holds, for [`FX_RASTER_BUDGET`]. pub(crate) fn bytes(&self) -> usize { - raster_bytes(&self.image) + self.made.bytes() + raster_bytes(&self.image) + self.shown.as_ref().map_or(0, |(_, copy, _)| raster_bytes(copy)) + self.made.bytes() } } +/// Is `view` panned by whole device pixels from a view whose pan was `pan`? +pub(super) fn panned_whole(pan: Vec2, view: Affine) -> bool { + let d = view.translation() - pan; + (d - Vec2::new(d.x.round(), d.y.round())).hypot() < 1e-6 +} + +/// Is `view` panned by whole device pixels from `pan`, allowing floating-point rounding +/// with a tolerance between 1e-9 and 1e-6 device pixels per axis and a combined error +/// below 1e-6 device pixels, as required by [`panned_whole`]? +pub(super) fn panned_exactly_whole(pan: Vec2, view: Affine) -> bool { + let at = view.translation(); + let whole = |a: f64, b: f64| { + let d = b - a; + (d - d.round()).abs() <= (f64::EPSILON * 64.0 * (a.abs() + b.abs())).clamp(1e-9, 1e-6) + }; + panned_whole(pan, view) && whole(pan.x, at.x) && whole(pan.y, at.y) +} + /// The four linear coefficients of `view` (zoom and rotation, not the pan), as cache keys. pub(crate) fn linear_key(view: Affine) -> [u64; 4] { let c = view.as_coeffs(); @@ -153,7 +187,7 @@ impl ViewCrop { let d = view.translation() - self.pan; let whole = Vec2::new(d.x.round(), d.y.round()); let s = screen - whole; - (d - whole).hypot() < 1e-6 && s.x0 >= self.screen.x0 && s.y0 >= self.screen.y0 && s.x1 <= self.screen.x1 && s.y1 <= self.screen.y1 + panned_whole(self.pan, view) && s.x0 >= self.screen.x0 && s.y0 >= self.screen.y0 && s.x1 <= self.screen.x1 && s.y1 <= self.screen.y1 } /// The rect the raster was made for, in the device pixels of a frame through `view` that it diff --git a/crates/render/src/fx/renderer.rs b/crates/render/src/fx/renderer.rs index c119ef8b64..ebc82abeb1 100644 --- a/crates/render/src/fx/renderer.rs +++ b/crates/render/src/fx/renderer.rs @@ -1142,6 +1142,7 @@ mod tests { visible: Rect::new(0.0, 0.0, 100.0, 100.0), px: 1.0, opts: &opts, + hidden_inputs: Frame::hidden_inputs(&opts), ink: Ink::Display, output: Affine::IDENTITY, plates: None, diff --git a/crates/render/src/fx/tests.rs b/crates/render/src/fx/tests.rs index be44374572..21e0e9fbd9 100644 --- a/crates/render/src/fx/tests.rs +++ b/crates/render/src/fx/tests.rs @@ -9,6 +9,77 @@ use super::{DRAG_PIXEL_BUDGET, Drawn, PIXEL_BUDGET, drag_scale, filter_region, f use crate::tests_fontchange::{fonts_steady, with_fonts_unchanged}; use crate::{RenderOptions, Rendered, Renderer}; +/// Placed documents, symbol art and brushed strokes follow progressive bitmap readiness. +/// Plain images and paths painted only with patterns keep their rasters when a bitmap is ready. +#[test] +fn reads_follow_progressive_placed_documents_in_content_and_art() { + use super::Reads; + use vectorcraft_doc::{ImageObject, LinkInfo, NodeKind, PlacedDocument}; + + let mut d = Document::new(100.0, 100.0); + let placed = Node::new( + d.alloc_id(), + NodeKind::PlacedDocument(Box::new(PlacedDocument { + link: LinkInfo::new("/art/card.vectorcraft"), + key: "placed".into(), + bounding: false, + page_box: Default::default(), + width: 20.0, + height: 20.0, + xf: Affine::IDENTITY, + placement: Default::default(), + })), + ); + assert!(Reads::of(&placed).placed_documents, "a placed document reads progressive bitmap readiness"); + + let symbol = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Stamp".into(), xf: Affine::IDENTITY }); + assert!(Reads::of(&symbol).placed_documents, "a symbol instance reads progressive bitmap readiness"); + + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + appearance.stroke_mut().unwrap().brush = Some("Stamp".into()); + let brushed = Node::path(d.alloc_id(), shapes::line((0.0, 0.0).into(), (20.0, 20.0).into()), appearance); + assert!(Reads::of(&brushed).placed_documents, "a brushed stroke reads progressive bitmap readiness"); + + let image = Node::new( + d.alloc_id(), + NodeKind::Image(Box::new(ImageObject { + key: "image".into(), + width: 20, + height: 20, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ); + assert!(!Reads::of(&image).placed_documents, "a plain image does not read progressive bitmap readiness"); + + let patterned = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), + Appearance::basic(Paint::Pattern { pattern: "Tile".into(), xf: Affine::IDENTITY }, Paint::None, 0.0), + ); + assert!(!Reads::of(&patterned).placed_documents, "a pattern-only path does not read progressive bitmap readiness"); +} + +/// Brush and symbol art can hold images drawn with the frame's image options, and brush art can +/// show symbols. +#[test] +fn reads_follow_images_in_brush_and_symbol_art() { + use super::Reads; + use vectorcraft_doc::NodeKind; + + let mut d = Document::new(100.0, 100.0); + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 1.0); + appearance.stroke_mut().unwrap().brush = Some("Stamp".into()); + let brushed = Node::path(d.alloc_id(), shapes::line((0.0, 0.0).into(), (20.0, 20.0).into()), appearance); + assert!(Reads::of(&brushed).images, "a brushed stroke reads images"); + assert!(Reads::of(&brushed).symbols, "a brushed stroke reads symbol art"); + + let symbol = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Stamp".into(), xf: Affine::IDENTITY }); + assert!(Reads::of(&symbol).images, "a symbol instance reads images"); +} + /// Rasterize and culling include the complete rendered image under lights from opposite sides. #[test] fn rendered_three_d_painted_bounds_hold_both_shadows() { @@ -1889,6 +1960,710 @@ fn a_zoomed_drag_keeps_the_sampling_footprint_inside_the_valid_crop() { assert_eq!(r.stats.previewed, 1, "the sampling footprint outside the valid crop filters the content again"); } +/// At 6400% a 200 × 150 pt rectangle with Torn Edges, which looks anywhere in the object, covers +/// 12800 × 9600 px, past the pixel budget, so its raster holds the whole object at a lower +/// resolution. The view shows its torn right edge. Pans by whole pixels with the same sampling +/// grid draw that raster again, and a frame through the same view copies its pixels resampled to +/// the view; a new fill, color mode or zoom, or a pan by part of a pixel, filters the content +/// again. +#[test] +fn pans_draw_the_lower_resolution_raster_of_the_whole_object_again() { + let mut d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let id = d.layers[0].children().unwrap()[0].id; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |zoom: f64, dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(zoom) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let first = r.render(&d, 1280, 800, view(64.0, 0.0), &opts); + assert!(first.pixels.as_chunks::<4>().0.iter().any(|pixel| *pixel != first.pixel(0, 0)), "the view shows the torn edge"); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let drawn = |r: &Renderer, image: &Arc| r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, image)); + for dx in [40.0, 80.0, -40.0] { + let pixels = r.render(&d, 1280, 800, view(64.0, dx), &opts).pixels; + assert!(drawn(&r, &image), "a pan of {dx} px draws the kept raster"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(64.0, dx), &opts).pixels, "a pan of {dx} px as a new renderer draws it"); + } + let copy = |r: &Renderer| r.pixel_fx.values().next().and_then(|e| e.shown.as_ref()).map(|(_, copy, _)| copy.clone()).unwrap(); + let before = copy(&r); + let _ = r.render(&d, 1280, 800, view(64.0, -40.0), &opts); + assert!(Arc::ptr_eq(&before, ©(&r)), "a frame through the same view copies the resampled pixels"); + for pan in [(39.9999999, 0.0), (0.0, 39.9999999), (40.0000001, 0.0), (0.0, 40.0000001)] { + let _ = r.render(&d, 1280, 800, view(64.0, 0.0), &opts); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let shifted = Affine::translate(pan) * view(64.0, 0.0); + let pixels = r.render(&d, 1280, 800, shifted, &opts).pixels; + assert!(!drawn(&r, &image), "a nearly whole-pixel pan with a different raster origin or sampling grid filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, shifted, &opts).pixels, "after a nearly whole-pixel pan"); + } + let _ = r.render(&d, 1280, 800, view(64.0, 40.0), &opts); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let n = d.node_mut(id).unwrap(); + let effects = std::mem::take(&mut n.appearance.effects); + n.appearance = Appearance::basic(Paint::solid(Color::rgb(0.1, 0.4, 0.9)), Paint::None, 0.0).into(); + n.appearance.effects = effects; + let pixels = r.render(&d, 1280, 800, view(64.0, 40.0), &opts).pixels; + assert!(!drawn(&r, &image), "a new fill filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(64.0, 40.0), &opts).pixels, "with the new fill"); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + d.color_mode = vectorcraft_doc::ColorMode::Cmyk; + let pixels = r.render(&d, 1280, 800, view(64.0, 40.0), &opts).pixels; + assert!(!drawn(&r, &image), "a new color mode filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(64.0, 40.0), &opts).pixels, "in the new color mode"); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let pixels = r.render(&d, 1280, 800, view(48.0, 40.0), &opts).pixels; + assert!(!drawn(&r, &image), "a new zoom filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(48.0, 40.0), &opts).pixels, "at the new zoom"); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let pixels = r.render(&d, 1280, 800, view(48.0, 40.5), &opts).pixels; + assert!(!drawn(&r, &image), "a pan by part of a pixel filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(48.0, 40.5), &opts).pixels, "after a pan by part of a pixel"); +} + +/// At 6400% a 2000 × 1 pt bar with Torn Edges is 128000 px wide, so its whole-object raster is +/// capped at the widest raster side and its scale stays the same across vertical pans. A vertical +/// pan by part of a pixel that leaves the raster's rounded origin and size unchanged moves the +/// sampling grid, so it filters the content again. +#[test] +fn a_pan_by_part_of_a_pixel_filters_a_width_capped_whole_object_raster_again() { + let d = doc_with(Rect::new(100.0, 100.0, 2100.0, 101.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |y: f64| Affine::translate((640.0, y)) * Affine::scale(64.0) * Affine::translate((-1100.0, -100.5)); + for (start, pan) in [(400.1, 40.2), (400.3, 40.7)] { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(start), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + assert_eq!(u32::from(kept.image.width()), crate::MAX_RASTER_SIDE, "the raster is as wide as a raster can be"); + let image = kept.image.clone(); + let pixels = r.render(&d, 1280, 800, view(start + pan), &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "a pan of {pan} px from {start} filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(start + pan), &opts).pixels, "after a pan of {pan} px from {start}"); + } +} + +/// The canvas centers its view on a document point and pans by moving that point by the pan's +/// device pixels over the scale, here across and down in turn. At scales from 50 to 120, with +/// centers on whole points and between them, each whole-pixel pan keeps the raster's origin, scale +/// and size bit-identical to a fresh render's and draws the kept raster. +#[test] +fn pans_of_a_centered_view_draw_the_whole_object_raster_again() { + let d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |scale: f64, c: Point| Affine::translate((640.0, 400.0)) * Affine::scale(scale) * Affine::translate((-c.x, -c.y)); + for (scale, c) in [ + (96.0, Point::new(295.3, 175.7)), + (96.0, Point::new(291.137, 171.913)), + (96.0, Point::new(150.0, 120.0)), + (72.0, Point::new(200.0, 175.0)), + (120.0, Point::new(295.3, 175.7)), + (56.0, Point::new(150.0, 120.0)), + (50.0, Point::new(291.137, 171.913)), + ] { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(scale, c), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let mut at = c; + for i in 1..=4 { + if i % 2 == 1 { + at.x -= 40.0 / scale; + } else { + at.y -= 40.0 / scale; + } + let pixels = r.render(&d, 1280, 800, view(scale, at), &opts).pixels; + assert!(r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "pan {i} of 40 px at scale {scale} from {c:?} draws the kept raster"); + let mut fresh = Renderer::new(); + assert!(pixels == fresh.render(&d, 1280, 800, view(scale, at), &opts).pixels, "pan {i} at scale {scale} from {c:?}"); + let made = fresh.pixel_fx.values().next().unwrap(); + let kept = r.pixel_fx.values().next().unwrap(); + assert_eq!(kept.k.to_bits(), made.k.to_bits(), "pan {i} at scale {scale} from {c:?}"); + assert_eq!((kept.image.width(), kept.image.height()), (made.image.width(), made.image.height())); + } + } +} + +/// A whole-object raster kept for pans draws again only while its scale, its size, and the zoom, +/// rotation and whole-pixel pan of the output it was made for match the frame's. +#[test] +fn a_whole_object_raster_draws_after_a_pan_only_as_made_for_this_output_scale_and_size() { + use super::linear_key; + let d = doc_with(Rect::new(100.0, 100.0, 2100.0, 101.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |dy: f64| Affine::translate((640.0, 400.0 + dy)) * Affine::scale(64.0) * Affine::translate((-1100.0, -100.5)); + type Change = fn(&mut super::PixelEntry); + let changes: [(&str, Change); 6] = [ + ("the same output scale and size", |_| {}), + ("an output at another zoom", |e| { + if let Some(pan) = &mut e.pan { + pan.2 = linear_key(Affine::scale(2.0) * Affine::scale(64.0)); + } + }), + ("an output panned by part of a pixel", |e| { + if let Some(pan) = &mut e.pan { + pan.1.y += 0.5; + } + }), + ("a scale off by a small relative amount", |e| e.k *= 1.0 + 1e-6), + ("another width", |e| { + e.image = Arc::new(vello_cpu::Pixmap::new(e.image.width() + 1, e.image.height())); + }), + ("another height", |e| { + e.image = Arc::new(vello_cpu::Pixmap::new(e.image.width(), e.image.height() + 1)); + }), + ]; + for (case, (what, change)) in changes.into_iter().enumerate() { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let e = r.pixel_fx.values_mut().next().unwrap(); + assert!(e.k < 1.0 && e.pan.is_some(), "a raster of the whole object kept for pans"); + assert_eq!(u32::from(e.image.width()), crate::MAX_RASTER_SIDE, "the raster is as wide as a raster can be"); + change(e); + let image = e.image.clone(); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + let reused = r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)); + assert_eq!(reused, case == 0, "reuse after a pan, for {what}"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "after a pan, for {what}"); + } +} + +/// A width-capped whole-object raster draws after a whole-pixel pan, but filters again when the +/// pan differs from whole pixels by more than floating-point rounding. +#[test] +fn a_pan_near_a_whole_pixel_filters_a_width_capped_whole_object_raster_again() { + let d = doc_with(Rect::new(100.0, 100.0, 2100.0, 101.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |y: f64| Affine::translate((640.0, y)) * Affine::scale(64.0) * Affine::translate((-1100.0, -100.5)); + let drawn = |r: &Renderer, image: &Arc| r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, image)); + for start in [400.1, 400.3] { + for pan in [40.0000001, 39.9999999, 40.0] { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(start), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + assert_eq!(u32::from(kept.image.width()), crate::MAX_RASTER_SIDE, "the raster is as wide as a raster can be"); + let image = kept.image.clone(); + let pixels = r.render(&d, 1280, 800, view(start + pan), &opts).pixels; + if pan == 40.0 { + assert!(drawn(&r, &image), "a whole-pixel pan of the width-capped raster draws the kept raster"); + } else { + assert!(!drawn(&r, &image), "a pan within 1e-6 px of whole but off the grid filters the content again"); + } + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(start + pan), &opts).pixels, "after a pan of {pan} px from {start}"); + } + } +} + +/// Hiding a member of a group filters its whole-object raster again after a pan by whole pixels. +#[test] +fn hiding_a_member_filters_the_whole_object_raster_again_after_a_pan() { + let mut d = Document::new(100.0, 100.0); + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let members = vec![square(Rect::new(100.0, 100.0, 300.0, 250.0), Color::WHITE), square(Rect::new(200.0, 100.0, 300.0, 250.0), Color::BLACK)]; + let id = members[1].id; + let mut g = Node::group(d.alloc_id(), members); + g.appearance.effects = vec![Effect { id: "sketch.tornEdges".into(), params: json!({}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let mut opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + opts.hidden.insert(id); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "hiding a member filters the content again"); +} + +/// Image smoothing changes the pixels of an effected stroke whose scatter brush holds an image. +#[test] +fn image_smoothing_filters_a_brushed_strokes_raster_again_after_a_pan() { + use vectorcraft_brush::{Brush, BrushKind, Colorization, Scatter}; + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + + let mut d = Document::new(160.0, 100.0); + let rgba = [0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 255]; + let png = crate::encode::png::encode(&rgba, 2, 2, &Default::default()).unwrap(); + d.images.insert("checks".into(), ImageBlob::new("image/png", png)); + let art = Node::new( + d.alloc_id(), + NodeKind::Image(Box::new(ImageObject { + key: "checks".into(), + width: 2, + height: 2, + xf: Affine::IDENTITY, + link: None, + placement: Default::default(), + pixels: None, + })), + ); + vectorcraft_brush::store( + &mut d, + &[Brush { name: "Checks".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }], + ); + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 20.0); + appearance.stroke_mut().unwrap().brush = Some("Checks".into()); + let mut n = Node::path(d.alloc_id(), shapes::line((20.0, 50.0).into(), (100.0, 50.0).into()), appearance); + n.appearance.effects = vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": 1}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let mut opts = RenderOptions { background: Some([255, 255, 255, 255]), smooth_images: false, image_mips: false, ..Default::default() }; + let mut r = Renderer::new(); + let _ = r.render(&d, 160, 100, Affine::IDENTITY, &opts); + let image = r.pixel_fx.values().next().unwrap().image.clone(); + let view = Affine::translate((4.0, 0.0)); + let unchanged = Renderer::new().render(&d, 160, 100, view, &opts).pixels; + opts.smooth_images = true; + let pixels = r.render(&d, 160, 100, view, &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "image smoothing filters the content again"); + assert!(pixels != unchanged, "image smoothing changes the brush art through the effect"); + assert!(pixels == Renderer::new().render(&d, 160, 100, view, &opts).pixels, "image smoothing draws as a new renderer does"); +} + +/// A symbol's fill color changes the pixels of an effected stroke whose scatter brush shows it. +#[test] +fn editing_a_symbol_in_brush_art_filters_a_brushed_strokes_raster_again_after_a_pan() { + use vectorcraft_brush::{Brush, BrushKind, Colorization, Scatter}; + use vectorcraft_doc::{NodeKind, Symbol}; + + let mut d = Document::new(160.0, 100.0); + let mut art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(-4.0, -4.0, 4.0, 4.0)), + Appearance::basic(Paint::solid(Color::rgb(0.9, 0.1, 0.1)), Paint::None, 0.0), + ); + d.symbols.push(Symbol { dynamic: false, name: "Stamp".into(), art: Arc::new(art.clone()) }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Stamp".into(), xf: Affine::IDENTITY }); + vectorcraft_brush::store( + &mut d, + &[Brush { + name: "Stamps".into(), + kind: BrushKind::Scatter(Scatter { art: instance, colorization: Colorization::None, ..Default::default() }), + }], + ); + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); + appearance.stroke_mut().unwrap().brush = Some("Stamps".into()); + let mut n = Node::path(d.alloc_id(), shapes::line((20.0, 50.0).into(), (100.0, 50.0).into()), appearance); + n.appearance.effects = vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": 1}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let mut r = Renderer::new(); + let _ = r.render(&d, 160, 100, Affine::IDENTITY, &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.view.is_none(), "a raster of the whole object"); + let image = kept.image.clone(); + let view = Affine::translate((4.0, 0.0)); + let unchanged = Renderer::new().render(&d, 160, 100, view, &opts).pixels; + art.appearance = Appearance::basic(Paint::solid(Color::rgb(0.1, 0.4, 0.9)), Paint::None, 0.0).into(); + d.symbols[0].art = Arc::new(art); + let pixels = r.render(&d, 160, 100, view, &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "editing a symbol in brush art filters the content again"); + assert!(pixels == Renderer::new().render(&d, 160, 100, view, &opts).pixels, "the edited symbol draws as a new renderer does"); + assert!(pixels != unchanged, "the edited symbol changes the brush art through the effect"); +} + +/// Removing a plug-in used only in brush art filters a stroke again after a whole-pixel pan. +#[test] +fn removing_a_plugin_in_brush_art_filters_a_brushed_strokes_raster_again_after_a_pan() { + use vectorcraft_brush::{Brush, BrushKind, Colorization, Scatter}; + use vectorcraft_geom::{PathData, SubPath}; + use vectorcraft_plugins::wat as tpl; + + let _fonts = fonts_steady(); + const ID: &str = "test.render.fx.brush-art"; + let triangle = PathData::single(SubPath::polyline(&[Point::new(-4.0, -4.0), Point::new(4.0, -4.0), Point::new(0.0, 4.0)], true)); + let output = json!({"objects": [{"path": triangle}]}).to_string(); + let module = wat::parse_str(tpl::returning(&tpl::manifest(ID, "effect", "{}"), &output)).unwrap(); + vectorcraft_plugins::registry::install_bytes(&module).unwrap(); + + let mut d = Document::new(160.0, 100.0); + let mut r = Renderer::new(); + let mut art = + Node::path(d.alloc_id(), shapes::rectangle(Rect::new(-4.0, -4.0, 4.0, 4.0)), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + art.appearance.effects = vec![Effect { id: format!("plugin.{ID}"), params: json!({}), visible: true }]; + vectorcraft_brush::store( + &mut d, + &[Brush { name: "Stamps".into(), kind: BrushKind::Scatter(Scatter { art, colorization: Colorization::None, ..Default::default() }) }], + ); + let mut appearance = Appearance::basic(Paint::None, Paint::solid(Color::BLACK), 2.0); + appearance.stroke_mut().unwrap().brush = Some("Stamps".into()); + let mut n = Node::path(d.alloc_id(), shapes::line((20.0, 50.0).into(), (100.0, 50.0).into()), appearance); + n.appearance.effects = vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": 1}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + let opts = RenderOptions { precise: true, background: Some([255, 255, 255, 255]), ..Default::default() }; + let _ = r.render(&d, 160, 100, Affine::IDENTITY, &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.view.is_none(), "a raster of the whole object"); + let image = kept.image.clone(); + let view = Affine::translate((4.0, 0.0)); + let unchanged = Renderer::new().render(&d, 160, 100, view, &opts).pixels; + assert!(vectorcraft_plugins::registry::remove(ID), "the plug-in was installed"); + let pixels = r.render(&d, 160, 100, view, &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "removing the brush art's plug-in filters the content again"); + assert!(pixels != unchanged, "the plug-in changes the brush art through the effect"); + assert!(pixels == Renderer::new().render(&d, 160, 100, view, &opts).pixels, "removing the plug-in draws as a new renderer does"); +} + +/// Symbol editing leaves out the original instance inside a group's whole-object raster. +#[test] +fn symbol_editing_filters_the_whole_object_raster_again_after_a_pan() { + use vectorcraft_doc::{NodeKind, Symbol, SymbolEdit}; + + let mut d = Document::new(100.0, 100.0); + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let art = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(200.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0), + ); + d.symbols.push(Symbol { dynamic: false, name: "Stamp".into(), art: Arc::new(art.clone()) }); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Stamp".into(), xf: Affine::IDENTITY }); + let id = instance.id; + let mut g = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(instance)]); + g.appearance.effects = vec![Effect { id: "sketch.tornEdges".into(), params: json!({}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, g).unwrap(); + let mut opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let layer = d.add_layer(Some("Stamp")); + let copy = d.reid(&art); + d.insert(Some(layer), 0, copy).unwrap(); + d.symbol_edit = Some(SymbolEdit { + symbol: "Stamp".into(), + layer, + instance: Some(id), + xf: Affine::IDENTITY, + group: false, + changed: false, + back_isolation: None, + back_layer: None, + }); + opts.isolated = Some(layer); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "symbol editing filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "symbol editing draws as a new renderer does"); +} + +/// Hiding or skipping template layers filters the whole-object raster of a layer with effects +/// that holds a template sublayer again after a pan by whole pixels. +#[test] +fn hiding_templates_filters_the_whole_object_raster_again_after_a_pan() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let white = square(Rect::new(100.0, 100.0, 300.0, 250.0), Color::WHITE); + let black = square(Rect::new(200.0, 100.0, 300.0, 250.0), Color::BLACK); + let mut template = Node::layer(d.alloc_id(), "Template", vectorcraft_doc::LayerColor::Preset(0)); + if let vectorcraft_doc::NodeKind::Layer { template: flag, children, .. } = &mut template.kind { + *flag = true; + children.push(black); + } + d.insert(Some(l), 0, Arc::unwrap_or_clone(white)).unwrap(); + d.insert(Some(l), 1, template).unwrap(); + d.node_mut(l).unwrap().appearance.effects = vec![Effect { id: "sketch.tornEdges".into(), params: json!({}), visible: true }]; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), dim_templates: false, ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + for (left_out, what) in + [(RenderOptions { hide_templates: true, ..opts.clone() }, "hiding"), (RenderOptions { skip_templates: true, ..opts.clone() }, "skipping")] + { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &left_out).pixels; + assert!(fresh != Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "the template shows through the effect"); + let pixels = r.render(&d, 1280, 800, view(40.0), &left_out).pixels; + assert!(pixels == fresh, "{what} templates filters the content again"); + } +} + +/// Show Images in Outline Mode filters the whole-object raster of a layer with Torn Edges and +/// an embedded image in a sublayer with Preview off again after a pan by whole pixels. +#[test] +fn outline_images_filters_the_whole_object_raster_again_after_a_pan() { + use vectorcraft_doc::{ImageBlob, ImageObject, NodeKind}; + + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let rgba = [255, 0, 0, 255].repeat(200 * 150); + let png = crate::encode::png::encode(&rgba, 200, 150, &Default::default()).unwrap(); + d.images.insert("red".into(), ImageBlob::new("image/png", png)); + let im = ImageObject { + key: "red".into(), + width: 200, + height: 150, + xf: Affine::translate((100.0, 100.0)), + link: None, + placement: Default::default(), + pixels: None, + }; + let image = Arc::new(Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))); + let mut outlined = Node::layer(d.alloc_id(), "Outlined", vectorcraft_doc::LayerColor::Preset(0)); + if let NodeKind::Layer { preview, children, .. } = &mut outlined.kind { + *preview = false; + children.push(image); + } + d.insert(Some(l), 0, white).unwrap(); + d.insert(Some(l), 1, outlined).unwrap(); + d.node_mut(l).unwrap().appearance.effects = vec![Effect { id: "sketch.tornEdges".into(), params: json!({}), visible: true }]; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.pan.is_some(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let unchanged = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + d.setup.outline_images = true; + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "Show Images in Outline Mode filters the content again"); + assert!(pixels != unchanged, "Show Images in Outline Mode changes the image through the effect"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels, "Show Images in Outline Mode draws as a new renderer does"); +} + +/// A new guide color or style, or turning the Layer Options' screen look on or off, filters the +/// whole-object raster of a layer with effects that holds a guide and a sublayer with Preview +/// off again after a pan by whole pixels. +#[test] +fn guide_style_and_layer_options_filter_the_whole_object_raster_again_after_a_pan() { + let mut d = Document::new(100.0, 100.0); + let l = d.layers[0].id; + let mut square = + |r: Rect, c: Color| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(r), Appearance::basic(Paint::solid(c), Paint::None, 0.0))); + let white = square(Rect::new(100.0, 100.0, 300.0, 250.0), Color::WHITE); + let black = square(Rect::new(200.0, 100.0, 300.0, 250.0), Color::BLACK); + let mut guide = Arc::unwrap_or_clone(square(Rect::new(150.0, 120.0, 290.0, 230.0), Color::BLACK)); + if let vectorcraft_doc::NodeKind::Path { guide: flag, .. } = &mut guide.kind { + *flag = true; + } + let mut outlined = Node::layer(d.alloc_id(), "Outlined", vectorcraft_doc::LayerColor::Preset(0)); + if let vectorcraft_doc::NodeKind::Layer { preview, children, .. } = &mut outlined.kind { + *preview = false; + children.push(black); + } + d.insert(Some(l), 0, Arc::unwrap_or_clone(white)).unwrap(); + d.insert(Some(l), 1, outlined).unwrap(); + d.insert(Some(l), 2, guide).unwrap(); + d.node_mut(l).unwrap().appearance.effects = + vec![Effect { id: "blur.radial".into(), params: json!({"amount": 1, "quality": "draft"}), visible: true }]; + let opts = RenderOptions { background: Some([255, 255, 255, 255]), guide: ([0, 200, 255], false), ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let changes = [ + (RenderOptions { guide: ([255, 0, 0], false), ..opts.clone() }, "a new guide color"), + (RenderOptions { guide: ([0, 200, 255], true), ..opts.clone() }, "dotted guides"), + (RenderOptions { dim_templates: false, ..opts.clone() }, "Layer Options turned off"), + ]; + let unchanged = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + for (changed, what) in changes { + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &changed).pixels; + assert!(fresh != unchanged, "{what} changes the effect's pixels"); + let pixels = r.render(&d, 1280, 800, view(40.0), &changed).pixels; + assert!(pixels == fresh, "{what} filters the content again"); + } +} + +/// Switching the render mode ([`crate::RenderOptions::precise`]) filters the whole-object raster +/// again after a pan by whole pixels. +#[test] +fn render_mode_filters_the_whole_object_raster_again_after_a_pan() { + let d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { precise: false, background: Some([255, 255, 255, 255]), ..Default::default() }; + let precise = RenderOptions { precise: true, ..opts.clone() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.pan.is_some(), "a raster of the whole object at a lower resolution"); + let image = kept.image.clone(); + let pixels = r.render(&d, 1280, 800, view(40.0), &precise).pixels; + assert!(!r.pixel_fx.values().any(|e| Arc::ptr_eq(&e.image, &image)), "the precise render mode filters the content again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view(40.0), &precise).pixels, "in the precise render mode"); +} + +/// Art and Type edge smoothing share a coverage threshold, but Type snaps glyphs to the pixel +/// grid: switching between them filters the whole-object raster of a group with type again after +/// a pan by whole pixels. +#[test] +fn anti_aliasing_mode_filters_the_whole_object_text_raster_again_after_a_pan() { + use vectorcraft_doc::NodeKind; + use vectorcraft_doc::text::{CharStyle, TextObject}; + + let _fonts = fonts_steady(); + let mut d = Document::new(100.0, 100.0); + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let style = CharStyle { font_family: "Source Sans 3".into(), size: 20.0, fill: Paint::solid(Color::BLACK), ..Default::default() }; + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(270.013, 180.017), "Hm", style)))); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(text)]); + group.appearance.effects = vec![Effect { id: "blur.radial".into(), params: json!({"amount": 1, "quality": "draft"}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + let art = RenderOptions { background: Some([255, 255, 255, 255]), anti_alias: crate::AntiAlias::Art, ..Default::default() }; + let snapped = RenderOptions { anti_alias: crate::AntiAlias::Type, ..art.clone() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-280.0, -175.0)); + with_fonts_unchanged(|| { + let unchanged = Renderer::new().render(&d, 1280, 800, view(40.0), &art).pixels; + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &snapped).pixels; + assert!(fresh != unchanged, "Art and Type anti-aliasing draw different text pixels"); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &art); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.k < 1.0 && kept.view.is_none(), "a raster of the whole object at a lower resolution"); + let pixels = r.render(&d, 1280, 800, view(40.0), &snapped).pixels; + assert!(pixels == fresh, "changing anti-aliasing mode filters the text again after a whole-pixel pan"); + }); +} + +/// A whole-object raster gives way to its view copy when the cache budget cannot hold both. +/// The same view draws the copy again without filtering the content. +#[test] +fn a_lower_resolution_whole_raster_keeps_its_view_copy_under_the_cache_budget() { + let d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((640.0, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view, &opts); + let _ = r.render(&d, 1280, 800, view, &opts); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.pan.is_some() && kept.k < 1.0, "the whole-object raster is kept at a lower resolution"); + let copy = kept.shown.as_ref().unwrap().1.clone(); + let budget = kept.bytes() - super::entries::raster_bytes(&kept.image); + r.trim_fx_rasters(budget); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.view.is_some() && kept.pan.is_none() && kept.shown.is_none(), "the entry holds only its view copy"); + assert_eq!(kept.k, 1.0); + assert!(Arc::ptr_eq(&kept.image, ©), "the copy replaces the whole-object raster"); + let pixels = r.render(&d, 1280, 800, view, &opts).pixels; + assert!(Arc::ptr_eq(&r.pixel_fx.values().next().unwrap().image, ©), "the same view draws the copy without filtering again"); + assert!(pixels == Renderer::new().render(&d, 1280, 800, view, &opts).pixels, "the copy draws the same pixels as a new renderer"); +} + +/// An older shadow gives way before the newest whole-object raster loses its whole image. +#[test] +fn an_older_shadow_is_evicted_before_the_newest_whole_raster_loses_its_whole_image() { + let shadow_fx = ("stylize.dropShadow", json!({"x": 4, "y": 3, "blur": 2, "opacity": 80})); + let shadow = doc_with(Rect::new(20.0, 20.0, 40.0, 40.0), Color::BLACK, vec![shadow_fx]); + let d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((640.0, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&shadow, 200, 200, Affine::scale(2.0), &opts); + assert_eq!(r.shadows.len(), 1, "the first frame keeps a shadow"); + let _ = r.render(&d, 1280, 800, view, &opts); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.pan.is_some() && kept.k < 1.0 && kept.shown.is_some(), "the whole raster holds its view copy"); + assert!(r.shadows.values().all(|e| e.stamp < kept.stamp), "the shadow is older than the whole raster"); + let image = kept.image.clone(); + let budget = kept.bytes(); + assert!(r.shadows.values().all(|e| e.bytes() > 0), "the shadow and the whole raster together exceed the budget"); + r.trim_fx_rasters(budget); + assert!(r.shadows.is_empty(), "the older shadow is evicted first"); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.pan.is_some() && kept.view.is_none(), "the newest raster stays whole"); + assert!(Arc::ptr_eq(&kept.image, &image), "the newest raster keeps its whole image"); + assert!(kept.shown.is_some(), "the newest raster keeps its view copy"); + assert!(kept.bytes() <= budget, "the remaining entry fits the budget"); +} + +/// An older whole raster and its view copy give way before a newer whole raster is reduced. A +/// frame's start holds the previous frame's rasters, so the test marks one of two rasters older. +#[test] +fn an_older_whole_raster_is_evicted_before_a_newer_whole_raster_is_reduced() { + let mut d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::BLACK, vec![("sketch.tornEdges", json!({}))]); + let next = doc_with(Rect::new(300.0, 100.0, 500.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let mut n = (**next.layers[0].children().unwrap().first().unwrap()).clone(); + n.id = d.alloc_id(); + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((640.0, 400.0)) * Affine::scale(64.0) * Affine::translate((-300.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view, &opts); + assert_eq!(r.pixel_fx.len(), 2, "the view shows both objects"); + assert!(r.pixel_fx.values().all(|e| e.pan.is_some() && e.shown.is_some()), "both whole rasters hold view copies"); + let older_stamp = r.stamp - 1; + if let Some(e) = r.pixel_fx.values_mut().next() { + e.stamp = older_stamp; + } + let old = r.pixel_fx.values().find(|e| e.stamp == older_stamp).unwrap(); + let kept = r.pixel_fx.values().find(|e| e.stamp > older_stamp).unwrap(); + let newest_stamp = kept.stamp; + let image = kept.image.clone(); + let copy = kept.shown.as_ref().unwrap().1.clone(); + let budget = kept.bytes(); + assert!(old.bytes() > super::entries::raster_bytes(&old.image), "reducing the older raster leaves the cache over budget"); + r.trim_fx_rasters(budget); + assert_eq!(r.pixel_fx.len(), 1, "the older entry is evicted"); + let kept = r.pixel_fx.values().next().unwrap(); + assert_eq!(kept.stamp, newest_stamp); + assert!(kept.pan.is_some() && kept.view.is_none(), "the newer raster stays whole"); + assert!(Arc::ptr_eq(&kept.image, &image), "the newer raster keeps its whole image"); + assert!(Arc::ptr_eq(&kept.shown.as_ref().unwrap().1, ©), "the newer raster keeps its view copy"); + assert!(kept.bytes() <= budget, "the remaining entry fits the budget"); +} + +/// A whole raster is reduced before a shadow drawn in the same frame is evicted. +#[test] +fn a_whole_raster_is_reduced_before_a_shadow_of_the_same_stamp_is_evicted() { + let shadow_fx = ("stylize.dropShadow", json!({"x": 0.25, "y": 0.25, "blur": 0.5, "opacity": 80})); + let shadow = doc_with(Rect::new(292.0, 174.0, 293.0, 175.0), Color::BLACK, vec![shadow_fx]); + let mut d = doc_with(Rect::new(100.0, 100.0, 300.0, 250.0), Color::rgb(0.9, 0.4, 0.1), vec![("sketch.tornEdges", json!({}))]); + let mut n = (**shadow.layers[0].children().unwrap().first().unwrap()).clone(); + n.id = d.alloc_id(); + d.insert(Some(d.layers[0].id), 0, n).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() }; + let view = Affine::translate((640.0, 400.0)) * Affine::scale(64.0) * Affine::translate((-295.0, -175.0)); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view, &opts); + assert_eq!(r.shadows.len(), 1); + assert_eq!(r.pixel_fx.len(), 1); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.pan.is_some() && kept.shown.is_some(), "the whole raster holds its view copy"); + let shadow = r.shadows.values().next().unwrap(); + assert_eq!(shadow.stamp, kept.stamp, "both effects are drawn in the same frame"); + let copy = kept.shown.as_ref().unwrap().1.clone(); + let budget = shadow.bytes() + kept.bytes() - super::entries::raster_bytes(&kept.image); + assert!(shadow.bytes() > 0, "the shadow occupies cache space"); + r.trim_fx_rasters(budget); + assert_eq!(r.shadows.len(), 1, "the shadow stays cached"); + assert_eq!(r.pixel_fx.len(), 1, "the reduced raster stays cached"); + let kept = r.pixel_fx.values().next().unwrap(); + assert!(kept.view.is_some() && kept.pan.is_none() && kept.shown.is_none(), "the entry holds only its view copy"); + assert_eq!(kept.k, 1.0); + assert!(Arc::ptr_eq(&kept.image, ©), "the copy replaces the whole raster"); + assert!(kept.bytes() + r.shadows.values().map(|e| e.bytes()).sum::() <= budget, "both entries fit the budget"); +} + #[test] fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() { let doc = doc_with( diff --git a/crates/render/src/pattern.rs b/crates/render/src/pattern.rs index 75d783e8a8..bc8423a2e5 100644 --- a/crates/render/src/pattern.rs +++ b/crates/render/src/pattern.rs @@ -201,6 +201,7 @@ fn rasterize_as( // A tile drawn for a proof that preserves the colors' numbers shows its images through that // proof too. let plates = crate::proof::ink_plate_lut(ink, doc); + let hidden_inputs = Frame::hidden_inputs(&opts); for o in def.offsets_covering(region) { let v = view * def.instance_xf(o); let frame = Frame { @@ -212,6 +213,7 @@ fn rasterize_as( visible: v.inverse().transform_rect_bbox(px_rect), px: 1.0 / v.determinant().abs().sqrt().max(1e-12), opts: &opts, + hidden_inputs, ink, output: v, plates: plates.as_deref(), diff --git a/crates/render/src/placed_document.rs b/crates/render/src/placed_document.rs index fab8122af4..ec0d55ac48 100644 --- a/crates/render/src/placed_document.rs +++ b/crates/render/src/placed_document.rs @@ -550,6 +550,11 @@ fn mean_scale(a: Affine) -> f64 { a.determinant().abs().sqrt() } +/// Whether frame `f` allows placed documents to draw from progressive bitmaps. +pub(crate) fn progressive_bitmaps(f: &Frame) -> bool { + f.opts.progressive_placed && f.ink == Ink::Display && !f.opts.outline && f.opts.proof.is_none() && !f.opts.overprint_preview +} + impl Renderer { /// Draw placed document `p` in frame `f`: from a cached bitmap on screen, else exactly; in /// Outline mode without Document Setup → Show Images in Outline Mode, its box crossed from @@ -558,8 +563,7 @@ impl Renderer { if self.crosses_placed(f) { return self.draw_crossed_placed(ctx, f, p); } - let plain = f.ink == Ink::Display && !f.opts.outline && f.opts.proof.is_none() && !f.opts.overprint_preview; - if f.opts.progressive_placed && plain && depth() == 0 && self.draw_placed_bitmap(ctx, f, p) { + if progressive_bitmaps(f) && depth() == 0 && self.draw_placed_bitmap(ctx, f, p) { return; } let Some(blob) = f.doc.images.get(&p.key) else { return }; diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index c2a10b37a4..692d7d3fbc 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -225,7 +225,21 @@ impl Renderer { let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; let plates = proof::plate_lut(opts, doc); - let frame = Frame { mt: threads > 0, patch, doc, symbols: &symbols, view, visible, px, opts, ink: screen, output, plates: plates.as_deref() }; + let hidden_inputs = Frame::hidden_inputs(opts); + let frame = Frame { + mt: threads > 0, + patch, + doc, + symbols: &symbols, + view, + visible, + px, + opts, + hidden_inputs, + ink: screen, + output, + plates: plates.as_deref(), + }; let _crossed = self.cross_placed(&frame); self.begin_frame(); // View Opacity Mask: the mask's coverage in greyscale instead of the artwork. @@ -549,7 +563,9 @@ impl Renderer { ctx.set_aliasing_threshold(opts.anti_alias.threshold()); let symbols = doc.symbol_boxes().quick(); let output = Affine::scale(1.0 / f64::from(cell.max(1))) * view; - let frame = Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, ink: Ink::Display, output, plates: None }; + let hidden_inputs = Frame::hidden_inputs(opts); + let frame = + Frame { mt: false, patch: None, doc, symbols: &symbols, view, visible, px, opts, hidden_inputs, ink: Ink::Display, output, plates: None }; let raster = std::mem::replace(&mut self.raster, raster_settings(opts)); let _crossed = self.cross_placed(&frame); self.begin_frame(); diff --git a/crates/render/src/tests/bitmapglyphs.rs b/crates/render/src/tests/bitmapglyphs.rs index d1a96458ae..ebe7756623 100644 --- a/crates/render/src/tests/bitmapglyphs.rs +++ b/crates/render/src/tests/bitmapglyphs.rs @@ -98,6 +98,7 @@ fn rasters_of_type_follow_image_smoothing() { visible: vectorcraft_geom::Rect::new(0.0, 0.0, 160.0, 160.0), px: 1.0, opts: &opts, + hidden_inputs: Frame::hidden_inputs(&opts), ink: crate::ink::Ink::Display, output: Affine::IDENTITY, plates: None, diff --git a/crates/render/src/tests/placed_document.rs b/crates/render/src/tests/placed_document.rs index d7606f3094..57340de555 100644 --- a/crates/render/src/tests/placed_document.rs +++ b/crates/render/src/tests/placed_document.rs @@ -575,6 +575,128 @@ fn on_screen_a_placed_document_shows_a_placeholder_then_its_bitmap() { } } +/// A group with a whole-object effect drawn while its placed document showed a placeholder +/// filters its content again with the bitmap after a pan by whole pixels. +#[test] +fn a_ready_placed_bitmap_filters_the_whole_object_raster_again_after_a_pan() { + let _serial = serial(); + vectorcraft_doc::placed_document::set_loader(gated_blue_page); + let mut d = Document::new(100.0, 100.0); + let key = "whole-object-preview-1"; + d.images.insert(key.into(), ImageBlob::new("application/json", b"blue whole-object preview".to_vec())); + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let placed = placed_node(d.alloc_id().0, key, 40.0, 20.0, Affine::translate((280.0, 170.0)) * Affine::scale(0.5)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(placed)]); + group.appearance.effects = + vec![vectorcraft_doc::Effect { id: "blur.radial".into(), params: serde_json::json!({"amount": 1, "quality": "draft"}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-290.0, -175.0)); + let gate = shut_gate(); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let image = &r.pixel_fx.values().next().unwrap().image; + assert!( + image.width() > 1280 && image.height() > 800 && f64::from(image.width()) < 200.0 * 64.0, + "the group keeps a lower-resolution whole-object effect raster" + ); + let placeholder = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + drop(gate); + settle(); + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(fresh != placeholder, "the ready placed bitmap changes the effect's pixels"); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(pixels == fresh, "a ready placed bitmap filters the content again after a whole-pixel pan"); +} + +/// A group with a whole-object effect that holds a placed document's placeholder filters its +/// content again when Overprint Preview turns on and the view pans by whole pixels before the +/// bitmap is ready. +#[test] +fn overprint_preview_filters_the_whole_object_raster_again_after_a_pan() { + let _serial = serial(); + vectorcraft_doc::placed_document::set_loader(gated_blue_page); + let mut d = Document::new(100.0, 100.0); + let key = "whole-object-overprint-preview-1"; + d.images.insert(key.into(), ImageBlob::new("application/json", b"blue whole-object overprint preview".to_vec())); + let white = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 250.0)), + Appearance::basic(Paint::solid(Color::WHITE), Paint::None, 0.0), + ); + let placed = placed_node(d.alloc_id().0, key, 40.0, 20.0, Affine::translate((280.0, 170.0)) * Affine::scale(0.5)); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(white), Arc::new(placed)]); + group.appearance.effects = + vec![vectorcraft_doc::Effect { id: "blur.radial".into(), params: serde_json::json!({"amount": 1, "quality": "draft"}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, ..Default::default() }; + let view = |dx: f64| Affine::translate((640.0 + dx, 400.0)) * Affine::scale(64.0) * Affine::translate((-290.0, -175.0)); + let gate = shut_gate(); + let mut r = Renderer::new(); + let _ = r.render(&d, 1280, 800, view(0.0), &opts); + let placeholder = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + let opts = RenderOptions { overprint_preview: true, ..opts }; + let fresh = Renderer::new().render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(fresh != placeholder, "Overprint Preview draws the placed art before its bitmap is ready"); + let pixels = r.render(&d, 1280, 800, view(40.0), &opts).pixels; + assert!(pixels == fresh, "Overprint Preview filters the content again after a whole-pixel pan"); + drop(gate); + settle(); +} + +/// A group with a whole-object effect that holds only an ordinary image keeps its raster after a +/// placed document's bitmap in another document is ready and the view pans by whole pixels. +#[test] +fn an_ordinary_image_keeps_its_whole_object_raster_when_a_placed_bitmap_elsewhere_is_ready() { + let _serial = serial(); + let elsewhere = doc("ordinary-image-unrelated-preview-1"); + let mut d = Document::new(100.0, 100.0); + let raw = [0u8, 0, 255, 255].repeat(40 * 20); + let blue = craft_image_codecs::Image::from_raw(40, 20, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).unwrap(); + let png = craft_image_codecs::encode(&blue, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + let key = "whole-object-ordinary-image-1"; + d.images.insert(key.into(), ImageBlob::new("image/png", png.to_vec())); + let image = vectorcraft_doc::ImageObject { + key: key.into(), + width: 40, + height: 20, + xf: Affine::translate((10.0, 10.0)) * Affine::scale(2.0), + link: None, + placement: Default::default(), + pixels: None, + }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(image))); + let mut group = Node::group(d.alloc_id(), vec![Arc::new(image)]); + group.appearance.effects = + vec![vectorcraft_doc::Effect { id: "blur.radial".into(), params: serde_json::json!({"amount": 1, "quality": "draft"}), visible: true }]; + let l = d.layers[0].id; + d.insert(Some(l), 0, group).unwrap(); + let opts = RenderOptions { background: Some([255, 255, 255, 255]), progressive_placed: true, ..Default::default() }; + let gate = shut_gate(); + let mut r = Renderer::new(); + let _ = r.render(&d, 100, 100, Affine::IDENTITY, &opts); + let kept = r.pixel_fx.values().next().unwrap().image.clone(); + let _ = r.render(&d, 100, 100, Affine::translate((8.0, 0.0)), &opts); + assert!(Arc::ptr_eq(&kept, &r.pixel_fx.values().next().unwrap().image), "a whole-pixel pan keeps the ordinary image's effect raster"); + let generation = placed_document::generation(); + render(&elsewhere, true); + assert!(placed_document::pending_for("ordinary-image-unrelated-preview-1"), "the unrelated placed bitmap waits for the gate"); + drop(gate); + settle(); + assert!(placed_document::generation() > generation, "the unrelated placed bitmap becomes ready"); + let _ = r.render(&d, 100, 100, Affine::translate((16.0, 0.0)), &opts); + assert!( + Arc::ptr_eq(&kept, &r.pixel_fx.values().next().unwrap().image), + "an unrelated ready placed bitmap preserves the ordinary image's effect raster after a whole-pixel pan" + ); +} + #[test] fn a_bitmap_that_panics_while_made_on_the_drawing_thread_stops_being_pending() { let _serial = serial();