mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 21:12:57 -05:00
Pencil: the moves of one frame preview the stroke once
The canvas hands every pointer move of a frame to the freehand tools, and each move ran a full preview: the stroke was fitted again, inserted into the document and run through every post-edit pass, and the next move's preview threw it away. A pen or a fast mouse delivers several moves per frame, so drawing slowed down with both the move rate and the document size (#4343). - SessionTool keeps the drag samples of a pass and hands them, with the release when it comes in the same pass, to the new Session::pointer_samples. Every other tool call hands them over first, so the order of events does not change. - Session::pointer_samples feeds every sample to the tool and applies only the last preview of each run of previews of one command. The held preview is applied before the release and before any other action. - Every preview still runs during a Global Edit, with Objects on Path selected, with more than one object selected, and with New Art Has Basic Appearance off when the stroke began with a selection, since a preview there changes what the next sample reads. The decision is made again after each event that is not a drag.
This commit is contained in:
1 parent
b36fbc76bd
commit
f080afc4ae
9 files changed
+515
-15
No files matched your search
@@ -102,7 +102,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
|
||||
/// The Objects on Path groups of `ids`: the ones among them, and the innermost one around each
|
||||
/// object in one.
|
||||
fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
pub(crate) fn groups_of(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
|
||||
let mut out = vec![];
|
||||
for id in ids {
|
||||
let group = d.ancestry(*id).unwrap_or_default().into_iter().rev().find(|a| d.node(*a).is_some_and(is_objects_on_path));
|
||||
|
||||
@@ -455,6 +455,13 @@ pub struct Session {
|
||||
/// The pointer button is held: the last pointer event was a press or a drag, not a release or
|
||||
/// a move ([`Session::pointer_held`]).
|
||||
pub(crate) pointer_held: bool,
|
||||
/// While [`Session::pointer_samples`] feeds a pass's samples to the tool, the tool's previews are
|
||||
/// held in [`Self::sampled_preview`] instead of being applied.
|
||||
pub(crate) holds_previews: bool,
|
||||
/// The last preview the tool asked for during [`Session::pointer_samples`], not yet applied. It is
|
||||
/// applied before any other action of the tool, before a preview of another command, and when the
|
||||
/// samples end.
|
||||
pub(crate) sampled_preview: Option<(String, serde_json::Value)>,
|
||||
/// The id and persistent options of the tool when the press under way began, which a dropped
|
||||
/// press puts back ([`Session::drop_tool_press`]).
|
||||
pub(crate) press_options: Option<(String, serde_json::Map<String, serde_json::Value>)>,
|
||||
|
||||
@@ -14,3 +14,6 @@ mod documents;
|
||||
mod edit;
|
||||
mod execute;
|
||||
mod undo;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use edit::previews_run;
|
||||
@@ -165,6 +165,8 @@ impl Session {
|
||||
liquify_stroke: None,
|
||||
plane_widget_press: false,
|
||||
pointer_held: false,
|
||||
holds_previews: false,
|
||||
sampled_preview: None,
|
||||
press_options: None,
|
||||
press_options_stored: false,
|
||||
press_type_selection: None,
|
||||
|
||||
@@ -4,6 +4,18 @@ use super::{
|
||||
};
|
||||
use crate::doc_state::{kept_from, objects_only};
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many times [`Session::preview`] ran on this thread.
|
||||
static PREVIEWS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// How many times [`Session::preview`] has run on this thread.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn previews_run() -> usize {
|
||||
PREVIEWS.get()
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Takes committed swatch renames as (document uid, old name, new name) in execution order and leaves the record empty.
|
||||
/// The uid identifies the originating document through [`crate::DocState::uid`].
|
||||
@@ -583,6 +595,8 @@ impl Session {
|
||||
|
||||
/// Re-apply `cmd` on top of the interaction snapshot (replacing the previous preview).
|
||||
pub fn preview(&mut self, cmd: &str, params: &Value) -> Result<Value> {
|
||||
#[cfg(test)]
|
||||
PREVIEWS.set(PREVIEWS.get() + 1);
|
||||
self.put_back_interaction();
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
|
||||
@@ -320,6 +320,192 @@ fn pencil_continues_selected_open_path() {
|
||||
assert_eq!(p.subpaths[0].anchors[0].p, Point::new(100.0, 100.0));
|
||||
}
|
||||
|
||||
/// The document without its creation time, the selection and the new-art paints.
|
||||
type Drawn = (vectorcraft_doc::Document, vectorcraft_doc::Selection, vectorcraft_tools::PaintDefaults);
|
||||
|
||||
fn drawn(s: &Session) -> Drawn {
|
||||
let st = s.doc().unwrap();
|
||||
let mut doc = (*st.doc).clone();
|
||||
// `file.new` stamps the time in seconds, which differs between two sessions made a second apart.
|
||||
doc.metadata.created = None;
|
||||
(doc, st.selection.clone(), s.paint.clone())
|
||||
}
|
||||
|
||||
/// Draws `pts` with the Pencil in a session that `setup` prepared, handing the drag's samples and the release to the
|
||||
/// session in groups of 4, the release in the last group: through [`Session::pointer_samples`] with `by_frame`, else
|
||||
/// one at a time through [`Session::pointer`]. What [`drawn`] gives after each group, the previews each group ran,
|
||||
/// and the previews a group runs when its drags preview once: one for its drags and one for its release.
|
||||
fn pencil_in_frames(setup: &dyn Fn(&mut Session), pts: &[(f64, f64)], by_frame: bool) -> (Vec<Drawn>, Vec<usize>, Vec<usize>) {
|
||||
let mut s = session();
|
||||
setup(&mut s);
|
||||
let v = view();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, pts[0].0, pts[0].1), v).unwrap();
|
||||
let mut samples: Vec<PointerEvent> = pts[1..].iter().map(|&(x, y)| PointerEvent::new(PointerKind::Drag, x, y)).collect();
|
||||
let l = pts[pts.len() - 1];
|
||||
samples.push(PointerEvent::new(PointerKind::Up, l.0, l.1));
|
||||
let (mut states, mut previews, mut once) = (vec![], vec![], vec![]);
|
||||
for group in samples.rchunks(4).rev() {
|
||||
let has = |kind| usize::from(group.iter().any(|ev| ev.kind == kind));
|
||||
once.push(has(PointerKind::Drag) + has(PointerKind::Up));
|
||||
let before = crate::session::previews_run();
|
||||
if by_frame {
|
||||
let (fed, r) = s.pointer_samples(group, v);
|
||||
r.unwrap();
|
||||
assert_eq!(fed, group.len(), "every sample fed");
|
||||
} else {
|
||||
for ev in group {
|
||||
s.pointer(ev, v).unwrap();
|
||||
}
|
||||
}
|
||||
previews.push(crate::session::previews_run() - before);
|
||||
states.push(drawn(&s));
|
||||
}
|
||||
(states, previews, once)
|
||||
}
|
||||
|
||||
/// The drag samples of a frame of up to 4 Pencil samples run one preview, the last sample's, before the release when
|
||||
/// the frame ends with it, and leave the document, the selection and the new-art paints as handing the samples over one
|
||||
/// by one does, after every frame: for a new stroke, for strokes that continue a selected path at its end and at its
|
||||
/// start, and with New Art Has Basic Appearance off and an empty starting selection. Every sample is previewed when
|
||||
/// inheriting a selected gradient, with two selected paths in a group, during a Global Edit, or with Objects on Path selected.
|
||||
#[test]
|
||||
fn pencil_samples_of_one_frame_run_one_preview() {
|
||||
let none = |_: &mut Session| {};
|
||||
let selected_line = |s: &mut Session| {
|
||||
line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
};
|
||||
let not_basic = |s: &mut Session| {
|
||||
rect(s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
};
|
||||
let selected_gradient = |s: &mut Session| {
|
||||
rect(s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [400, 400], "end": [400, 450]}})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.select_tool("pencil", view()).unwrap();
|
||||
s.set_tool_option("fill", &json!(true));
|
||||
s.set_tool_option("keepSelected", &json!(true));
|
||||
};
|
||||
let grouped_paths = |s: &mut Session| {
|
||||
let a = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
let b = line(s, 400.0, 200.0, 420.0, 200.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
};
|
||||
let new_stroke = wave(100.0, 180.0, 300.0);
|
||||
let wavy =
|
||||
|x0: f64, step: f64| -> Vec<(f64, f64)> { (0..=40).map(|i| (x0 + step * f64::from(i), 101.0 + 10.0 * (f64::from(i) / 6.0).sin())).collect() };
|
||||
let (past_end, before_start) = (wavy(202.0, 2.0), wavy(99.0, -2.0));
|
||||
// A Global Edit preview also changes the other members, which the tool reads for its next sample.
|
||||
let global_edit = |s: &mut Session| {
|
||||
let a = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
line(s, 100.0, 140.0, 200.0, 140.0);
|
||||
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
|
||||
assert_eq!(s.execute("select.globalEdit", &json!({})).unwrap()["active"], true);
|
||||
};
|
||||
// Continuing the spine of an Objects on Path group moves the attached art, so every sample is previewed.
|
||||
let objects_on_path = |s: &mut Session| {
|
||||
let spine = line(s, 100.0, 100.0, 200.0, 100.0);
|
||||
let attached = line(s, 400.0, 200.0, 420.0, 200.0);
|
||||
s.execute("object.objectsOnPath.attach", &json!({"path": spine.0, "ids": [attached.0]})).unwrap();
|
||||
s.execute("select.set", &json!({"ids": [spine.0]})).unwrap();
|
||||
};
|
||||
// The name, the setup, the stroke, the paths after the release, and whether a frame previews once.
|
||||
type Case<'a> = (&'a str, &'a dyn Fn(&mut Session), &'a [(f64, f64)], usize, bool);
|
||||
let cases: [Case; 8] = [
|
||||
("new stroke", &none, &new_stroke, 1, true),
|
||||
("continues the end", &selected_line, &past_end, 1, true),
|
||||
("continues the start", &selected_line, &before_start, 1, true),
|
||||
("basic appearance off", ¬_basic, &new_stroke, 2, true),
|
||||
(
|
||||
"inherits a selected gradient",
|
||||
&selected_gradient,
|
||||
&[(100.0, 180.0), (120.0, 180.0), (140.0, 180.0), (160.0, 200.0), (180.0, 220.0), (200.0, 230.0)],
|
||||
2,
|
||||
false,
|
||||
),
|
||||
("two selected paths in a group", &grouped_paths, &past_end, 2, false),
|
||||
("global edit", &global_edit, &past_end, 2, false),
|
||||
("objects on path", &objects_on_path, &past_end, 2, false),
|
||||
];
|
||||
for (name, setup, pts, path_count, once) in cases {
|
||||
let (one_by_one, each, _) = pencil_in_frames(setup, pts, false);
|
||||
let (by_frames, previews, expected) = pencil_in_frames(setup, pts, true);
|
||||
if once {
|
||||
assert_eq!(previews, expected, "{name}: one preview for the drags of a frame, and one for its release");
|
||||
} else {
|
||||
assert_eq!(previews, each, "{name}: a preview per sample");
|
||||
}
|
||||
assert_eq!(by_frames.len(), one_by_one.len(), "{name}");
|
||||
for (k, (a, b)) in by_frames.iter().zip(&one_by_one).enumerate() {
|
||||
assert!(a == b, "{name}: state {k} differs from handing the samples over one by one");
|
||||
}
|
||||
let mut paths = 0;
|
||||
by_frames[by_frames.len() - 1].0.walk(|n| paths += usize::from(matches!(n.kind, NodeKind::Path { .. })));
|
||||
assert_eq!(paths, path_count, "{name}: paths after the release");
|
||||
}
|
||||
}
|
||||
|
||||
/// One call that carries a Pencil release and the next stroke's press and drags previews every drag of the second
|
||||
/// stroke when that stroke begins with the first one selected and New Art Has Basic Appearance off, and leaves the
|
||||
/// document, the selection and the new-art paints as handing the events over one by one does.
|
||||
#[test]
|
||||
fn pencil_samples_spanning_two_strokes_decide_again_after_the_press() {
|
||||
let v = view();
|
||||
let setup = || {
|
||||
let mut s = session();
|
||||
rect(&mut s, 400.0, 400.0, 50.0, 50.0);
|
||||
s.execute("paint.setFill", &json!({"gradient": {"kind": "linear", "start": [400, 400], "end": [400, 450]}})).unwrap();
|
||||
s.execute("appearance.setNewArtBasic", &json!({"on": false})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.select_tool("pencil", v).unwrap();
|
||||
s.set_tool_option("fill", &json!(true));
|
||||
s.set_tool_option("keepSelected", &json!(true));
|
||||
assert!(s.doc().unwrap().selection.is_empty());
|
||||
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
|
||||
for (x, y) in [(120.0, 100.0), (140.0, 120.0), (160.0, 130.0)] {
|
||||
s.pointer(&PointerEvent::new(PointerKind::Drag, x, y), v).unwrap();
|
||||
}
|
||||
s
|
||||
};
|
||||
let mut batched = setup();
|
||||
let mut individual = setup();
|
||||
let mut samples = vec![PointerEvent::new(PointerKind::Up, 160.0, 130.0), PointerEvent::new(PointerKind::Down, 100.0, 220.0)];
|
||||
let drags = [
|
||||
(120.0, 220.0),
|
||||
(140.0, 220.0),
|
||||
(160.0, 220.0),
|
||||
(180.0, 220.0),
|
||||
(200.0, 220.0),
|
||||
(220.0, 240.0),
|
||||
(240.0, 260.0),
|
||||
(260.0, 280.0),
|
||||
(280.0, 290.0),
|
||||
(300.0, 300.0),
|
||||
];
|
||||
samples.extend(drags.iter().map(|&(x, y)| PointerEvent::new(PointerKind::Drag, x, y)));
|
||||
let before = crate::session::previews_run();
|
||||
let (fed, result) = batched.pointer_samples(&samples, v);
|
||||
result.unwrap();
|
||||
let batched_previews = crate::session::previews_run() - before;
|
||||
assert_eq!(fed, samples.len(), "every sample fed");
|
||||
let before = crate::session::previews_run();
|
||||
individual.pointer(&samples[0], v).unwrap();
|
||||
let release_previews = crate::session::previews_run() - before;
|
||||
assert!(!individual.doc().unwrap().selection.is_empty());
|
||||
for ev in &samples[1..] {
|
||||
individual.pointer(ev, v).unwrap();
|
||||
}
|
||||
let individual_previews = crate::session::previews_run() - before;
|
||||
assert_eq!(individual_previews, drags.len() + release_previews, "each drag runs a preview");
|
||||
assert_eq!(batched_previews, individual_previews, "the batch runs every preview");
|
||||
assert!(drawn(&batched) == drawn(&individual), "document, selection and new-art paints match");
|
||||
}
|
||||
|
||||
/// Connect two paths: with two open paths selected, a Pencil stroke from an end of one to an end
|
||||
/// of the other joins them into one path, the first one's, in one undo step. A path that is not
|
||||
/// selected is not joined.
|
||||
|
||||
+124
-10
@@ -750,6 +750,94 @@ impl Session {
|
||||
r
|
||||
}
|
||||
|
||||
/// [`Self::pointer`] for each of `evs`, the samples one frame delivers to a tool that builds its
|
||||
/// stroke from every position the pointer passed ([`Self::tool_wants_samples`]), and the release
|
||||
/// when it comes in that frame. The tool gets every sample, but of a run of previews of one
|
||||
/// command only the last is applied, since each preview replaces the one before it. Every other
|
||||
/// action of the tool runs in its order, after the preview held before it. The held preview is
|
||||
/// applied before the release or any other event that is not a drag, since the release reads the
|
||||
/// document as the drag's preview left it. Every preview is applied during a Global Edit, with
|
||||
/// Objects on Path selected, or with multiple objects selected, since a preview can change other
|
||||
/// paths or their eligibility for joins. Every preview is also applied with New Art Has Basic
|
||||
/// Appearance off when the interaction began with a selection, since previews then carry the
|
||||
/// inherited new-art paints forward. The decision is made again after each event that is not a drag.
|
||||
/// Feeding stops after a sample that fails, that asks the frontend for more than a status
|
||||
/// message, or that leaves the tool computing an edit on another thread, so the frontend acts
|
||||
/// on it before the samples after it.
|
||||
/// Returns how many of `evs` were fed (at least one unless `evs` is empty) and what they ask of
|
||||
/// the frontend.
|
||||
pub fn pointer_samples(&mut self, evs: &[PointerEvent], view: ViewInfo) -> (usize, Result<Vec<UiRequest>>) {
|
||||
let mut ui = vec![];
|
||||
let mut failed = None;
|
||||
let mut fed = 0;
|
||||
let mut holds = self.holds_previews || !self.preview_affects_later_samples();
|
||||
let outer = std::mem::replace(&mut self.holds_previews, holds);
|
||||
for ev in evs {
|
||||
fed += 1;
|
||||
if ev.kind != PointerKind::Drag && !outer {
|
||||
self.holds_previews = false;
|
||||
match self.apply_sampled_preview() {
|
||||
Ok(asks) => ui.extend(asks),
|
||||
Err(e) => {
|
||||
failed.get_or_insert(e);
|
||||
}
|
||||
}
|
||||
self.holds_previews = holds;
|
||||
}
|
||||
let result = self.pointer(ev, view);
|
||||
if ev.kind != PointerKind::Drag {
|
||||
holds = outer || !self.preview_affects_later_samples();
|
||||
self.holds_previews = holds;
|
||||
}
|
||||
match result {
|
||||
Ok(asks) => {
|
||||
let stop = asks.iter().any(|a| !matches!(a, UiRequest::Status(_)));
|
||||
ui.extend(asks);
|
||||
if stop || self.tool_edit_pending() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
failed = Some(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.holds_previews = outer;
|
||||
let held = if outer { Ok(vec![]) } else { self.apply_sampled_preview() };
|
||||
let r = match (failed, held) {
|
||||
(Some(e), _) | (None, Err(e)) => Err(e),
|
||||
(None, Ok(more)) => {
|
||||
ui.extend(more);
|
||||
Ok(ui)
|
||||
}
|
||||
};
|
||||
(fed, r)
|
||||
}
|
||||
|
||||
/// Whether each preview must run because it can change other paths, their eligibility for joins,
|
||||
/// or the new-art paints inherited by later previews: with more than one object selected now or
|
||||
/// when the interaction began, since the tool reads the other selected paths for joins. Before an
|
||||
/// interaction opens, its starting selection is the active document's current selection.
|
||||
fn preview_affects_later_samples(&self) -> bool {
|
||||
self.active().is_some_and(|st| {
|
||||
let selection = st.interaction.as_ref().map_or(&st.selection, |it| it.selection.as_ref());
|
||||
(!self.prefs.new_art_basic && !selection.is_empty())
|
||||
|| selection.objects.len() > 1
|
||||
|| st.selection.objects.len() > 1
|
||||
|| st.global_edit.is_some()
|
||||
|| !crate::cmd::objects_on_path::groups_of(&st.doc, &st.selection.objects).is_empty()
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies the preview [`Self::pointer_samples`] held, if any, as the tool's own action.
|
||||
fn apply_sampled_preview(&mut self) -> Result<Vec<UiRequest>> {
|
||||
match self.sampled_preview.take() {
|
||||
Some((cmd, p)) => self.apply_actions(vec![Action::Preview(cmd, p)]),
|
||||
None => Ok(vec![]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of the next pointer or key event handed to the session.
|
||||
fn next_input(&mut self) -> u64 {
|
||||
let n = self.input_count;
|
||||
@@ -1865,9 +1953,23 @@ impl Session {
|
||||
r
|
||||
}
|
||||
|
||||
/// [`Self::run_tool_actions`], holding the previews while [`Self::pointer_samples`] runs. Actions
|
||||
/// that these actions lead to run with nothing held.
|
||||
fn apply_tool_actions(&mut self, acts: Vec<Action>) -> Result<Vec<UiRequest>> {
|
||||
let holds = std::mem::take(&mut self.holds_previews);
|
||||
let r = self.run_tool_actions(acts, holds);
|
||||
self.holds_previews = holds;
|
||||
r
|
||||
}
|
||||
|
||||
/// Runs the tool's actions in order. With `holds`, a preview is kept in [`Self::sampled_preview`]
|
||||
/// in place of the one kept before it, and the kept preview is applied before any other action.
|
||||
fn run_tool_actions(&mut self, acts: Vec<Action>, holds: bool) -> Result<Vec<UiRequest>> {
|
||||
let mut ui = vec![];
|
||||
for a in acts {
|
||||
if let Some((cmd, p)) = self.sampled_preview.take_if(|(held, _)| !matches!(&a, Action::Preview(cmd, _) if *cmd == *held)) {
|
||||
self.run_preview(&cmd, &p, &mut ui);
|
||||
}
|
||||
match a {
|
||||
Action::Begin(label) => {
|
||||
// The snapshot of the interaction open before, which the tool's drag then joins.
|
||||
@@ -1893,17 +1995,13 @@ impl Session {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
self.clear_deferred_overlay_cache();
|
||||
match self.preview(&cmd, &p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str)
|
||||
&& !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))
|
||||
{
|
||||
ui.push(UiRequest::Status(w.to_string()));
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("preview {cmd}: {e}"),
|
||||
if holds {
|
||||
self.sampled_preview = Some((cmd, p));
|
||||
continue;
|
||||
}
|
||||
// This preview replaces a held preview of the same command.
|
||||
self.sampled_preview = None;
|
||||
self.run_preview(&cmd, &p, &mut ui);
|
||||
}
|
||||
// The drag is over: the dabs of a Liquify stroke have no further use.
|
||||
Action::Commit => {
|
||||
@@ -1965,6 +2063,22 @@ impl Session {
|
||||
Ok(ui)
|
||||
}
|
||||
|
||||
/// Applies the tool's preview of `cmd` with `p`. Its warning goes to `ui` once; a failed preview
|
||||
/// is logged and leaves the interaction open.
|
||||
fn run_preview(&mut self, cmd: &str, p: &Value, ui: &mut Vec<UiRequest>) {
|
||||
self.clear_deferred_overlay_cache();
|
||||
match self.preview(cmd, p) {
|
||||
Ok(v) => {
|
||||
if let Some(w) = v.get("warning").and_then(Value::as_str)
|
||||
&& !ui.iter().any(|r| matches!(r, UiRequest::Status(s) if s == w))
|
||||
{
|
||||
ui.push(UiRequest::Status(w.to_string()));
|
||||
}
|
||||
}
|
||||
Err(e) => log::warn!("preview {cmd}: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// With Real-time Drawing off, the selection's transform box ([`Session::transform_box`]) as the
|
||||
/// pending preview of a handle resize or of a shape being drawn leaves it, measured once per
|
||||
/// preview step, with the layer color of the first object it measures; `None` when no such
|
||||
|
||||
@@ -149,11 +149,40 @@ struct SessionTool<'a> {
|
||||
/// The canvas's context and layer: a window over the canvas (a floating document's) hides it from the pointer.
|
||||
ctx: egui::Context,
|
||||
layer: egui::LayerId,
|
||||
/// The drag samples of this pass for a tool that takes every position the pointer passed, handed to the session
|
||||
/// together by [`Self::send_samples`].
|
||||
samples: RefCell<Vec<PointerEvent>>,
|
||||
}
|
||||
|
||||
impl<'a> SessionTool<'a> {
|
||||
fn new(app: &'a mut VectorcraftApp, view: ViewInfo, ui: &Ui) -> Self {
|
||||
Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id() }
|
||||
Self { app: RefCell::new(app), view, carrying: Cell::new(false), ctx: ui.ctx().clone(), layer: ui.layer_id(), samples: RefCell::new(vec![]) }
|
||||
}
|
||||
|
||||
/// Keeps `ev`, a drag or the release, for [`Self::send_samples`] when the tool takes every position the pointer
|
||||
/// passed; otherwise hands the kept samples and then `ev` to the session.
|
||||
fn send_sample(&self, ev: PointerEvent) {
|
||||
if self.app().session.tool_wants_samples() {
|
||||
self.samples.borrow_mut().push(ev);
|
||||
} else {
|
||||
self.send_samples();
|
||||
dispatch(&mut self.app(), &ev, self.view);
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands the drag samples kept in this pass to the session ([`vectorcraft_engine::Session::pointer_samples`]),
|
||||
/// which applies only the last of the tool's previews, and acts on what they ask of the UI. Each call on the tool
|
||||
/// other than a drag runs it first, so every other event reaches the tool after the samples before it.
|
||||
fn send_samples(&self) {
|
||||
let samples = std::mem::take(&mut *self.samples.borrow_mut());
|
||||
let mut rest = samples.as_slice();
|
||||
while !rest.is_empty() {
|
||||
let mut app = self.app();
|
||||
let (fed, r) = app.session.pointer_samples(rest, self.view);
|
||||
sync_artboard(&mut app);
|
||||
apply_requests(&mut app, r);
|
||||
rest = rest.get(fed.max(1)..).unwrap_or_default();
|
||||
}
|
||||
}
|
||||
|
||||
/// `ev` with Shift, Alt, Cmd and Ctrl as they were held when the gesture's button went up in this pass, latched ones
|
||||
@@ -284,6 +313,7 @@ fn engine_key(chord: Chord) -> Option<(EngineKey, bool)> {
|
||||
|
||||
impl CanvasTool for SessionTool<'_> {
|
||||
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
|
||||
self.send_samples();
|
||||
let mut app = self.app();
|
||||
if app.ui.screen_mode == 3 {
|
||||
// Presentation Mode: the tool gets nothing; the release of a click steps to the next artboard.
|
||||
@@ -342,7 +372,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
if !carried {
|
||||
// The moves of the pass that releases the press came before its release, with the keys held then.
|
||||
let ev = self.at_release(pointer, pointer_event(PointerKind::Drag, pointer, cx));
|
||||
dispatch(&mut self.app(), &ev, self.view);
|
||||
self.send_sample(ev);
|
||||
self.app().canvas.last_drag = Some((pointer.pos, ev));
|
||||
}
|
||||
self.carrying.set(carried);
|
||||
@@ -367,6 +397,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
let given_up = cx.over_drop_target() || carried.is_some();
|
||||
if given_up {
|
||||
// The art goes to the drop target, or nowhere off the canvas: the move is given up where it started.
|
||||
self.send_samples();
|
||||
let _ = self.app().session.cancel_interaction();
|
||||
}
|
||||
if let Some(art) = carried.filter(|_| !cx.over_drop_target()) {
|
||||
@@ -381,9 +412,11 @@ impl CanvasTool for SessionTool<'_> {
|
||||
// that pass still draws a square. A move that was given up gets none.
|
||||
let last = self.app().canvas.last_drag.map(|(_, ev)| ev);
|
||||
if !given_up && last.is_some_and(|last| (last.pos, last.mods, last.backquote) != (up.pos, up.mods, up.backquote)) {
|
||||
dispatch(&mut self.app(), &PointerEvent { kind: PointerKind::Drag, ..up }, self.view);
|
||||
self.send_sample(PointerEvent { kind: PointerKind::Drag, ..up });
|
||||
}
|
||||
dispatch(&mut self.app(), &up, self.view);
|
||||
// The release goes to the session after the samples of its pass, which preview the stroke once before it.
|
||||
self.send_sample(up);
|
||||
self.send_samples();
|
||||
if self.app().canvas.last_drag.is_some() {
|
||||
// A press that dragged is no click, and the framework counts presses: the next press starts a new run.
|
||||
self.app().ui.trace_pick_clicks = pointer.clicks;
|
||||
@@ -412,10 +445,12 @@ impl CanvasTool for SessionTool<'_> {
|
||||
}
|
||||
|
||||
fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.send_samples();
|
||||
self.send(PointerKind::Move, pointer, cx);
|
||||
}
|
||||
|
||||
fn cancel(&mut self, reason: CancelReason, cx: &mut ToolContext<'_>) {
|
||||
self.send_samples();
|
||||
let mut app = self.app();
|
||||
if app.ui.screen_mode == 3 {
|
||||
// The tool had no press of Presentation Mode's.
|
||||
@@ -435,6 +470,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
}
|
||||
|
||||
fn claims(&self) -> ToolClaims {
|
||||
self.send_samples();
|
||||
let mut app = self.app();
|
||||
let view = self.view;
|
||||
let claim = |app: &mut VectorcraftApp, key: EngineKey| app.session.tool_claims_key(key, view);
|
||||
@@ -477,6 +513,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, cx: &mut ToolContext<'_>) -> bool {
|
||||
self.send_samples();
|
||||
let space = cx.held(Key::Space);
|
||||
let held = tool_mods(cx.mods, space);
|
||||
match key {
|
||||
@@ -564,6 +601,7 @@ impl CanvasTool for SessionTool<'_> {
|
||||
/// While the view moves under the pointer, the cursor the tool last gave for the same tool and keys stays: asking
|
||||
/// the tool again would hit-test the art under the pointer in every frame of a pan or zoom (#2452).
|
||||
fn cursor(&self, cx: &ToolContext<'_>) -> Cursor {
|
||||
self.send_samples();
|
||||
let Some(space) = cx.space() else { return tool_cursor(vectorcraft_tools::Cursor::Arrow) };
|
||||
let at = cx.pointer.map_or(Point::ZERO, |p| space.view.to_doc(p.pos));
|
||||
let mods = tool_mods(cx.mods, cx.held(Key::Space));
|
||||
@@ -730,6 +768,7 @@ pub(crate) fn run(app: &mut VectorcraftApp, ui: &mut Ui, pass: &ToolPass) -> Too
|
||||
app.canvas.zoom_tool = None;
|
||||
let mut tool = SessionTool::new(app, view_info, ui);
|
||||
let response = host_run_session(&mut tool, ui, pass);
|
||||
tool.send_samples();
|
||||
drop(tool);
|
||||
response
|
||||
};
|
||||
|
||||
@@ -215,3 +215,138 @@ fn the_caps_lock_command_before_the_first_frame_stays_in_place() {
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
assert!(app.session.caps_lock);
|
||||
}
|
||||
|
||||
/// The moves of one pass reach the Pencil together: the pass previews the stroke once, and the path the release draws
|
||||
/// runs from the press to the last move.
|
||||
#[test]
|
||||
fn a_pencil_pass_of_four_moves_previews_once() {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("pencil");
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let view = app.canvas_view().unwrap();
|
||||
let on_wave = |x: f64| Point::new(x, 150.0 + 20.0 * (x / 15.0).sin());
|
||||
let at = |x: f64| view.to_screen(on_wave(x));
|
||||
let button =
|
||||
|x: f64, pressed| egui::Event::PointerButton { pos: at(x), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let moves = |from: f64, n: u32| (1..=n).map(|i| egui::Event::PointerMoved(at(from + 6.0 * f64::from(i)))).collect::<Vec<_>>();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(100.0)), button(100.0, true)]);
|
||||
frame(&mut app, &ctx, moves(100.0, 4));
|
||||
// Each preview the pass runs moves the revision by the same amount.
|
||||
let revision = |app: &VectorcraftApp| app.session.active().unwrap().revision;
|
||||
let before = revision(&app);
|
||||
frame(&mut app, &ctx, moves(124.0, 1));
|
||||
let one = revision(&app) - before;
|
||||
assert!(one > 0, "a pass of one move previews the stroke");
|
||||
let before = revision(&app);
|
||||
frame(&mut app, &ctx, moves(130.0, 4));
|
||||
assert_eq!(revision(&app) - before, one, "a pass of 4 moves previews the stroke once, as a pass of one move does");
|
||||
frame(&mut app, &ctx, vec![button(154.0, false)]);
|
||||
let mut ends = vec![];
|
||||
app.session.active().unwrap().doc.walk(|n| {
|
||||
if let Some(pd) = n.path_data() {
|
||||
ends.extend(pd.subpaths.iter().filter_map(|sp| Some((sp.anchors.first()?.p, sp.anchors.last()?.p))));
|
||||
}
|
||||
});
|
||||
let near = |a: Point, x: f64| a.distance(on_wave(x)) < 0.5;
|
||||
assert!(matches!(ends.as_slice(), [(first, last)] if near(*first, 100.0) && near(*last, 154.0)), "{ends:?}");
|
||||
}
|
||||
|
||||
/// The release reaches the Pencil after the moves of its pass: a pass of 4 moves and the release previews the moves
|
||||
/// once, as a pass of one move and the release does, and the path runs from the press to the release.
|
||||
#[test]
|
||||
fn a_pencil_release_with_moves_previews_once() {
|
||||
// The revision's change in the pass that releases after `last` moves, and the ends of the paths drawn.
|
||||
let stroke = |last: u32| {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("pencil");
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let view = app.canvas_view().unwrap();
|
||||
let on_wave = |x: f64| Point::new(x, 150.0 + 20.0 * (x / 15.0).sin());
|
||||
let at = |x: f64| view.to_screen(on_wave(x));
|
||||
let button =
|
||||
|x: f64, pressed| egui::Event::PointerButton { pos: at(x), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
let moves = |from: f64, n: u32| (1..=n).map(|i| egui::Event::PointerMoved(at(from + 6.0 * f64::from(i)))).collect::<Vec<_>>();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at(100.0)), button(100.0, true)]);
|
||||
frame(&mut app, &ctx, moves(100.0, 4));
|
||||
let before = app.session.active().unwrap().revision;
|
||||
let end = 124.0 + 6.0 * f64::from(last);
|
||||
let mut pass = moves(124.0, last);
|
||||
pass.push(button(end, false));
|
||||
frame(&mut app, &ctx, pass);
|
||||
let changed = app.session.active().unwrap().revision - before;
|
||||
let mut ends = vec![];
|
||||
app.session.active().unwrap().doc.walk(|n| {
|
||||
if let Some(pd) = n.path_data() {
|
||||
ends.extend(pd.subpaths.iter().filter_map(|sp| Some((sp.anchors.first()?.p, sp.anchors.last()?.p))));
|
||||
}
|
||||
});
|
||||
let near = |a: Point, x: f64| a.distance(on_wave(x)) < 0.5;
|
||||
assert!(matches!(ends.as_slice(), [(first, last)] if near(*first, 100.0) && near(*last, end)), "{ends:?}");
|
||||
changed
|
||||
};
|
||||
let one = stroke(1);
|
||||
assert!(one > stroke(0), "a move in the release's pass previews the stroke");
|
||||
assert_eq!(stroke(4), one, "a pass of 4 moves and the release previews the moves once, as a pass of one move does");
|
||||
}
|
||||
|
||||
/// The Pencil draws the same path when the moves come in passes of 4, the last one with the release, as when each move
|
||||
/// comes in a pass of its own: the moves inside a pass bend the path.
|
||||
#[test]
|
||||
fn a_pencil_stroke_in_passes_of_four_keeps_every_bend() {
|
||||
let stroke = |grouped: bool| {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
app.run("file.new", serde_json::json!({"width": 400, "height": 300})).unwrap();
|
||||
app.select_tool("pencil");
|
||||
let ctx = crate::testing::ui_context();
|
||||
frame(&mut app, &ctx, vec![]);
|
||||
let view = app.canvas_view().unwrap();
|
||||
let start = view.to_screen(Point::new(80.0, 150.0));
|
||||
let end = view.to_screen(Point::new(320.0, 150.0));
|
||||
let button = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
// Every fourth move lies on the chord: a path made from the last move of each pass alone has no bend.
|
||||
let moves: Vec<_> = (1..=12)
|
||||
.zip([90.0, 210.0, 90.0, 150.0, 90.0, 210.0, 90.0, 150.0, 90.0, 210.0, 90.0, 150.0])
|
||||
.map(|(i, y)| egui::Event::PointerMoved(view.to_screen(Point::new(80.0 + 20.0 * f64::from(i), y))))
|
||||
.collect();
|
||||
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(start), button(start, true)]);
|
||||
let pass_size = if grouped { 4 } else { 1 };
|
||||
for (i, chunk) in moves.chunks(pass_size).enumerate() {
|
||||
let mut events = chunk.to_vec();
|
||||
if grouped && (i + 1) * pass_size == moves.len() {
|
||||
events.push(button(end, false));
|
||||
}
|
||||
frame(&mut app, &ctx, events);
|
||||
}
|
||||
if !grouped {
|
||||
frame(&mut app, &ctx, vec![button(end, false)]);
|
||||
}
|
||||
let mut paths = vec![];
|
||||
app.session.active().unwrap().doc.walk(|n| {
|
||||
if let Some(pd) = n.path_data() {
|
||||
paths.push(pd.clone());
|
||||
}
|
||||
});
|
||||
paths
|
||||
};
|
||||
let separate = stroke(false);
|
||||
let grouped = stroke(true);
|
||||
assert_eq!(grouped, separate, "grouping moves with the release preserves every path's data");
|
||||
assert_eq!(separate.len(), 1, "the stroke creates one path");
|
||||
assert_eq!(separate[0].subpaths.len(), 1, "the stroke creates one subpath");
|
||||
let anchors = &separate[0].subpaths[0].anchors;
|
||||
let first = anchors.first().unwrap().p;
|
||||
let last = anchors.last().unwrap().p;
|
||||
let chord = first.distance(last);
|
||||
assert!(chord > 1.0, "the stroke has distinct endpoints");
|
||||
assert!(
|
||||
anchors.iter().any(|a| {
|
||||
let cross = (last.x - first.x) * (a.p.y - first.y) - (last.y - first.y) * (a.p.x - first.x);
|
||||
cross.abs() / chord > 1.0
|
||||
}),
|
||||
"the finished path has a bend more than 1 pt from its chord"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user