GitCorner

Code

ossartcraftvectorcraft🌐
2bc41aeb8602
use super::{Drag, Mods, PenPose, Point, PointerEvent, PointerKind, Pos2, StylusFeed, Ui, VectorcraftApp, Xf, widgets};

/// Whether drag `d` is a press the tool holds. Every other drag (panning, zooming, turning the
/// view, a touch gesture, Presentation Mode) never reaches the tool, so its hover ends with it.
pub(super) fn tool_holds(d: Drag) -> bool {
    matches!(d, Drag::Tool | Drag::Art)
}

/// What a hover depends on besides the pointer's screen position.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct HoverContext {
    /// The active tool: a tool switched to under a still pointer is hovered at once.
    pub(super) tool: &'static str,
    /// The canvas, and the view's centre, zoom and rotation.
    pub(super) canvas: egui::Rect,
    pub(super) center: Point,
    pub(super) zoom: f64,
    pub(super) rotation: f64,
    /// A pen turning in place changes a Bristle tip even when its pointer stays still.
    pub(super) pen: Option<PenPose>,
    /// The active document's id and revision (which moves with every edit, undo and selection
    /// change).
    pub(super) doc: Option<(u64, u64)>,
}

/// Clear canvas interaction state before a tab transfer takes ownership of the artwork drag.
pub(crate) fn end_document_drag(ctx: &egui::Context) {
    ctx.data_mut(|d| {
        d.remove::<Drag>(drag_id());
        d.remove::<Pos2>(drag_pos_id());
    });
}

/// Whether a Selection tool move has left the canvas ([`drag_art_out`]) and still waits there.
pub(crate) fn art_out(ctx: &egui::Context) -> bool {
    matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Art))
}

/// Temp-memory key for the active canvas drag state.
pub(super) fn drag_id() -> egui::Id {
    egui::Id::unique("canvas-drag")
}

/// Where the pointer was last seen during a press on the canvas.
pub(super) fn drag_pos_id() -> egui::Id {
    egui::Id::unique("canvas-drag-pos")
}

/// The layer the canvas was last drawn on: a release over another layer is over a panel (#2826).
pub(super) fn drag_layer_id() -> egui::Id {
    egui::Id::unique("canvas-drag-layer")
}

/// Whether `p` is over the canvas itself, not a panel or a floating window over it.
pub(super) fn on_canvas(ui: &Ui, resp: &egui::Response, p: Pos2) -> bool {
    resp.rect.contains(p) && ui.clip_rect().contains(p) && ui.ctx().layer_id_at(p).is_none_or(|l| l == resp.layer_id)
}

/// The document point last sent to the tool as a drag during [`Drag::Tool`]; none until the press
/// has dragged.
pub(super) fn tool_drag_doc_id() -> egui::Id {
    egui::Id::unique("canvas-tool-drag-doc")
}

/// The document point of the press that began [`Drag::Tool`], sent to the tool as its Down.
pub(super) fn tool_press_doc_id() -> egui::Id {
    egui::Id::unique("canvas-tool-press-doc")
}

/// Whether the tool should get another drag event, and if so records `p` as the last position
/// sent: the pointer moved this frame, or its document position changed without a delta (#834).
/// egui's frame delta is zero when some Wayland compositors coalesce motion until release, and in
/// the frame the pointer comes back into the window after leaving it (`PointerGone` forgot where
/// it was), though it is somewhere new; judged on the delta alone, the preview stayed behind.
pub(super) fn tool_drag_moved(ui: &Ui, xf: &Xf, p: Pos2, pointer: &egui::PointerState) -> bool {
    let at = xf.to_doc(p);
    let id = tool_drag_doc_id();
    // Before the press has dragged, the last position the tool got is the press itself: a press
    // held still is not a drag.
    let prev = ui.data(|d| d.get_temp::<Point>(id).or_else(|| d.get_temp::<Point>(tool_press_doc_id())));
    if pointer.delta() == egui::Vec2::ZERO && prev == Some(at) {
        return false;
    }
    ui.data_mut(|d| d.insert_temp(id, at));
    true
}

