mirror of
https://github.com/storytold/designcraft.git
synced 2026-10-31 05:36:46 -06:00
Conflicts resolved per file (both sides kept unless noted):
crates/engine/src/atomic.rs | 1 | main's: `write_file` removed (main routes command writes through `crate::io::write_file`); its one caller in file.rs now uses `crate::io::write_file`
crates/engine/src/cmd/datamerge/fill.rs | 1 | next's `Graphic` literal (has `clip` and `wrap`, which next's `Graphic` carries)
crates/engine/src/cmd/datamerge/mod.rs | 1 | main's `read_path_capped` (crate::io metadata/read_capped, roots checked); next's capped read is the same behaviour
crates/engine/src/cmd/datamerge/parse.rs | 1 | main's (`crate::io::metadata`, `crate::io::Metadata`)
crates/engine/src/cmd/edit.rs | 1 | next's `spread_param(p, "edit.paste")` (the second argument is the command id on both sides)
crates/engine/src/cmd/export.rs | 3 | main's: EPUB params doc, `toc_title` once (main's position; next's duplicate dropped)
crates/engine/src/cmd/file.rs | 7 | place doc: next's (lists page/rect/autoflow params #803 checks); next's recent-file functions + main's `foreign_document`; next's open (load_bytes, warnings, non-DesignCraft refusal) with main's checked `crate::io::read_file` for the bytes; main's `check_write` be
crates/engine/src/cmd/find.rs | 7 | main's Find scope (FindContext, scope/selection/story, continuation, UTF-8 repair) on next's `designcraft_compose::grep::Grep` (dialect GREP): find uses `find_all` capped at MAX_MATCHES, change uses `replacements`/`find_all` (literal change text not expanded), fin
crates/engine/src/cmd/fonts.rs | 1 | next's (`has_style`, resolved/replacement face); `has_style` already compares styles ignoring spacing and case, which is main's `same_style` fix; main's test kept
crates/engine/src/cmd/interchange.rs | 1 | next's `import_idml_report_with_previews` (previews for unreadable links)
crates/engine/src/cmd/layout.rs | 8 | pages.insert: main's overflow-safe `after` + next's checked `parent_ref`; main's duplicateSpread doc; layout.section: next's `SectionEdit` (already keeps unnamed settings, #717) with main's `d.repaginate()` moved into `SectionEdit::apply` (remove and set paths),
crates/engine/src/cmd/links.rs | 5 | next's links.list (no doc clone); main's `text_status` via crate::io; `use std::io::Read` dropped (unused after main's read_capped); test literals main's. `link_missing` (next) uses `crate::io::exists` for the file-guard scan
crates/engine/src/cmd/object.rs | 4 | object.fill/stroke tint-alone: main's (23e1680e7; out-of-range tint is an error, which main's test asserts); object.fit doc: next's (lists `axis`)
crates/engine/src/cmd/paths.rs | 1 | next's (shatai transform on outlines)
crates/engine/src/cmd/place_text.rs | 1 | next's `add_flow_frame` (used by autoflow)
crates/engine/src/cmd/preflight.rs | 2 | next's overset/unplacedStory issue (its `overset_location` already applies the parent transform main's #738 fix adds); next's two test modules kept with main's
crates/engine/src/cmd/scripts.rs | 1 | combined: next's `in_undo_step = false` (#406) + main's full rollback of a failed script (#709)
crates/engine/src/cmd/style.rs | 14 | param docs next's (gradient swatch.create, swatch stops, model colours); create_para next's; rename_style main's structure (rename entry, then `redirect_style_refs`), redirect has next's full reference set (cells, defaults, notes, TOC) + main's never-based-on-it
crates/engine/src/cmd/text.rs | 10 | main's selectSentence/Paragraph/Story + select_around; next's selectionAttrs (mixed) + main's openTypeFeatures/type.feature; main's comments; tracked typing: next's `reserve_command_text` + main's `insert_format_at`; empty-paragraph mark formatting main's (with `
crates/engine/src/cmd/thread.rs | 1 | next's `spread_param(p, "text.thread")`
crates/engine/src/dtd.rs | 1 | next's linear, depth-bounded `expand_parameter_entities` with main's budget (input + 1 MiB, `MAX_EXPANDED_BYTES`) and message ("expand the DTD beyond"); 16 MiB constant removed; both sides' tests pass on message
crates/engine/src/guard.rs | 2 | main's whole-transaction snapshot (docs, active, journal; #742) + next's `in_undo_step` restore; tests both
crates/engine/src/lib.rs | 5 | LoadedGraphic doc next's; next's `new_document_preview`; execute: main's `discard_stale_find_scope()` before next's nested-undo run; modules both (tests_autosize, tests_file_guard, tests_params, tests_roots)
crates/engine/src/recovery.rs | 1 | next's test (superset of main's assertion)
crates/engine/src/tests.rs | 4 | moved tests deduplicated (identical on both sides); next's preflight and direct-selection/kerning tests + main's style-delete, locked-frame and baseline-fit tests
crates/engine/src/tests_idml.rs | 3 | main's order (drop cap and margins tests identical on both sides, once each)
crates/ui-egui/src/canvas.rs | 3 | next's screen_options/DisplayKey block and tests kept; two tests that auto-merge had added twice (parent_guides_on_a_page_are_not_picked_there, baseline_grid_lines_are_the_ones_on_the_page) kept once; main's `typing`/`screen_at`/`click` helpers and its tests clicks
crates/ui-egui/src/control.rs | 3 | main's `count` check and pending budget (control queue + synthetic queue); exact-budget test runs both sides' cases (click 255 on 9,492 pending; drag 9492×255)
crates/ui-egui/src/cursors.rs | 1 | main's (same Pen cursor set)
crates/ui-egui/src/dialogs.rs | 14 | dialog body (newDocument … alert match) is next's text, with main's Find/Change scope reset (`set_field`, `reset_find_scope`, `find_change_params`) and main's Create Guides / Margins and Columns arms ported in; `Dialog::new` ruby section (next) + main's `set_fi
crates/ui-egui/src/i18n.rs | 7 | ka and pl modules, languages, statics and lookups both; `category_first` covers uk, ru, pl, ka and `count_label` keeps next's Czech plurals; shared TABLE union; next's duplicate rows for Auto, Number:, Gutter:, Top:, Bottom:, Inside:, Outside:, Left:, Right: dropped
crates/ui-egui/src/i18n/ar.rs | 2 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/it.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/ja.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/pt_br.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/i18n/uk.rs | 1 | union of rows, no duplicate keys
crates/ui-egui/src/icons.rs | 2 | both tests (main's typography icon, next's distribute icons)
crates/ui-egui/src/lib.rs | 11 | UiState: next's tabs_panel + main's last_color/last_gradient; `cursors` field once; next's SVG paste and paste-on-spread-in-view; next's extensionless document open; opens_as_document next's comment; tests both (next's control bar / key-name tests, main's rich black
crates/ui-egui/src/menus.rs | 15 | app.language doc next's text with pl and ka; UI_COMMANDS both (next's Tabs, Toggle Presentation, Apply None text; main's panel commands, Apply Color, Apply Gradient); Edit › Interface Language stays out (next moved it to Preferences); Type menu main's order with
crates/ui-egui/src/panels/glyphs.rs | 1 | next's (already has main's scroll-bar fix); the scroll-bar test module auto-merge had added twice kept once
crates/ui-egui/src/panels/layers.rs | 3 | next's drag-and-drop `object_rows`, with main's features ported into it: selection reveal (layer opens, row scrolls into view once), selected rows highlighted (also a group whose member is selected), double-click rename in place (`object.rename` queued like
crates/ui-egui/src/panels/mod.rs | 6 | tabs + typography modules and color_panel_tests; SelInfo has wrap_side/wrap_contour and wrap_offsets (offsets from the graphic's own wrap when it is selected); next's swatch_picker returning the chip response; next's content_selection_tests
crates/ui-egui/src/panels/pages.rs | 1 | next's (parents dragged by id)
crates/ui-egui/src/panels/properties.rs | 4 | next's swatch popup (Apply To, Tint); main's four wrap offsets then next's Wrap To / Contour Type; test fixtures main's (`..Default::default()`, no unused builder)
crates/ui-egui/src/panels/swatches.rs | 3 | main's Delete Swatch button + next's New Swatch comment; next's draggable rows; click: main's PICKED + fill/stroke in front, with next's no-apply on double-click
crates/ui-egui/src/toolbar.rs | 2 | main's Apply Color / Gradient / None wells and functions; next's apply_none doc line
crates/compose/src/lib.rs | 5 | next's line loop kept (mark_leading + last_line_mark, wrap segments/carry, grid gyoudori); main's mark-chars base_leading block (auto-merged) stays beside it. `fits`: next's #106 rule (baseline fit for horizontal frames, full descent for paths, vertical text, footnote
crates/compose/src/tests.rs | 5 | next's tests (tombstone set, sliver/one-sided/contour/clipping wrap tests, borders, lists, kenten, grid, anchored wrap, balance, shaped frames) plus main's an_empty_last_paragraph_isnt_overset; main's wrap_object_beside_one_narrow_column_leaves_the_other_alone re-ad
crates/doc/src/assets.rs | 1 | main's doc comment (same meaning)
crates/doc/src/build.rs | 3 | parent_page_for: next's parent_page_for_side (RTL-aware); single_sided_page_shows_first_parent_page test kept once, at main's position
crates/doc/src/item.rs | 1 | next's rotated_group_bounds_follow_the_children_outlines test kept
crates/doc/src/lib.rs | 1 | next's kerning_increment field kept; main's "Bulleted & Numbered" wording
crates/doc/src/page.rs | 1 | next's outer_page_indices + parent_page_for_side (integration of parent-margins with rtl-master-sides); main's parent_page_index dropped, its only caller (build.rs) uses parent_page_for_side
crates/doc/src/slice.rs | 5 | extract: next's `marked()` (get-based, fix_notes/fix_endnotes/fix_marks; main's version indexed slices and could panic); insert_story: main's take() limit on endnote/editorial payload copies with next's id comment, redundant `let ne`/`let nn` dropped; main's excess_note
crates/geom/src/corners.rs | 1 | next's box_outline_rounds_only_closed_corners test kept
crates/render/src/damage.rs | 1 | next's wrapping-anchored-object damage test kept
crates/render/src/fx.rs | 2 | feather: next's choke/corners sigma+join inside main's structure (body and clip at device resolution, with_filters(.., None)); inner glow centre: next's blend `mix` with main's clip argument (bp, xf)
crates/render/src/lib.rs | 3 | next's layer comment; next's front baseline grid draw after items; gradient match on g.kind (main's tuple scrutinee did not match the single-pattern arms)
crates/render/src/text.rs | 5 | paint_glyphs: main's paint_stroke closure structure with next's stroke overprint (overprinting helper, stroke `(TextPaint, bool)`); callers pass next's overprint_fill/overprint_stroke
crates/render/tests/placed_pdf.rs | 1 | main's `near` helper version
crates/tools/src/lib.rs | 1 | main's (PenConvert already declared below, avoids a duplicate variant)
crates/tools/src/pen.rs | 1 | main's module doc
crates/tools/src/select.rs | 1 | next's Drag::Corner variant (live corners) kept
crates/tools/src/tests.rs | 4 | next's tests (content drag, live corners, table border drag, eyedropper matchFrom, fitting handles, pen cursors once); eyedropper_ignores_inactive keeps next's samples_image check (main's exact-JSON compare lacks matchFrom) with main's `..Default::default()` Asset lit
crates/tools/src/text.rs | 2 | next's table border drag (BorderDrag, border_at) kept, then main's comment on locked text frames
crates/tools/src/xform.rs | 2 | main's explicit `Vec<&Item>` for shown children; next's eyedropper matchFrom (integration 796e9d713)
Cargo.toml | 2 | main's craft-pdf workspace dep added (craft-print stays once, in next's craft-libs block); [patch.crates-io] keeps next's winit (rust-windowing #4694 backport) and adds main's krilla patch; main's skylartaylor winit left out (see UNSURE 1)
Cargo.lock | 1 | union: next's craft-atomic and craft-cms entries plus main's craft-pdf entry; needs `cargo` normalisation
README.md | 1 | Open bullet combines INDD import via indd-utils (next) and editable PowerPoint export (main); main's paragraph break kept
contributors/people.toml | 1 | both people kept (switch87 from next, Nmarello from main)
apps/designcraft-cli/src/main.rs | 4 | next's `Export` enum dispatch kept; main's .pptx export added as `Export::Pptx` (run prints slides and warnings, script runs file.exportPptx); main's `--pdf-options` null-as-{} parse; usage lines list .pptx
apps/designcraft/src/main.rs | 3 | `startup.leave()` right after `app.ui` (main #380) and next's macOS `sync_movable` kept after the IME discard; next's Apple Events install kept; main's macOS Dock Quit `with_close_requested_on_terminate` block left out (needs the skylartaylor winit; UNSURE 1)
crates/fonts/src/fontdb.rs | 9 | FONT6 aliases (next) combined with #911 WWS names (main): ScannedFace and both CatalogEntry constructors carry `wws` and `aliases`; `canonical_family` falls back to WWS family names; `exact_style_traits` canonicalises then tries typographic, then WWS names (`named_st
crates/format/src/lib.rs | 1 | tests: both sides kept (next's r7a nullable-default tests; main's oversized ZIP entry/asset/entry-count tests)
crates/idml/src/import.rs | 11 | main's bounded `Package` reader under next's `import_idml_report_with_previews` (metadata read through `pkg.part`); next's `tab_list_repaired` kept; ruler origin: next's `settings.ruler_origin`, and main's guide import reads it (main's private `RulerOrigin` enum and
crates/idml/src/tests.rs | 6 | item-level union: all next tests plus main's new ones (ruler guides, package limits, CJK leading model, liquid page rules module, mojikumi); no test dropped
crates/mcp/src/backend.rs | 1 | test comment merged from both
crates/pdf/src/tests.rs | 1 | tests: both sides kept
crates/pdf/src/text.rs | 4 | next's (skew `tan`, cluster `start`, ruby overprint warning); main had no change here beyond base
crates/textimport/src/docx.rs | 5 | next's (ListCounter integration for list levels, page-break test position); main's side was the older form of the same code
crates/epub/src/lib.rs | 30 | non-test code is next's (StoryWriter holds img_src/images/no_alt/heading_ids; covers main's #787/#791/#782 fixes, plus #314 group transforms, anchored images in images_without_alt, endnote story skipped in the TOC); tests: next's set plus main's extra css_weight_style a
docs/control-protocol.md | 2 | next's rows (ui.paste, count 1–255, documentGrid) and wording
docs/file-format-parity.md | 1 | rows combined (next's ICC notes, main's TIFF indexed colour)
docs/gaps.md | 2 | status change notes unioned; Flex Layout removed from missing (main implemented it), next's Parent Options sentence kept
docs/localization-parity.md | 4 | Polish and Georgian rows; 5 languages beyond the twelve; file list includes cs and ka; both history rows
docs/roadmap.md | 1 | M1 next's (#186 fixed on next), M2 main's IME wording
docs/target-app-parity.md | 6 | next's status line; File formats row next's, UI/UX row main's (IME no longer failing); UI line next's plus main's Swatches detail; one Page tool line (main's fuller one); Load styles and main's fuller Pathfinder line both kept, main's duplicate short Pathfinder line r
docs/ui-parity.md | 1 | IME row main's, Font menu row next's
i18n/fr.rs: five rows dropped that main's shared table now has (Row, Open Path, Flex Layout, Current Page Number, Rulers).
337 lines
14 KiB
Rust
337 lines
14 KiB
Rust
//! Pen tool (P): click for corner points, drag for smooth points, click the first point to close,
|
|
//! Enter/Esc (or switching tools) to finish an open path. Each anchor is its own undo step.
|
|
//! Between paths, a click on a selected path's anchor deletes it and a click on its outline adds an
|
|
//! anchor; clicking an end point of an open path continues that path from there (dragging from it
|
|
//! first reshapes its direction lines). The cursor shows which.
|
|
|
|
use designcraft_doc::{ItemId, SpreadRef};
|
|
use designcraft_geom::{BezPath, Point};
|
|
use serde_json::{Value, json};
|
|
|
|
use crate::anchors::segment_at;
|
|
use crate::select::anchor_at_in;
|
|
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, spread_json};
|
|
|
|
#[derive(Default)]
|
|
pub struct PenTool {
|
|
/// The path being drawn: (item id once created, spread, anchors in spread coords).
|
|
path: Option<u64>,
|
|
spread: Option<SpreadRef>,
|
|
/// Anchors as (p, in, out) in spread coordinates.
|
|
anchors: Vec<(Point, Point, Point)>,
|
|
dragging: bool,
|
|
hover: Point,
|
|
/// Smart guides in canvas coordinates, as `snap_point` returned them.
|
|
guides: Vec<Overlay>,
|
|
/// Continuing an existing path: the subpath the new anchors go on.
|
|
subpath: Option<usize>,
|
|
/// The press was on the continued path's end point: a drag reshapes its direction lines
|
|
/// instead of adding an anchor.
|
|
editing_end: bool,
|
|
/// The press on the end point has been dragged.
|
|
end_moved: bool,
|
|
/// Continuing from the subpath's first anchor: `anchors` run in drawing order, the reverse
|
|
/// of the path's, and new anchors go before its first one.
|
|
from_start: bool,
|
|
}
|
|
|
|
/// An end point of an open path under canvas point `p`: (item, subpath, whether it is the last
|
|
/// anchor). The selection is checked first, then the frontmost item under the pointer.
|
|
fn endpoint_at(cx: &ToolContext, p: Point) -> Option<(ItemId, usize, bool)> {
|
|
let tol = cx.tol(6.0);
|
|
let mut ids = cx.selection.items.clone();
|
|
if let Some((_, id)) = cx.hit(p)
|
|
&& !ids.contains(&id)
|
|
{
|
|
ids.push(id);
|
|
}
|
|
for id in ids {
|
|
let Some(it) = cx.doc.item(id) else { continue };
|
|
if it.locked || it.is_group() || !matches!(it.content, designcraft_doc::Content::Unassigned) {
|
|
continue;
|
|
}
|
|
let Some(xf) = cx.item_canvas_xf(id).map(|m| m * it.xf) else { continue };
|
|
for (si, sp) in it.path.subpaths.iter().enumerate() {
|
|
if sp.closed {
|
|
continue;
|
|
}
|
|
let (Some(first), Some(last)) = (sp.anchors.first(), sp.anchors.last()) else { continue };
|
|
if (xf * last.p - p).hypot() <= tol {
|
|
return Some((id, si, true));
|
|
}
|
|
if (xf * first.p - p).hypot() <= tol {
|
|
return Some((id, si, false));
|
|
}
|
|
}
|
|
}
|
|
None
|
|
}
|
|
|
|
fn anchor_json(a: &(Point, Point, Point)) -> Value {
|
|
json!({"p": [a.0.x, a.0.y], "in": [a.1.x, a.1.y], "out": [a.2.x, a.2.y]})
|
|
}
|
|
|
|
/// What a pen click at the pointer does instead of placing an anchor.
|
|
#[derive(Debug, PartialEq)]
|
|
enum Hover {
|
|
Place,
|
|
/// Close the path being drawn (the pointer is on its first anchor).
|
|
Close,
|
|
/// Delete anchor (subpath, anchor) of a selected path.
|
|
Delete(u64, usize, usize),
|
|
/// Add an anchor on a selected path's outline.
|
|
Add(ItemId),
|
|
/// Continue subpath `.1` of open path `.0` from its last (`.2`) or first anchor.
|
|
Continue(ItemId, usize, bool),
|
|
}
|
|
|
|
impl PenTool {
|
|
/// What a click at canvas point `p` does.
|
|
fn hover_at(&self, cx: &ToolContext, p: Point) -> Hover {
|
|
if let Some(sr) = self.spread {
|
|
if self.anchors.len() >= 2
|
|
&& let Some(first) = self.anchors.first()
|
|
&& (first.0 - cx.layout.to_spread(sr, p)).hypot() <= cx.tol(6.0)
|
|
{
|
|
return Hover::Close;
|
|
}
|
|
return Hover::Place;
|
|
}
|
|
if !self.anchors.is_empty() {
|
|
return Hover::Place;
|
|
}
|
|
if let Some((id, si, at_end)) = endpoint_at(cx, p) {
|
|
return Hover::Continue(id, si, at_end);
|
|
}
|
|
let ids = &cx.selection.items;
|
|
if let Some((id, si, ai, None)) = anchor_at_in(cx, ids, p) {
|
|
return Hover::Delete(id, si, ai);
|
|
}
|
|
segment_at(cx, ids, p).map_or(Hover::Place, Hover::Add)
|
|
}
|
|
|
|
fn finish(&mut self) -> Vec<Action> {
|
|
self.path = None;
|
|
self.spread = None;
|
|
self.anchors.clear();
|
|
self.dragging = false;
|
|
self.guides.clear();
|
|
self.subpath = None;
|
|
self.editing_end = false;
|
|
self.end_moved = false;
|
|
self.from_start = false;
|
|
vec![]
|
|
}
|
|
|
|
/// Start continuing subpath `si` of `id` from its last (`at_end`) or first anchor: the anchors
|
|
/// so far are its other end and the end point, in spread coordinates.
|
|
fn continue_from(&mut self, cx: &ToolContext, id: ItemId, si: usize, at_end: bool) -> Vec<Action> {
|
|
let (Some(it), Some(loc)) = (cx.doc.item(id), cx.doc.find(id)) else { return vec![] };
|
|
let Some(sp) = it.path.subpaths.get(si) else { return vec![] };
|
|
let (Some(first), Some(last)) = (sp.anchors.first(), sp.anchors.last()) else { return vec![] };
|
|
let xf = cx.doc.parent_xf(&loc) * it.xf;
|
|
let at = |a: &designcraft_geom::Anchor, flip: bool| {
|
|
let (i, o) = if flip { (a.h_out, a.h_in) } else { (a.h_in, a.h_out) };
|
|
(xf * a.p, xf * i, xf * o)
|
|
};
|
|
// From the first anchor the anchors run backwards (handles swapped); new ones are added
|
|
// before the first, so the path keeps its direction (and its arrowheads their ends).
|
|
let (other, end) = if at_end { (at(first, false), at(last, false)) } else { (at(last, true), at(first, true)) };
|
|
self.path = Some(id.0);
|
|
self.subpath = Some(si);
|
|
self.spread = Some(loc.spread);
|
|
self.anchors = vec![other, end];
|
|
self.editing_end = true;
|
|
self.end_moved = false;
|
|
self.dragging = true;
|
|
self.from_start = !at_end;
|
|
vec![]
|
|
}
|
|
|
|
/// Anchor `a` (drawing order) in the path's order.
|
|
fn path_anchor(&self, a: &(Point, Point, Point)) -> (Point, Point, Point) {
|
|
if self.from_start { (a.0, a.2, a.1) } else { *a }
|
|
}
|
|
|
|
/// Shift constrains first. The stored point is the snapped spread point. Guides are already canvas.
|
|
fn snap_click(&mut self, cx: &ToolContext, spread: SpreadRef, mut p: Point, shift: bool) -> Point {
|
|
if shift && let Some(last) = self.anchors.last() {
|
|
p = last.0 + designcraft_geom::constrain_angle(p - last.0, 45.0);
|
|
}
|
|
let (p, guides) = crate::snap::snap_point(cx, spread, p);
|
|
self.guides = guides;
|
|
p
|
|
}
|
|
|
|
fn commit_anchor(&mut self) -> Vec<Action> {
|
|
let Some(sr) = self.spread else { return vec![] };
|
|
let Some(last) = self.anchors.last() else { return vec![] };
|
|
match self.path {
|
|
None if self.anchors.len() >= 2 => {
|
|
let anchors: Vec<Value> = self.anchors.iter().map(anchor_json).collect();
|
|
vec![Action::Exec("path.create".into(), json!({"spread": spread_json(sr), "anchors": anchors, "closed": false}))]
|
|
}
|
|
Some(id) => {
|
|
let mut p = json!({"id": id, "anchor": anchor_json(&self.path_anchor(last))});
|
|
if let Some(si) = self.subpath {
|
|
p["subpath"] = json!(si);
|
|
}
|
|
if self.from_start {
|
|
p["at"] = json!("start");
|
|
}
|
|
vec![Action::Exec("path.appendAnchor".into(), p)]
|
|
}
|
|
None => vec![],
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Tool for PenTool {
|
|
fn id(&self) -> &'static str {
|
|
"pen"
|
|
}
|
|
|
|
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
|
let Some((sr, sp)) = cx.layout.spread_at(ev.pos) else {
|
|
self.guides.clear();
|
|
return vec![];
|
|
};
|
|
self.hover = ev.pos;
|
|
// The pen continues on the spread where the path started.
|
|
let sp = match self.spread {
|
|
Some(s) if s != sr => cx.layout.to_spread(s, ev.pos),
|
|
_ => sp,
|
|
};
|
|
let snap_spread = self.spread.unwrap_or(sr);
|
|
// Pick up the item id created by path.create (the newest selected path).
|
|
if self.path.is_none() && self.anchors.len() >= 2 {
|
|
self.path = cx.selection.items.last().map(|i| i.0);
|
|
}
|
|
match ev.kind {
|
|
PointerKind::Move => {
|
|
let p = self.snap_click(cx, snap_spread, sp, ev.mods.shift);
|
|
self.hover = cx.layout.to_canvas(snap_spread, p);
|
|
vec![]
|
|
}
|
|
PointerKind::Down => {
|
|
match self.hover_at(cx, ev.pos) {
|
|
Hover::Close => {
|
|
let out = match self.path {
|
|
Some(id) => {
|
|
let mut p = json!({"id": id});
|
|
if let Some(si) = self.subpath {
|
|
p["subpath"] = json!(si);
|
|
}
|
|
vec![Action::Exec("path.close".into(), p)]
|
|
}
|
|
None => vec![],
|
|
};
|
|
self.finish();
|
|
return out;
|
|
}
|
|
Hover::Continue(id, si, at_end) => return self.continue_from(cx, id, si, at_end),
|
|
Hover::Delete(id, si, ai) => {
|
|
return vec![Action::Exec("path.deleteAnchor".into(), json!({"id": id, "subpath": si, "anchor": ai}))];
|
|
}
|
|
Hover::Add(id) => {
|
|
return vec![Action::Exec("path.addAnchor".into(), json!({"id": id.0, "at": [sp.x, sp.y], "tolerance": cx.tol(5.0)}))];
|
|
}
|
|
Hover::Place => {}
|
|
}
|
|
let p = self.snap_click(cx, snap_spread, sp, ev.mods.shift);
|
|
if self.anchors.is_empty() {
|
|
self.spread = Some(sr);
|
|
}
|
|
self.anchors.push((p, p, p));
|
|
self.dragging = true;
|
|
vec![]
|
|
}
|
|
PointerKind::Drag => {
|
|
self.end_moved |= self.editing_end;
|
|
if let Some(a) = self.anchors.last_mut() {
|
|
// Smooth point: out handle follows the pointer, in handle mirrors it.
|
|
a.2 = sp;
|
|
a.1 = a.0 - (sp - a.0);
|
|
}
|
|
vec![]
|
|
}
|
|
PointerKind::Up => {
|
|
if !self.dragging {
|
|
return vec![];
|
|
}
|
|
self.dragging = false;
|
|
// The continued path's end point: a drag set its direction lines.
|
|
if std::mem::take(&mut self.editing_end) {
|
|
let (Some(id), Some(si), Some(&(p, drawn_in, drawn_out))) = (self.path, self.subpath, self.anchors.last()) else {
|
|
return vec![];
|
|
};
|
|
if !std::mem::take(&mut self.end_moved) || (drawn_out - p).hypot() < 1e-9 {
|
|
return vec![];
|
|
}
|
|
let (_, h_in, h_out) = self.path_anchor(&(p, drawn_in, drawn_out));
|
|
let anchor = if self.from_start { "first" } else { "last" };
|
|
return vec![Action::Exec(
|
|
"path.setAnchor".into(),
|
|
json!({"id": id, "subpath": si, "anchor": anchor, "in": [h_in.x, h_in.y], "out": [h_out.x, h_out.y]}),
|
|
)];
|
|
}
|
|
self.commit_anchor()
|
|
}
|
|
_ => vec![],
|
|
}
|
|
}
|
|
|
|
fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
|
|
match key {
|
|
ToolKey::Enter | ToolKey::Escape => {
|
|
let had = !self.anchors.is_empty();
|
|
self.finish();
|
|
if had { vec![Action::Exec("selection.set".into(), json!({"ids": []}))] } else { vec![] }
|
|
}
|
|
_ => vec![],
|
|
}
|
|
}
|
|
|
|
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
|
let mut out = Vec::new();
|
|
let Some(sr) = self.spread else {
|
|
out.extend(self.guides.iter().cloned());
|
|
return out;
|
|
};
|
|
let xf = cx.layout.xf(sr);
|
|
if let Some(last) = self.anchors.last()
|
|
&& !self.dragging
|
|
{
|
|
// Rubber band to the pointer.
|
|
out.push(Overlay::Line { a: xf * last.0, b: self.hover, color: [79, 153, 255], dashed: true });
|
|
}
|
|
if self.path.is_none() && self.anchors.len() == 1 {
|
|
let a = self.anchors[0];
|
|
out.push(Overlay::Line { a: xf * a.1, b: xf * a.2, color: [79, 153, 255], dashed: false });
|
|
}
|
|
if self.dragging
|
|
&& let Some(a) = self.anchors.last()
|
|
{
|
|
out.push(Overlay::Line { a: xf * a.1, b: xf * a.2, color: [79, 153, 255], dashed: false });
|
|
let _ = BezPath::new();
|
|
}
|
|
// Guides are already canvas. Do not run them through the spread transform again.
|
|
out.extend(self.guides.iter().cloned());
|
|
out
|
|
}
|
|
|
|
fn cursor(&self, cx: &ToolContext, p: Point, _m: Mods) -> Cursor {
|
|
match self.hover_at(cx, p) {
|
|
Hover::Place => Cursor::Pen,
|
|
Hover::Close => Cursor::PenClose,
|
|
Hover::Continue(..) => Cursor::PenContinue,
|
|
Hover::Delete(..) => Cursor::PenDelete,
|
|
Hover::Add(_) => Cursor::PenAdd,
|
|
}
|
|
}
|
|
|
|
fn busy(&self) -> bool {
|
|
!self.anchors.is_empty()
|
|
}
|
|
}
|