Merge main into fix/monitor-work-area-placement

DesktopWindows now passes the pointer, button, text and warp calls to
windows_stylus::ContactWindows, so a pen or a finger in contact still
counts as the primary button with the monitor listing in place.
This commit is contained in:
dotCooCoo committed 2026-12-05 15:45:04 -08:00
commit 01f331fe8c
27 files changed
+2923 -111

No files matched your search

+1
View File
@@ -885,6 +885,7 @@ fn main() -> std::process::ExitCode {
if let Some(window) = &winit_window {
restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland);
}
// 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)))
+10 -7
View File
@@ -6,9 +6,11 @@ use std::sync::{Arc, Mutex, PoisonError, Weak};
use std::time::{Duration, Instant};
use craft::behavior::{Monitor, MonitorKey};
use craft::window::system::{HeldButtons, SystemWindows, WindowSystem};
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);
@@ -67,7 +69,8 @@ fn from_edges(left: i32, top: i32, right: i32, bottom: i32) -> Option<([i32; 2],
Some(([left, top], [width, height]))
}
/// The platform's window services, with the monitors listed through winit. On macOS no monitors are listed: winit
/// 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`]).
@@ -93,23 +96,23 @@ impl DesktopWindows {
impl WindowSystem for DesktopWindows {
fn desktop_pointer(&self) -> Option<[f32; 2]> {
SystemWindows.desktop_pointer()
ContactWindows.desktop_pointer()
}
fn buttons_held(&self) -> Option<HeldButtons> {
SystemWindows.buttons_held()
ContactWindows.buttons_held()
}
fn discard_marked_text(&self) -> bool {
SystemWindows.discard_marked_text()
ContactWindows.discard_marked_text()
}
fn command_held(&self) -> Option<bool> {
SystemWindows.command_held()
ContactWindows.command_held()
}
fn warp_pointer(&self, to: [f32; 2]) -> bool {
SystemWindows.warp_pointer(to)
ContactWindows.warp_pointer(to)
}
/// The monitors of the last listing, listed again once [`RELIST_AFTER`] has passed. A listing that fails keeps
+167 -5
View File
@@ -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<PenSource> = OnceLock::new();
/// The ids of the pointers in contact (pens and fingers), from [`msg_hook`].
static CONTACTS: Mutex<Vec<u32>> = 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<HeldButtons> {
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<bool> {
SystemWindows.command_held()
}
fn warp_pointer(&self, to: [f32; 2]) -> bool {
SystemWindows.warp_pointer(to)
}
fn monitors(&self) -> Vec<Monitor> {
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<HeldButtons>, in_contact: bool) -> Option<HeldButtons> {
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<u32>, 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::<MSG>().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<u32>) -> 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<u32>, 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");
+11 -3
View File
@@ -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, <https://learn.microsoft.com/en-us/windows/win32/winmsg/wm-activateapp>)
/// closes the context ([`deactivate`]), and a pen's `WM_POINTERENTER` and `WM_POINTERLEAVE`
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/wm-pointerleave>) go to
/// closes the context ([`deactivate`]), and a pointer's `WM_POINTERENTER`, `WM_POINTERLEAVE`
/// (<https://learn.microsoft.com/en-us/windows/win32/inputmsg/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 (<https://learn.microsoft.com/en-us/windows/win32/winmsg/callwndproc>).
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 {
@@ -63,6 +63,7 @@ pub(crate) fn silent(s: &mut Session, f: impl FnOnce(&mut PerspectiveGrid)) -> R
store_grid(Arc::make_mut(&mut st.doc), &g);
if let Some(it) = &mut st.interaction {
store_grid(Arc::make_mut(&mut it.doc), &g);
it.revision = st.revision + 1;
}
st.revision += 1;
Ok(g)
@@ -745,6 +746,7 @@ pub(crate) fn finish_edit_text(st: &mut crate::DocState, id: NodeId) {
}
if let Some(it) = &mut st.interaction {
clear(&mut it.doc);
it.revision = st.revision + 1;
}
st.revision += 1;
}
+5
View File
@@ -7,6 +7,11 @@ use vectorcraft_geom::Rect;
use crate::Session;
/// The new-art paint state before the running preview, or its current value without a preview.
pub fn new_art_paint_before_preview(s: &Session) -> &vectorcraft_tools::PaintDefaults {
s.active().and_then(|st| st.interaction.as_ref()).map_or(&s.paint, |it| &it.paint)
}
pub(crate) fn rect_json(r: Option<vectorcraft_geom::Rect>) -> Value {
match r {
Some(r) => json!({ "x": r.x0, "y": r.y0, "width": r.width(), "height": r.height() }),
+2 -2
View File
@@ -11,8 +11,8 @@ pub struct Interaction {
/// The selection the previews start from (shared, so a preview frame copies nothing).
pub selection: Arc<Selection>,
pub(crate) active_appearance_item: Option<PreviewAppearanceItem>,
/// The document's [`crate::DocState::revision`] when the interaction began. The previews change the document's
/// revision, and this value stays the same until the interaction ends.
/// The baseline document's [`crate::DocState::revision`]. Previews keep this value; replacing or changing the
/// baseline advances it to the document's next revision.
pub revision: u64,
pub preview: Option<(String, Value)>,
/// The active tool began it (a drag): a command from outside the tool runs as a step of its
+48
View File
@@ -68,6 +68,53 @@ type Recipient = (String, String, u64);
#[cfg(test)]
std::thread_local! {
pub(crate) static RECIPIENT_IDENTITIES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
/// How many [`EventPluginsHeld`] this thread holds.
static EVENT_PLUGINS_HELD: std::cell::Cell<usize> = 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<Option<std::thread::ThreadId>> = 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();
+2
View File
@@ -522,6 +522,8 @@ impl Session {
return;
}
let began = std::mem::replace(&mut it.doc, st.doc.clone());
st.revision += 1;
it.revision = st.revision;
// The drag acts on the objects it began with: a selection the command made (a paste, a
// duplicate, Select All) does not change what the drag moves. A dialog's preview acts on
// the selection the command left, and its dialog previews again on its next pass, from the
@@ -846,3 +846,58 @@ fn a_command_during_a_quick_pen_press_runs_inside_it() {
assert_eq!(s.doc().unwrap().history.undo.len(), steps, "{at}: no step of its own during the press");
}
}
#[test]
fn a_rebased_drag_advances_its_baseline_revision() {
for real_time in [true, false] {
let (mut s, _, other) = two_squares(real_time);
s.select_tool("selection", view()).unwrap();
pointer(&mut s, PointerKind::Down, 120.0, 120.0);
pointer(&mut s, PointerKind::Drag, 140.0, 130.0);
let revision = s.doc().unwrap().interaction.as_ref().unwrap().revision;
pointer(&mut s, PointerKind::Drag, 150.0, 140.0);
assert_eq!(s.doc().unwrap().interaction.as_ref().unwrap().revision, revision, "previews keep the baseline revision");
s.execute("appearance.setItem", &json!({"ids": [other.0], "index": 1, "weight": 3})).unwrap();
let rebased = s.doc().unwrap().interaction.as_ref().unwrap().revision;
assert!(rebased > revision, "an outside document edit advances the baseline revision");
pointer(&mut s, PointerKind::Drag, 160.0, 150.0);
assert_eq!(s.doc().unwrap().interaction.as_ref().unwrap().revision, rebased, "later previews keep the rebased revision");
s.cancel_interaction().unwrap();
assert_eq!(s.doc().unwrap().doc.node(other).unwrap().appearance.stroke().unwrap().width, 3.0);
}
}
#[test]
fn a_grid_change_during_an_interaction_advances_its_baseline_revision() {
let (mut s, _) = session(true);
s.begin_interaction("Grid").unwrap();
let revision = s.doc().unwrap().interaction.as_ref().unwrap().revision;
crate::cmd::distortcmds::silent(&mut s, |grid| grid.visible = !grid.visible).unwrap();
let st = s.doc().unwrap();
let it = st.interaction.as_ref().unwrap();
assert!(it.revision > revision, "a direct baseline change advances its revision");
assert_eq!(crate::cmd::distortcmds::grid_of(&it.doc).visible, crate::cmd::distortcmds::grid_of(&st.doc).visible);
}
#[test]
fn leaving_perspective_type_editing_during_an_interaction_advances_its_baseline_revision() {
let (mut s, _) = crate::tests_persp_select::persp_session();
let r = s.execute("text.create", &json!({"x": 430, "y": 400, "text": "HELLO", "size": 48})).unwrap();
let id = NodeId(r["id"].as_u64().unwrap());
s.execute("perspective.attach", &json!({"ids": [id.0], "plane": "right"})).unwrap();
s.execute("perspective.editText", &json!({"id": id.0})).unwrap();
s.begin_interaction("Edit").unwrap();
let it = s.doc().unwrap().interaction.as_ref().unwrap();
let revision = it.revision;
let text = it.doc.node(id).unwrap();
assert!(text.extras().perspective.as_deref().unwrap().editing, "the baseline starts in Edit Text mode");
assert!(text.projection().is_none(), "the baseline text is flat while editing");
crate::cmd::distortcmds::finish_edit_text(s.doc_mut().unwrap(), id);
let st = s.doc().unwrap();
let it = st.interaction.as_ref().unwrap();
let text = it.doc.node(id).unwrap();
assert!(!text.extras().perspective.as_deref().unwrap().editing, "the baseline leaves Edit Text mode");
assert!(text.projection().is_some(), "the baseline text is projected again");
assert!(it.revision > revision, "leaving Edit Text advances the baseline revision");
assert_eq!(it.revision, st.revision, "the baseline revision is the document's new revision");
}
+24 -3
View File
@@ -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 {
+1 -1
View File
@@ -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();
+9
View File
@@ -61,6 +61,8 @@ pub(crate) struct BrushCache {
/// (frame stamp, document address) the library was last validated for.
checked: (u64, usize),
lib: HashMap<String, Arc<Brush>>,
/// 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<Node>)>,
@@ -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 {
+13
View File
@@ -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);
+32 -11
View File
@@ -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<Item = &'a Node>) -> 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());
+177 -50
View File
@@ -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<vello_cpu::Pixmap>, (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::<usize>() + self.pixel_fx.values().map(|e| e.bytes()).sum::<usize>();
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;
}
}
+40 -6
View File
@@ -90,16 +90,32 @@ pub(crate) struct PixelEntry {
pub(super) rel: (f64, f64),
pub(super) k: f64,
pub(crate) image: std::sync::Arc<vello_cpu::Pixmap>,
/// 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<ViewCrop>,
/// 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<Rect>,
/// 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<vello_cpu::Pixmap>, (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
+1
View File
@@ -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,
+775
View File
@@ -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<vello_cpu::Pixmap>| 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, &copy(&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<vello_cpu::Pixmap>| 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, &copy), "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, &copy), "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, &copy), "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, &copy), "the copy replaces the whole raster");
assert!(kept.bytes() + r.shadows.values().map(|e| e.bytes()).sum::<usize>() <= budget, "both entries fit the budget");
}
#[test]
fn a_drag_glow_fallback_cannot_be_spliced_into_a_still_frame() {
let doc = doc_with(
+2
View File
@@ -201,6 +201,7 @@ fn rasterize_as<T>(
// 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<T>(
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(),
+6 -2
View File
@@ -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 };
+18 -2
View File
@@ -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();
+1
View File
@@ -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,
+122
View File
@@ -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();
+9 -4
View File
@@ -452,9 +452,11 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let copy = craft::ui::runtime::pointer::frame(ui.ctx()).mods.alt;
let pass = RefCell::new(Pass::default());
let footer = RefCell::new(None);
let shown_target = stroke::target_key(&stroke::edit_target(app, ui.ctx()));
let shared: &VectorcraftApp = app;
let cx = RowCx {
app: shared,
shown_target,
node: node.as_deref(),
new_art: &new_art,
mix,
@@ -751,6 +753,7 @@ struct Pass {
/// What a row reads to build itself.
struct RowCx<'a> {
app: &'a VectorcraftApp,
shown_target: u64,
node: Option<&'a Node>,
new_art: &'a Appearance,
mix: Option<&'a Mixed>,
@@ -860,10 +863,12 @@ fn item_row<'r>(cx: &'r RowCx<'_>, key: RowKey, i: usize) -> ListRow<'r> {
}
if let Some(st) = stroke_layer {
let target = if new_art { WeightTarget::Shown } else { WeightTarget::Item(i) };
let field =
if new_art { row_weight(cx.app, Some(st.width), &cx.shown_target) } else { row_weight(cx.app, Some(st.width), &(cx.shown_target, i)) };
let pass = cx.pass;
row = row.trailing_field(row_weight(cx.app, Some(st.width)), move |out| pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out))));
row = row.trailing_field(field, move |out| pass.borrow_mut().acts.push(Act::Weight(target, Box::new(out))));
} else {
row = row.trailing_space(row_weight(cx.app, None));
row = row.trailing_space(row_weight(cx.app, None, &()));
}
let painted = if new_art { Painted::NewArt { fill } } else { Painted::Item(i) };
let pass = cx.pass;
@@ -894,8 +899,8 @@ fn paint_swatch(fill: bool, paint: &Paint) -> Swatch {
/// The weight field of a stroke row, or the room it takes in a fill row: the Stroke panel's field as a small control,
/// as the row's swatch is, without the presets list (a step still stops at each preset), so the row's label shows
/// whole in the narrowest group.
fn row_weight(app: &VectorcraftApp, weight: Option<f64>) -> NumberField<'static> {
stroke::steps_weight(app, weight).size(ControlSize::Sm)
fn row_weight(app: &VectorcraftApp, weight: Option<f64>, target: &impl egui::AsIdSalt) -> NumberField<'static> {
stroke::steps_weight(app, weight, target).size(ControlSize::Sm)
}
/// A stroke row's notes after the weight: its brush and "Dashed".
+234 -14
View File
@@ -3,6 +3,7 @@
// PLAN: import paths of craft_ui / craft_draw items are assumed from the crates' own module layout (craft_draw is
// not yet a dependency of ui-egui; its owner adds it to Cargo.toml).
use std::hash::{DefaultHasher, Hash, Hasher};
use std::sync::LazyLock;
mod profile_picker;
@@ -32,7 +33,9 @@ use craft::ui::text::{NumberField, NumberOutput, NumberPick, StepArrows};
use egui::{Rect, Response, Ui, pos2};
use serde_json::{Value, json};
use vectorcraft_color::{Color, Paint};
use vectorcraft_doc::{Appearance, ArrowAlign, Arrowhead, Dash, Document, LineCap, LineJoin, Node, StrokeAlign, StrokeLayer, Unit, WidthProfile};
use vectorcraft_doc::{
Appearance, ArrowAlign, Arrowhead, Dash, Document, LineCap, LineJoin, Node, NodeId, StrokeAlign, StrokeLayer, Unit, WidthProfile,
};
use vectorcraft_engine::inspect::StrokeMixed;
use vectorcraft_tools::PaintDefaults;
@@ -50,6 +53,15 @@ const ARROWHEAD_ASPECT: (u16, u16) = (2, 1);
/// The key of [`StrokePanel::brushed`]: (document uid, revision, active Appearance row).
type BrushedKey = (u64, u64, Option<usize>);
#[derive(Clone, Debug, Default)]
struct FieldGesture {
held: Option<(EditTarget, EditTarget)>,
serial: u64,
}
/// Global Edit members in propagation order, with the transforms that place each member.
type GlobalEditTarget = Option<Vec<(NodeId, [u64; 6])>>;
/// What the Stroke panel remembers between frames; `UiState::stroke_panel` holds it.
#[derive(Clone, Debug, Default)]
pub(crate) struct StrokePanel {
@@ -63,6 +75,10 @@ pub(crate) struct StrokePanel {
pub brushed: Option<(BrushedKey, Option<bool>)>,
/// The running gesture of a Stroke panel select.
pub select_gesture: Option<SelectGesture>,
/// The editor gesture's starting target and targeting state.
editor_gesture: FieldGesture,
/// The arrow scale gesture's starting target and targeting state.
scale_gesture: FieldGesture,
}
/// The stroke a weight edit goes to.
@@ -394,22 +410,125 @@ static BLANK_WEIGHT_STOPS: [f64; 2] = [0.25, 0.5];
/// scrubbing by its label, blank when mixed. A plain step stops at each preset (0.52 pt goes down to 0.5 pt, not to
/// 0 pt); Shift or Page steps the grid by ten.
// PLAN: the sheet names `NumberField<'static, f64>`; `NumberField::length` takes `Option<f64>`.
pub(crate) fn weight_number(app: &VectorcraftApp, weight: Option<f64>) -> NumberField<'static> {
let field = steps_weight(app, weight);
pub(crate) fn weight_number(app: &VectorcraftApp, weight: Option<f64>, target: &EditTarget) -> NumberField<'static> {
let field = steps_weight(app, weight, target);
match weight_ladder(app) {
Some(l) => field.presets(&l.rows),
None => field,
}
}
/// The document edit state and session destination before a preview.
/// A field drops its unfinished value when either changes.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub(crate) struct Target {
/// The document.
doc: u64,
/// How many times File > Revert replaced the document's content.
reverts: u64,
/// The revision of the document that the next preview builds on.
revision: u64,
/// The pre-preview new-art paint state.
new_art: u64,
/// Whether new art uses a basic appearance.
new_art_basic: bool,
/// The selected objects and subjects, in targeting order.
objects: Vec<NodeId>,
subjects: Vec<NodeId>,
/// The active appearance row.
row: Option<usize>,
/// The selected object inside a dynamic symbol instance: its instance and path through the symbol's art.
symbol_part: Option<(NodeId, Vec<u32>)>,
/// Whether the Live Paint Bucket's stroke is edited.
bucket: bool,
/// The type object and characters the Type tool has selected.
characters: Option<(NodeId, usize, usize)>,
/// The frame ids in thread order when the Type tool has selected the whole story.
story: Option<Vec<NodeId>>,
/// The members and placement transforms used to propagate Global Edit changes.
global_edit: GlobalEditTarget,
/// Distinguishes a canceled gesture from a replacement with the same starting content.
gesture: u64,
}
/// The edit target of the Stroke panel's fields, `None` without a document.
pub(crate) type EditTarget = Option<Target>;
/// The [`EditTarget`] of the active document.
pub(crate) fn edit_target(app: &VectorcraftApp, _ctx: &egui::Context) -> EditTarget {
let st = app.session.active()?;
Some(Target {
doc: st.uid,
reverts: st.reverts,
revision: st.interaction.as_ref().map_or(st.revision, |it| it.revision),
new_art: if may_edit_new_art(app) {
paint_digest(vectorcraft_engine::inspect::new_art_paint_before_preview(&app.session))
} else {
vectorcraft_engine::inspect::new_art_paint_before_preview(&app.session).stroke_width.to_bits()
},
new_art_basic: app.session.prefs.new_art_basic,
objects: st.selection.objects.clone(),
subjects: st.selection.subjects().to_vec(),
row: app.session.appearance_item(),
symbol_part: st.selection.symbol_part.as_ref().map(|part| (part.instance, part.path.clone())),
bucket: app.session.tool_paints(true),
characters: character::text_editing(app),
story: character::text_story(app),
global_edit: st.global_edit.as_ref().map(|ge| ge.members.iter().map(|(id, xf)| (*id, xf.as_coeffs().map(f64::to_bits))).collect()),
gesture: 0,
})
}
pub(crate) fn target_key(target: &EditTarget) -> u64 {
let mut hasher = DefaultHasher::new();
target.hash(&mut hasher);
hasher.finish()
}
/// Whether the fields can edit the new-art paint. A selected path the Stroke panel edits directly
/// (not a guide, a clipping path or a Live Paint part) is always a target, so with one selected
/// the fields edit objects and the target skips formatting the new-art paint.
fn may_edit_new_art(app: &VectorcraftApp) -> bool {
use vectorcraft_tools::builder::{SOURCES_NAME, is_live_paint};
let Some(st) = app.session.active() else { return true };
if app.session.tool_paints(true) {
return true;
}
let d = &st.doc;
let edited_path = |id: NodeId| {
d.node(id).is_some_and(|n| matches!(n.kind, vectorcraft_doc::NodeKind::Path { guide: false, clipping: false, .. }) && !n.is_ruler_guide())
&& d.parent_of(id).and_then(|p| d.node(p)).is_none_or(|p| !is_live_paint(p) && p.name.as_deref() != Some(SOURCES_NAME))
};
!st.selection.objects.iter().any(|id| edited_path(*id))
}
fn paint_digest(paint: &impl std::fmt::Debug) -> u64 {
use std::fmt::Write as _;
struct HashSink(DefaultHasher);
impl std::fmt::Write for HashSink {
fn write_str(&mut self, s: &str) -> std::fmt::Result {
self.0.write(s.as_bytes());
Ok(())
}
}
let mut sink = HashSink(DefaultHasher::new());
let _ = write!(sink, "{paint:?}");
sink.0.finish()
}
/// [`weight_number`] without the presets list: a plain step still stops at each preset.
pub(crate) fn steps_weight(app: &VectorcraftApp, weight: Option<f64>) -> NumberField<'static> {
pub(crate) fn steps_weight(app: &VectorcraftApp, weight: Option<f64>, target: &impl egui::AsIdSalt) -> NumberField<'static> {
let unit = app.session.stroke_unit();
let lengths =
crate::fields::bare_points(LengthUnits::new(UnitKind::Points, shown_kind(unit), 72.0), app.session.prefs.numbers_without_units_are_points);
let ladder = weight_ladder(app);
let field =
NumberField::length(tl!("Weight"), Bind::given(weight), lengths).range(0.0..=1000.0).step_arrows(StepArrows::Leading).scrub_by_label();
let field = NumberField::length(tl!("Weight"), Bind::given(weight), lengths)
.range(0.0..=1000.0)
.step_arrows(StepArrows::Leading)
.scrub_by_label()
.edit_target(target);
// The stepper steps the number the field shows; the ladders are in points.
let in_points = move |stops: &'static [f64], blank: bool| {
let step = crate::fields::stops_stepper(1.0, stops, move |pt| unit.format(pt));
@@ -452,8 +571,15 @@ pub(crate) fn apply_weight(app: &mut VectorcraftApp, out: &NumberOutput, target:
/// The weight field in a row labelled `label` with the side label `side`: the field response and the output of
/// the number field when the row's body ran.
fn weight_row(app: &VectorcraftApp, ui: &mut Ui, label: &'static str, side: SideLabel, weight: Option<f64>) -> Inner<Response, NumberOutput> {
Field::new(label).side(side).id_salt("weight").sizing(Sizing::Content).show(ui, |ui, _| weight_number(app, weight).show(ui))
fn weight_row(
app: &VectorcraftApp,
ui: &mut Ui,
label: &'static str,
side: SideLabel,
weight: Option<f64>,
target: &EditTarget,
) -> Inner<Response, NumberOutput> {
Field::new(label).side(side).id_salt("weight").sizing(Sizing::Content).show(ui, |ui, _| weight_number(app, weight, target).show(ui))
}
/// The weight field whose link side label (`label`: the Control bar's "Stroke:", the Properties panel's "Stroke")
@@ -461,7 +587,8 @@ fn weight_row(app: &VectorcraftApp, ui: &mut Ui, label: &'static str, side: Side
/// Weight: the label beside the Stroke chip says which paint it is the weight of.
pub(crate) fn link_field(app: &mut VectorcraftApp, ui: &mut Ui, label: &'static str, weight: Option<f64>) {
let side = SideLabel::new().scrub(true).link().role(FieldLabelRole::Describes).tooltip(TooltipSpec::new(tl!("Stroke options")));
let field = weight_row(app, ui, label, side, weight);
let target = edit_target(app, ui.ctx());
let field = weight_row(app, ui, label, side, weight, &target);
let open_id = field.output.id.with("stroke_popover_open");
let mut open = ui.data(|d| d.get_temp::<bool>(open_id).unwrap_or(false));
if let Some(out) = field.inner {
@@ -492,30 +619,66 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// Keeps a group's starting key while its own gesture runs in the same targeting state.
fn gesture_target(gesture: &mut FieldGesture, target: EditTarget) -> EditTarget {
let changed = gesture.held.as_ref().is_some_and(|(_, produced)| produced != &target);
if changed {
gesture.held = None;
gesture.serial = gesture.serial.wrapping_add(1);
}
let mut target = gesture.held.as_ref().map_or(target, |(target, _)| target.clone());
if let Some(target) = &mut target {
target.gesture = gesture.serial;
}
target
}
/// Keeps the starting target and the content produced after the component's edits are applied.
fn remember_gesture<T>(gesture: &mut FieldGesture, target: &EditTarget, events: &craft::behavior::EditEvents<T>, produced: EditTarget) {
for event in events.iter() {
match event {
EditEvent::Begin { .. } => gesture.held = Some((target.clone(), produced.clone())),
EditEvent::Commit { .. } | EditEvent::Cancel { .. } => gesture.held = None,
_ => {}
}
}
if let Some((_, last)) = &mut gesture.held {
*last = produced;
}
}
/// The rows of [`show`].
fn rows(app: &mut VectorcraftApp, ui: &mut Ui) {
let st = current_stroke(app);
let mixed = stroke_mixed(app, ui.ctx());
let weight = shown_weight(app, st.as_ref(), &mixed);
if let Some(out) = weight_row(app, ui, tl!("Weight"), SideLabel::new().scrub(true), weight).inner {
let mut target = edit_target(app, ui.ctx());
if let Some(out) = weight_row(app, ui, tl!("Weight"), SideLabel::new().scrub(true), weight, &target).inner {
apply_weight(app, &out, WeightTarget::Shown);
target = edit_target(app, ui.ctx());
}
if app.ui.stroke_panel.hide_options {
app.ui.stroke_panel.editor_gesture.held = None;
app.ui.stroke_panel.scale_gesture.held = None;
return;
}
let style = style_of(st.as_ref());
let editor_target = gesture_target(&mut app.ui.stroke_panel.editor_gesture, target.clone());
let editor = StrokeEditor::new(tl!("Stroke"), Bind::given(style.clone()))
.sections(StrokeSections::PANEL | StrokeSections::DASH_ALIGN)
.closed(mixed.can_align)
.caps_on_closed(true)
.mixed(&mixed_of(&mixed))
.host_labels(true);
.host_labels(true)
.edit_target(&editor_target);
let output = editor.show(ui);
if let (Some(new), Some(field)) = (output.events.landed(), output.field) {
apply_style(app, &style, new.clone(), field);
target = edit_target(app, ui.ctx());
}
remember_gesture(&mut app.ui.stroke_panel.editor_gesture, &editor_target, &output.events, target.clone());
Divider::horizontal().show(ui);
arrow_rows(app, ui, st.as_ref());
arrow_rows(app, ui, st.as_ref(), target);
Divider::horizontal().show(ui);
Field::new(tl!("Profile")).show(ui, |ui, _| {
Row::new().wrap(true).show(ui, |ui, _| {
@@ -525,8 +688,11 @@ fn rows(app: &mut VectorcraftApp, ui: &mut Ui) {
});
}
/// The arrowhead rows: the start and end heads with Swap, the two scales with their link, and the alignment.
fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) {
/// The arrowhead rows: the start and end heads with Swap, the two scales with their link, and the alignment. `target`
/// is the current edit target used to track scale gestures.
fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>, target: EditTarget) {
let scale_target = gesture_target(&mut app.ui.stroke_panel.scale_gesture, target.clone());
let mut updated = false;
let custom: Vec<Arrowhead> = app.session.arrowheads.heads().iter().cloned().map(Arrowhead::Custom).collect();
let entries: Vec<Entry<Option<Arrowhead>>> = std::iter::once(None)
.chain(Arrowhead::ALL.iter().cloned().map(Some))
@@ -551,10 +717,12 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) {
let out = if listed { select } else { select.unlisted_label(unlisted_arrow_name(head.as_ref())) }.show(ui);
// A custom head goes with its art, as document.inspect reports it.
apply_select(app, key, &out, |app, a| set(app, json!({ key: a })));
updated |= out.events.iter().next().is_some();
}
let swap = IconButton::new(IconId::new("arrow-left-right")).label(tl!("Swap start and end arrowheads")).enabled(st.is_some()).show(ui);
if swap.clicked() {
app.run("stroke.setAdvanced", json!({"swapArrows": true})).ok();
updated = true;
}
});
});
@@ -568,6 +736,7 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) {
.mode(LinkMode::Equal)
.unit_kind(UnitKind::Percent)
.enabled(has_head)
.edit_target(&scale_target)
.show(ui)
})
.inner;
@@ -576,6 +745,13 @@ fn arrow_rows(app: &mut VectorcraftApp, ui: &mut Ui, st: Option<&StrokeLayer>) {
}
if let Some([a, b]) = out.as_ref().and_then(|out| out.edit.events.landed()).map(|p| (*p).map(|m| m.same().copied().flatten())) {
app.run("stroke.setAdvanced", json!({"arrowScale": [a.unwrap_or(scale.0), b.unwrap_or(scale.1)]})).ok();
updated = true;
}
if let Some(out) = &out {
let produced = if updated { edit_target(app, ui.ctx()) } else { target };
remember_gesture(&mut app.ui.stroke_panel.scale_gesture, &scale_target, &out.edit.events, produced);
} else {
app.ui.stroke_panel.scale_gesture.held = None;
}
let aligns: Vec<Entry<ArrowAlign>> = ARROW_ALIGN.iter().map(|(v, _, icon, tip)| Entry::new(*v, *tip).icon(IconId::new(icon))).collect();
let out = Field::new(tl!("Align"))
@@ -1021,6 +1197,15 @@ mod tests {
use super::*;
use crate::tests::panel_harness::Panel;
#[test]
fn paint_digest_tracks_stroke_width() {
let paint = PaintDefaults::default();
let mut changed = paint.clone();
assert_eq!(paint_digest(&paint), paint_digest(&changed));
changed.stroke_width += 1.0;
assert_ne!(paint_digest(&paint), paint_digest(&changed));
}
#[test]
fn editing_an_extended_dash_keeps_other_stroke_options_and_is_undoable() {
use vectorcraft_engine::Session;
@@ -1042,6 +1227,41 @@ mod tests {
assert_eq!(current_stroke(&app).unwrap(), after);
}
/// A field group's running gesture keeps the target it began with while its own edits change the stroke, and
/// takes the current target again once the gesture ends or the selection changes.
#[test]
fn a_gesture_keeps_its_starting_target_until_it_ends() {
let (mut app, path) = profiled_line(None);
let other = app.run("shape.line", json!({"x1": 10, "y1": 80, "x2": 90, "y2": 80})).unwrap();
app.run("select.set", json!({"ids": [path["id"]]})).unwrap();
let ctx = egui::Context::default();
let shown = |target: &EditTarget| format!("{target:?}");
let event = |e: EditEvent<f64>| craft::behavior::EditEvents::from(e);
let id = GestureId::new(1);
let mut gesture = FieldGesture::default();
let start = edit_target(&app, &ctx);
remember_gesture(&mut gesture, &start, &event(EditEvent::begin(id, Mixed::Same(10.0), std::sync::Arc::from("Miter"), None)), start.clone());
app.run("stroke.set", json!({"miterLimit": 22})).unwrap();
let fresh = edit_target(&app, &ctx);
assert_ne!(shown(&fresh), shown(&start), "the gesture's own edit changes the stroke's target");
remember_gesture(&mut gesture, &start, &craft::behavior::EditEvents::<f64>::new(), fresh.clone());
let held = gesture_target(&mut gesture, fresh.clone());
assert_eq!(shown(&held), shown(&start), "the running gesture keeps its starting target");
remember_gesture(&mut gesture, &held, &event(EditEvent::commit(id, Mixed::Same(10.0), 22.0)), fresh.clone());
let fresh = edit_target(&app, &ctx);
assert_eq!(shown(&gesture_target(&mut gesture, fresh)), shown(&edit_target(&app, &ctx)), "a commit ends it");
let start = edit_target(&app, &ctx);
remember_gesture(&mut gesture, &start, &event(EditEvent::begin(id, Mixed::Same(22.0), std::sync::Arc::from("Miter"), None)), start.clone());
app.run("select.set", json!({"ids": [other["id"]]})).unwrap();
let fresh = edit_target(&app, &ctx);
let now = gesture_target(&mut gesture, fresh);
assert_ne!(shown(&now), shown(&start), "another selection ends the held target");
assert!(gesture.held.is_none());
}
/// The Profile and arrowhead selects name a current value that is none of their choices on the closed face, and
/// the open list keeps only the choices.
#[test]
File diff suppressed because it is too large. Load diff