/// Whether the tool should get another drag event at a pointer held still because Shift, Alt,
/// Cmd/Ctrl, Space or Backtick went down or up (#4711): a scale switches to proportional or from the centre
/// at once. Records `m` and the Backtick state as last seen; only once the press has dragged.
pub(super) fn tool_drag_mods_changed(ui: &Ui, m: Mods, backquote: bool) -> bool {
    let id = egui::Id::unique("canvas-tool-drag-mods");
    let held = (m, backquote);
    let (dragged, last) = ui.data(|d| (d.get_temp::<Point>(tool_drag_doc_id()).is_some(), d.get_temp::<(Mods, bool)>(id)));
    ui.data_mut(|d| d.insert_temp(id, held));
    dragged && last.is_some_and(|l| l != held)
}

/// Whether Backtick is held at the end of this frame, and whether it was at the end of the frame
/// before (`None` before the first). The canvas records it once a frame.
pub(super) fn backquote_seen(ui: &Ui) -> (bool, Option<bool>) {
    let id = egui::Id::unique("canvas-backquote-seen");
    let now = ui.input(|i| i.key_down(egui::Key::Backtick));
    let before = ui.data_mut(|d| {
        let before = d.get_temp::<bool>(id);
        d.insert_temp(id, now);
        before
    });
    (now, before)
}

/// Whether Backtick was held when `button` went up in this frame, with `before` its state at the end
/// of the frame before ([`backquote_seen`]). Its state as the frame began is the opposite of its
/// first press or release in the frame; when the window lost the focus first (which lets go of every
/// key without a release), it is `before`; with neither, it is its state now. The frame's presses,
/// releases and focus losses before the button-up then apply in the order they came. Without a
/// button-up in this frame, its state now.
pub(super) fn backquote_at_release(ui: &Ui, button: egui::PointerButton, before: Option<bool>) -> bool {
    ui.input(|i| {
        let now = i.key_down(egui::Key::Backtick);
        // A press or release of Backtick (`Some(pressed)`), or a focus loss (`None`).
        let step = |e: &egui::Event| match e {
            egui::Event::Key { key: egui::Key::Backtick, pressed, repeat: false, .. } => Some(Some(*pressed)),
            egui::Event::WindowFocused(false) => Some(None),
            _ => None,
        };
        let Some(up) = i.events.iter().position(|e| matches!(e, egui::Event::PointerButton { button: b, pressed: false, .. } if *b == button)) else {
            return now;
        };
        let start = match i.events.iter().find_map(step) {
            Some(Some(down)) => !down,
            Some(None) => before.unwrap_or(now),
            None => now,
        };
        i.events[..up].iter().filter_map(step).fold(start, |_, s| s.unwrap_or(false))
    })
}

/// The pen pressure (0..1) of the press in progress: the force of this frame's pen or touch
/// input, else the pressure in the host's feed while a pen is the pointer that moved last
/// ([`crate::Services::stylus`]: [`StylusFeed::press`] for a new press, [`StylusFeed::held`]
/// after it), else the last one seen since the press (`pressed`: a new press, whose mouse has none
/// until a pen reports it). A mouse presses fully (1).
pub(super) fn pen_pressure(ui: &Ui, app: &VectorcraftApp, pressed: bool) -> f32 {
    let stylus = app.services.stylus.as_ref();
    let id = egui::Id::unique("canvas-pressure");
    let force = ui.input(|i| {
        i.events.iter().rev().find_map(|e| match e {
            egui::Event::Touch { force: Some(f), .. } if f.is_finite() => Some(f.clamp(0.0, 1.0)),
            _ => None,
        })
    });
    let force = force.or_else(|| stylus.and_then(if pressed { StylusFeed::press } else { StylusFeed::held }));
    let p = force.or_else(|| if pressed { None } else { ui.data(|d| d.get_temp::<f32>(id)) }).unwrap_or(1.0);
    ui.data_mut(|d| d.insert_temp(id, p));
    p
}

/// The tilt and rotation of the pen in the host's feed while a pen is the pointer that moved last
/// ([`crate::Services::stylus`], [`StylusFeed::pose`]), its tilt turned onto the page
/// ([`pose_on_page`]); `None` for a mouse, or a pen that reads neither.
pub(super) fn pen_pose(app: &VectorcraftApp, xf: &Xf) -> Option<PenPose> {
    app.services.stylus.as_ref().and_then(StylusFeed::pose).map(|q| pose_on_page(q, xf))
}

/// The tilt and rotation for one move: the pose the host's feed kept for that move
/// ([`frame_moves`]), turned onto the page and `None` when the pen read neither, else the latest
/// ([`pen_pose`]).
pub(super) fn move_pose(app: &VectorcraftApp, xf: &Xf, kept: Option<PenPose>) -> Option<PenPose> {
    match kept {
        Some(q) => (q != PenPose::default()).then(|| pose_on_page(q, xf)),
        None => pen_pose(app, xf),
    }
}

/// `pose` with its tilt, given in screen axes, turned into the document's (the view rotated by
/// Rotate View): the pen leans the same way on the page as on the screen. The rotation is kept.
pub(crate) fn pose_on_page(pose: PenPose, xf: &Xf) -> PenPose {
    let tilt = pose.tilt.map(|[x, y]| {
        // The direction the pen leans in, as `to_doc` turns a screen offset.
        let (tx, ty) = (f64::from(x).to_radians().tan(), f64::from(y).to_radians().tan());
        let (sn, cs) = xf.rot.sin_cos();
        let (u, v) = (tx * cs + ty * sn, -tx * sn + ty * cs);
        [u.atan().to_degrees() as f32, v.atan().to_degrees() as f32]
    });
    PenPose { tilt, ..pose }
}

/// One pointer move of a frame: its position, and the pressure and the tilt and rotation kept for
/// it, if any ([`frame_moves`]).
pub(super) type FrameMove = (Pos2, Option<f32>, Option<PenPose>);

/// The positions this frame's pointer moves passed through before its last one, each with the
/// pen force a touch event gave just before it, or the pressure the host's feed kept for that move
/// ([`StylusFeed::take_moves`], macOS), if any, and the tilt and rotation the feed kept for that
/// move (empty when the pen read neither), if any. The last move is the pointer's position; the
/// tilt and rotation the feed kept for it come second, if any. A mouse's moves count too, with no
/// pressure: a fast mouse stroke otherwise keeps one position a frame, a sample every few pixels,
/// too few for a low Fidelity to follow the hand (#3328). With `release`, the moves stop at that
/// button's button-up in this frame, if it came: the moves after it are hover, and the button-up's
/// position is the pointer's. The last move before it is left out only when it is at that
/// position; its tilt and rotation come second either way.
pub(super) fn frame_moves(ui: &Ui, stylus: Option<&StylusFeed>, release: Option<egui::PointerButton>) -> (Vec<FrameMove>, Option<PenPose>) {
    let samples = stylus.map(StylusFeed::take_moves).unwrap_or_default();
    ui.input(|i| {
        // How many of the frame's moves came before the button-up, and where it came, if it came.
        let before_up = release.and_then(|b| {
            i.events.iter().enumerate().find_map(|(k, e)| match e {
                egui::Event::PointerButton { pos, button, pressed: false, .. } if *button == b => {
                    Some((i.events.iter().take(k).filter(|e| matches!(e, egui::Event::PointerMoved(_))).count(), *pos))
                }
                _ => None,
            })
        });
        let mut moves = vec![];
        if i.events.iter().any(|e| matches!(e, egui::Event::Touch { .. })) {
            let mut force = None;
            for e in &i.events {
                match e {
                    egui::Event::Touch { force: Some(f), .. } if f.is_finite() && *f > 0.0 => force = Some(f.clamp(0.0, 1.0)),
                    egui::Event::PointerMoved(p) => moves.push((*p, force, None)),
                    _ => {}
                }
            }
        } else if !samples.is_empty() {
            // The feed's last sample is the last move's: pair them from the end. A lift's 0 is
            // no pressure (the press keeps its last touch).
            let points: Vec<Pos2> = i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some(*p) } else { None }).collect();
            let kept = samples.iter().rev().map(|&(f, q)| ((f > 0.0).then_some(f), Some(q)));
            moves = points.into_iter().rev().zip(kept.chain(std::iter::repeat((None, None)))).map(|(p, (f, q))| (p, f, q)).collect();
            moves.reverse();
        } else {
            moves = i.events.iter().filter_map(|e| if let egui::Event::PointerMoved(p) = e { Some((*p, None, None)) } else { None }).collect();
        }
        // Cut after pairing: the feed's samples pair with every move of the frame.
        // The pointer's position is the button-up's: a last move before it that is elsewhere
        // stays a move. Its tilt and rotation are still the pose.
        let last_pose = match before_up {
            Some((n, up_at)) => {
                moves.truncate(n);
                let pose = moves.last().and_then(|&(_, _, q)| q);
                if moves.last().is_some_and(|&(p, _, _)| p == up_at) {
                    moves.pop();
                }
                pose
            }
            None => moves.pop().and_then(|(_, _, q)| q),
        };
        // A burst of events (a stalled frame) is thinned to a bounded count.
        const MAX: usize = 64;
        if moves.len() > MAX {
            let step = moves.len().div_ceil(MAX);
            moves = moves.into_iter().step_by(step).collect();
        }
        (moves, last_pose)
    })
}

/// The moves of this frame ([`frame_moves`]) the active tool gets before the pointer's position:
/// all of them for a tool that builds a stroke from them ([`vectorcraft_engine::Session::tool_wants_samples`]), none
/// for the others, which get one drag a frame. The moves are read either way, so the host's feed
/// pairs the next frame's with its own. The tilt and rotation the feed kept for the pointer's
/// position come second, for every tool. With `released`, only the moves before the primary
/// button-up count.
pub(super) fn tool_frame_moves(ui: &Ui, app: &VectorcraftApp, released: bool) -> (Vec<FrameMove>, Option<PenPose>) {
    let release = released.then_some(egui::PointerButton::Primary);
    let (moves, last_pose) = frame_moves(ui, app.services.stylus.as_ref(), release);
    (if app.session.tool_wants_samples() { moves } else { vec![] }, last_pose)
}

pub fn mods(m: egui::Modifiers, space: bool) -> Mods {
    Mods { shift: m.shift, alt: m.alt, cmd: m.command, ctrl: m.ctrl, space }
}

/// Whether Space, held with the modifiers `m`, lends the Hand, Rotate View or Zoom tool. While the
/// Type tool edits text, Space types a space, and only Cmd+Space still lends the Zoom tool.
pub(super) fn space_lends_view_tools(app: &VectorcraftApp, m: egui::Modifiers, space: bool) -> bool {
    space && (m.command || !app.session.tool_wants_text())
}

/// Drop the tool press in progress, if any: nothing it began is kept, and the rest of the press
/// does nothing ([`Drag::Gesture`]).
pub(super) fn drop_press(app: &mut VectorcraftApp, ui: &Ui, view: vectorcraft_engine::ViewInfo) {
    match ui.data(|d| d.get_temp::<Drag>(drag_id())) {
        Some(Drag::Tool | Drag::Art) => {
            // The tool drops the press, and a mouse-up returns it to rest with the options it had
            // when the press began. A move waiting over a panel is still live and would otherwise outlive the drag that
            // owns it (#2826).
            let r = app.session.drop_tool_press(view);
            apply_requests(app, r.map(|()| vec![]));
            egui::DragAndDrop::clear_payload(ui.ctx());
        }
        Some(_) => {}
        None => return,
    }
    ui.data_mut(|d| d.insert_temp(drag_id(), Drag::Gesture));
}

/// A Selection tool move dragged off the canvas (to `p`, over a panel) becomes a panel drag of
/// the selected art ([`widgets::PanelDrag::Art`]): the art waits where it last moved on the
/// canvas, and a panel it is released on takes it (the Graphic Styles panel makes a style of it).
/// Back on the canvas, [`Drag::Art`] takes the move up again where the pointer is (#2826).
/// The Direct and Group Selection tools hand over art they move whole too (#4233); a move of
/// anchor points or segments stays a reshape.
pub(super) fn drag_art_out(app: &VectorcraftApp, ui: &Ui, resp: &egui::Response, p: Pos2) -> bool {
    let tool = app.session.tool_id();
    let Some(st) = app.session.active().filter(|_| matches!(tool, "selection" | "directSelection" | "groupSelection")) else { return false };
    // The tool's interaction while it moves (or Alt-copies) the selection.
    let Some(it) = st.interaction.as_ref().filter(|i| i.label == "Move" || i.label == "Copy") else { return false };
    if tool != "selection" && st.selection.objects.iter().any(|id| st.selection.partial(*id).is_some() || st.selection.segments.contains_key(id)) {
        return false;
    }
    // A floating panel in an OS window of its own takes the art too: craft-ui hands that window
    // the pointer while it is over it, and this window sees the pointer go.
    craft_ui::docking::route_app_drag(ui.ctx(), crate::panel_docking::area_id());
    if on_canvas(ui, resp, p) && ui.input(|i| i.pointer.has_pointer()) {
        return false;
    }
    // The art the drag started with: the release rolls the move back to it, and an Alt-copy's
    // copies, selected while it previews, go with that.
    let ids = it.selection.objects.clone();
    widgets::drag_art(ui.ctx(), st.uid, ids);
    true
}

/// A Selection tool move released over a panel: end it before the panels see the release, so a
/// panel that takes the art ([`widgets::PanelDrag::Art`]) takes it where it was, and no move is
/// left open (#2826). The art stays where it last moved while the pointer is over the panel.
pub(crate) fn release_over_panel(app: &mut VectorcraftApp, ctx: &egui::Context) {
    // A floating window's pane, or the main window's while the current window floats, takes the
    // art first.
    super::release_on_noted(app, ctx);
    crate::document_drag::cleanup(app, ctx);
    let art = matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Art));
    // Over a floating panel's own OS window the pointer is gone from this window, and the release
    // comes here later, at a point of this window that may lie on the canvas: that panel takes it.
    let gone_id = drag_id().with("art-gone");
    if !ctx.input(|i| i.pointer.primary_released()) {
        if art {
            let gone = ctx.input(|i| !i.pointer.has_pointer());
            ctx.data_mut(|d| d.insert_temp(gone_id, gone));
        }
        return;
    }
    let gone = ctx.data_mut(|d| d.remove_temp::<bool>(gone_id)).unwrap_or(false);
    let p = ctx.input(|i| i.pointer.interact_pos().or(i.pointer.latest_pos()));
    if !art {
        return;
    }
    let layer = ctx.data(|d| d.get_temp::<egui::LayerId>(drag_layer_id()));
    let on = !gone && p.is_some_and(|p| app.canvas_rect.is_some_and(|r| r.contains(p)) && ctx.layer_id_at(p).is_none_or(|l| Some(l) == layer));
    if on {
        // The canvas's release finishes the move.
        return;
    }
    end_art_move(app, ctx);
}

/// A release in a floating panel's own OS window, during an art drag from the canvas: the move
/// ends before that panel takes the art. The main window would only see it on its next pass.
pub(crate) fn release_art_in_window(app: &mut VectorcraftApp, ctx: &egui::Context) {
    let art = matches!(ctx.data(|d| d.get_temp::<Drag>(drag_id())), Some(Drag::Art));
    if art && ctx.input(|i| i.pointer.primary_released()) {
        end_art_move(app, ctx);
    }
}

/// Roll back the art move dragged off the canvas, and end the canvas's drag; a panel or another
/// window's tiled pane takes the art instead.
pub(crate) fn end_art_move(app: &mut VectorcraftApp, ctx: &egui::Context) {
    // With no document open there is nothing to roll back; the tool still gets its mouse-up.
    let _ = app.session.cancel_interaction();
    let view = app.view_info();
    dispatch(app, &PointerEvent { kind: PointerKind::Up, pos: Point::ZERO, mods: Mods::default(), backquote: false, pressure: 1.0, pen: None }, view);
    ctx.data_mut(|d| {
        d.remove::<Drag>(drag_id());
        d.remove::<bool>(drag_id().with("art-gone"));
    });
}

/// Send a pointer event to the active tool and act on UI requests (dialogs, tool switches).
pub fn dispatch(app: &mut VectorcraftApp, ev: &PointerEvent, view: vectorcraft_engine::ViewInfo) {
    // A press lent to a selection tool (Cmd/Ctrl held) does not use the tool of a held key.
    if ev.kind == PointerKind::Down && app.session.lent_tool_id(&ev.mods).is_none() {
        crate::shortcuts::note_tool_use(app);
    }
    let r = app.session.pointer(ev, view);
    // The artboard the Artboard tool makes active is the active one (the navigator's, the
    // Artboards panel's).
    if app.session.tool_id() == "artboard"
        && let Some(i) = app.session.tool_options()["active"].as_u64().and_then(|i| usize::try_from(i).ok())
        && let Some(v) = app.view_mut()
    {
        v.artboard = i;
    }
    if ev.kind == PointerKind::Down {
        pressed_with(app, app.session.active_index(), ev.pos, app.session.tool_id());
    }
    apply_requests(app, r);
}

/// A press at `pos` in document `index` with tool `tool` (a selection tool) inside an artboard
/// makes it that document's active one (#693), as the Artboard tool's does: Paste in Place and in
/// Front or Back then paste onto it, Align to Artboard aligns to it, and All on Active Artboard
/// selects on it.
fn pressed_with(app: &mut VectorcraftApp, index: Option<usize>, pos: Point, tool: &str) {
    if !vectorcraft_tools::catalog::is_selection_tool(tool) {
        return;
    }
    app.sync_views();
    if let Some(i) = index
        && let Some(board) = app.session.documents().get(i).and_then(|d| d.doc.artboard_at(pos))
        && let Some(v) = app.views.get_mut(i)
    {
        v.artboard = board;
    }
}

/// Act on what a tool event asked the UI for (dialogs, tool switches), or show its error. When an
/// edit the tool committed or ran no longer fits in the action being recorded, the edit stays and
/// the status bar names the limit ([`crate::panels::actions::after_journaled_edit`]).
pub fn apply_requests(app: &mut VectorcraftApp, r: vectorcraft_engine::Result<Vec<vectorcraft_engine::UiRequest>>) {
    match r {
        Ok(reqs) => {
            for r in reqs {
                match r {
                    vectorcraft_engine::UiRequest::Dialog(kind, p) => crate::dialogs::open_tool_dialog(app, &kind, p),
                    vectorcraft_engine::UiRequest::Panel(panel) => activate_panel(app, &panel),
                    vectorcraft_engine::UiRequest::SwitchTool(t) => app.select_tool(&t),
                    vectorcraft_engine::UiRequest::Status(msg) => app.status(msg),
                    vectorcraft_engine::UiRequest::Place(p) => crate::place::place_from_cursor(app, &p),
                    // In the document the press was made in, which may no longer be the active one.
                    vectorcraft_engine::UiRequest::HeldPress { doc, pos, tool } => {
                        let index = doc.and_then(|uid| app.session.documents().iter().position(|d| d.uid == uid));
                        pressed_with(app, index, pos, tool);
                        // The selection tool Cmd lent has the press now, so its drag can carry art to another tab.
                        if let Some(ctx) = app.ui_ctx.clone() {
                            crate::document_drag::begin(app, &ctx, pos);
                        }
                    }
                }
            }
            crate::panels::actions::after_journaled_edit(app);
        }
        Err(e) => app.status(e.to_string()),
    }
}

/// Show and select `panel` where it is (`window.panel.activate`): a panel already on show stays on
/// show, and a dock hidden by Tab shows again.
fn activate_panel(app: &mut VectorcraftApp, panel: &str) {
    if let Err(e) = app.run("window.panel.activate", serde_json::json!({ "panel": panel })) {
        app.status(e);
    }
}