Skip to content
2,775 changes: 36 additions & 2,739 deletions crates/ui-egui/src/canvas.rs

Large diffs are not rendered by default.

243 changes: 243 additions & 0 deletions crates/ui-egui/src/canvas/cursor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,243 @@
//! The cursor: crosshair and pick box, snap markers, tracking paths, snap overrides and tooltips.

use super::*;

pub(super) fn draw_snap_marker(p: &egui::Painter, at: Pos2, hit: &SnapHit) {
let t = Tokens::get();
let s = crate::theme::snap_marker_half();
let st = Stroke::new(2.0, t.snap);
use snap::mode;
match hit.mode {
mode::END => {
p.rect_stroke(Rect::from_center_size(at, vec2(2.0 * s, 2.0 * s)), 0.0, st, egui::StrokeKind::Middle);
}
mode::MID => {
p.add(Shape::closed_line(vec![at + vec2(0.0, -s), at + vec2(s, s * 0.8), at + vec2(-s, s * 0.8)], st));
}
mode::CEN | mode::GCEN => {
p.circle_stroke(at, s, st);
}
mode::QUA => {
p.add(Shape::closed_line(vec![at + vec2(0.0, -s), at + vec2(s, 0.0), at + vec2(0.0, s), at + vec2(-s, 0.0)], st));
}
mode::INT | mode::APP => {
p.line_segment([at + vec2(-s, -s), at + vec2(s, s)], st);
p.line_segment([at + vec2(s, -s), at + vec2(-s, s)], st);
if hit.mode == mode::APP {
p.rect_stroke(Rect::from_center_size(at, vec2(2.0 * s, 2.0 * s)), 0.0, st, egui::StrokeKind::Middle);
}
}
mode::PER => {
p.line(vec![at + vec2(-s, -s), at + vec2(-s, s), at + vec2(s, s)], st);
p.line(vec![at + vec2(-s, 0.0), at + vec2(0.0, 0.0), at + vec2(0.0, s)], st);
}
mode::TAN => {
p.circle_stroke(at, s * 0.8, st);
p.line_segment([at + vec2(-s, -s), at + vec2(s, -s)], st);
}
mode::NOD => {
p.circle_stroke(at, s, st);
p.line_segment([at + vec2(-s, -s), at + vec2(s, s)], st);
p.line_segment([at + vec2(s, -s), at + vec2(-s, s)], st);
}
mode::INS => {
p.line(
vec![
at + vec2(-s, -s),
at + vec2(0.0, -s),
at + vec2(0.0, 0.0),
at + vec2(s, 0.0),
at + vec2(s, s),
at + vec2(-s, s),
at + vec2(-s, -s),
],
st,
);
}
_ => {
p.line(vec![at + vec2(-s, -s), at + vec2(s, -s), at + vec2(-s, s), at + vec2(s, s), at + vec2(-s, -s)], st);
}
}
p.text(at + vec2(12.0, 12.0), egui::Align2::LEFT_TOP, crate::i18n::t(hit.name), crate::theme::small(), Color32::BLACK);
let galley = p.layout_no_wrap(crate::i18n::t(hit.name).to_string(), crate::theme::small(), Color32::BLACK);
let r = Rect::from_min_size(at + vec2(10.0, 10.0), galley.size() + vec2(6.0, 2.0));
p.rect_filled(r, 2.0, Color32::from_rgb(0xff, 0xff, 0xe1));
p.galley(r.min + vec2(3.0, 1.0), galley, Color32::BLACK);
}

/// Acquired tracking points (small `+`, `//` for a Parallel line), the dotted paths the cursor
/// is on and the tooltip naming them ("Endpoint: 5.0000 < 90°").
pub(super) fn draw_tracking(p: &egui::Painter, xf: &Xf, acquired: &[snap::tracking::Acquired], track: Option<&snap::tracking::Track>, far: f64) {
use snap::tracking::{Acquired, PathShape};
let t = Tokens::get();
let st = Stroke::new(1.0, t.snap);
for a in acquired {
let c = xf.to_screen(a.at());
if let Acquired::Parallel { .. } = a {
p.line_segment([c + vec2(-5.0, 3.0), c + vec2(-1.0, -5.0)], st);
p.line_segment([c + vec2(1.0, 3.0), c + vec2(5.0, -5.0)], st);
} else {
p.line_segment([c + vec2(-4.0, 0.0), c + vec2(4.0, 0.0)], st);
p.line_segment([c + vec2(0.0, -4.0), c + vec2(0.0, 4.0)], st);
}
}
let Some(tr) = track else { return };
let mut tips = Vec::new();
for path in &tr.paths {
// Around the cursor only (a path's origin may be far off screen).
let pts: Vec<Pos2> = match path.shape {
PathShape::Ray { origin, dir } => {
let back = (tr.point - origin).dot(dir).clamp(0.0, far);
vec![xf.to_screen(tr.point - dir * back), xf.to_screen(tr.point + dir * far)]
}
PathShape::Line { dir, .. } => vec![xf.to_screen(tr.point - dir * far), xf.to_screen(tr.point + dir * far)],
PathShape::Circle { center, radius, .. } => {
let (a0, span) = (center.angle_to(tr.point), (far / radius).min(std::f64::consts::PI));
(0..=96).map(|i| xf.to_screen(Vec2::polar(center, radius, a0 - span + span * f64::from(i) / 48.0))).collect()
}
PathShape::Ellipse { center, major, ratio, .. } => {
let e = cadcraft_geom::Ellipse::full(center, major, ratio);
let (t0, span) = (e.param_of(tr.point), (far / (major.len() * ratio.min(1.0))).min(std::f64::consts::PI));
(0..=96).map(|i| xf.to_screen(e.at_param(t0 - span + span * f64::from(i) / 48.0))).collect()
}
};
p.extend(Shape::dotted_line(&pts, t.snap, 6.0, 1.0));
let (distance, angle) = (
cadcraft_engine::units::format_distance(path.from.dist(tr.point), 2, 4),
(path.from.angle_to(tr.point).to_degrees().round() as i64).rem_euclid(360),
);
tips.push(if path.name == "Polar" {
crate::tf!("Polar: {distance} < {angle}°", distance = distance, angle = angle)
} else {
crate::tf!("{name}: {distance} < {angle}°", name = crate::i18n::t(path.name), distance = distance, angle = angle)
});
}
if let Some(o) = tr.object {
tips.push(crate::i18n::t(o).to_string());
}
let at = xf.to_screen(tr.point);
if tr.paths.len() > 1 || tr.object.is_some() {
p.line_segment([at + vec2(-4.0, -4.0), at + vec2(4.0, 4.0)], st);
p.line_segment([at + vec2(4.0, -4.0), at + vec2(-4.0, 4.0)], st);
}
tooltip(p, at + vec2(16.0, 18.0), &tips.join(", "));
}

/// The rubber-band and snap-adjusted cursor point for the current prompt (the engine's
/// `Session::snap_cursor`: object snaps, acquiring tracking points, grid, tracking paths, ortho).
pub(super) fn effective_point(app: &mut CadApp, raw: Vec2, xf: &Xf, ctx: &egui::Context) -> Vec2 {
let prompt = app.session.current_prompt();
let wants_point = prompt.as_ref().is_some_and(cadcraft_engine::pointmod::accepts);
let base = prompt.as_ref().and_then(|p| p.base);
let deferred = prompt.as_ref().is_some_and(|p| p.deferred);
let corner = prompt.as_ref().is_some_and(|p| p.corner);
app.canvas.snap = None;
app.canvas.track = None;
if !wants_point || app.session.pending_window.is_some() {
if !wants_point {
app.session.tracking.clear();
}
return raw;
}
let (now, shift) = ctx.input(|i| (i.time, i.modifiers.shift));
let q =
snap::tracking::CursorQuery { base, deferred, corner, aperture: app.session.settings.aperture / xf.scale, tol: 6.0 / xf.scale, now, shift };
let r = app.session.snap_cursor(raw, &q);
if r.wait {
ctx.request_repaint_after(std::time::Duration::from_secs_f64(snap::tracking::DWELL / 4.0));
}
app.canvas.snap = r.snap;
app.canvas.track = r.track;
r.point
}

pub(super) fn tooltip(p: &egui::Painter, at: Pos2, text: &str) {
let galley = p.layout_no_wrap(text.to_string(), crate::theme::small(), Color32::from_rgb(0x20, 0x20, 0x20));
let r = Rect::from_min_size(at, galley.size() + vec2(8.0, 4.0));
p.rect_filled(r, 2.0, Color32::from_rgb(0xf4, 0xf4, 0xf4));
p.galley(r.min + vec2(4.0, 2.0), galley, Color32::BLACK);
}

/// Half the side of the pick box: the pick aperture (PICKBOX × 1.5 pixels, as `select::pick` is
/// called with), so the square shows what a click hits. `None` when PICKBOX is 0 (no box).
/// The candidate Tab has cycled to, if cycling: a Tab press starts or advances it, and the
/// cursor leaving the aperture where it started ends it.
pub(super) fn snap_cycle(app: &mut CadApp, raw: Vec2, ap: f64) -> Option<usize> {
let tab = std::mem::take(&mut app.canvas.snap_tab);
let c = &mut app.canvas.snap_cycle;
if c.is_some_and(|c| c.anchor.dist(raw) > ap) {
*c = None;
}
if tab {
*c = Some(c.map_or(SnapCycle { anchor: raw, index: 1 }, |c| SnapCycle { index: c.index + 1, ..c }));
}
c.map(|c| c.index)
}

/// The cursor under a one-pick object snap override (`Session::snap_override`: END, NON…) or
/// while Tab cycles the candidates: the snap of that mode (or the cycled candidate) replaces
/// what the running snaps found; with none, a running snap no longer holds the cursor.
pub(super) fn override_cursor(app: &mut CadApp, raw: Vec2, xf: &Xf) {
let over = app.session.snap_override();
let ap = app.session.settings.aperture / xf.scale;
let cycle = snap_cycle(app, raw, ap);
let prompt = app.session.current_prompt();
let wants_point = prompt.as_ref().is_some_and(cadcraft_engine::pointmod::accepts);
if (over.is_none() && cycle.is_none()) || !wants_point || app.session.pending_window.is_some() {
return;
}
let base = prompt.as_ref().and_then(|p| p.base);
let deferred = prompt.as_ref().is_some_and(|p| p.deferred);
let s = &app.session.settings;
let osmode = over.unwrap_or(s.osmode) | if s.osnaphatch { snap::mode::HATCH } else { 0 };
let Ok(st) = app.session.state() else { return };
let hit = match cycle {
Some(i) => {
let cands = cadcraft_engine::pointmod::snap_candidates(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred);
cands.get(i % cands.len().max(1)).copied()
}
None => snap::osnap(&st.doc, &st.edit_space(), raw, ap, osmode, base, deferred),
};
let p = match (hit, app.canvas.snap) {
(Some(h), _) => {
app.canvas.snap = Some(h);
h.point
}
(None, Some(_)) => {
app.canvas.snap = None;
raw
}
(None, None) => return,
};
app.canvas.cursor = Some(p);
app.session.cursor = p;
app.session.cursor_deferred = app.canvas.snap.and_then(|h| h.deferred);
}

pub(super) fn pickbox_half(pickbox: f64) -> Option<f32> {
let half = (pickbox * 1.5) as f32;
(half.is_finite() && half >= 1.0).then_some(half)
}

pub(super) fn draw_crosshair(app: &CadApp, p: &egui::Painter, rect: Rect, at: Pos2, pickbox: bool) {
let st = Stroke::new(1.0, Tokens::get().crosshair);
let len = (rect.height() * app.session.settings.cursorsize as f32 / 100.0).max(12.0);
let pb = if pickbox { pickbox_half(app.session.settings.pickbox) } else { None };
let gap = pb.unwrap_or(0.0);
// Along the isometric plane's axes in isometric drafting.
if app.session.settings.isodraft {
for a in cadcraft_engine::snap::iso::cursor_axes(&app.session.settings) {
let dir = vec2(a.cos() as f32, -(a.sin() as f32));
p.line_segment([at - dir * len, at - dir * gap], st);
p.line_segment([at + dir * gap, at + dir * len], st);
}
} else {
p.line_segment([pos2(at.x - len, at.y), pos2(at.x - gap, at.y)], st);
p.line_segment([pos2(at.x + gap, at.y), pos2(at.x + len, at.y)], st);
p.line_segment([pos2(at.x, at.y - len), pos2(at.x, at.y - gap)], st);
p.line_segment([pos2(at.x, at.y + gap), pos2(at.x, at.y + len)], st);
}
if let Some(pb) = pb {
p.rect_stroke(Rect::from_center_size(at, vec2(pb * 2.0, pb * 2.0)), 0.0, st, egui::StrokeKind::Middle);
}
}
132 changes: 132 additions & 0 deletions crates/ui-egui/src/canvas/cycle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
//! Selection cycling: the list of overlapping objects under a click, Shift+Space, and the badge.

use super::*;

/// The objects under a click that selection cycling lets the user choose between: where the click
/// was, each object with its row's label (type and layer), Shift held, and the rows as drawn.
#[derive(Clone, Debug)]
pub(super) struct CycleList {
pub(super) at: Pos2,
pub(super) items: Vec<(Handle, String, String)>,
pub(super) shift: bool,
pub(super) rows: Vec<Rect>,
}

impl CycleList {
pub(super) fn row_at(&self, p: Pos2) -> Option<Handle> {
self.rows.iter().zip(&self.items).find(|(r, _)| r.contains(p)).map(|(_, (h, _, _))| *h)
}
}

/// A click while selection cycling's list is open picks the row under it (anywhere else just
/// closes the list); otherwise a click over overlapping objects that a pick would choose between
/// opens the list (SELECTIONCYCLING 2). True when the click was used up here.
pub(super) fn cycle_click(app: &mut CadApp, xf: &Xf, hover: Option<Pos2>, world: Option<Vec2>, shift: bool) -> bool {
// Only where a click picks objects; a click that places a point goes through.
let picks = app.session.click_picks();
if let Some((_, hs, i)) = app.canvas.hover_cycle.take()
&& picks
&& let Some(h) = hs.get(i % hs.len().max(1))
{
if let Err(e) = app.session.pick_cycled(*h, shift) {
app.session.echo(e.to_string());
}
return true;
}
if let Some(list) = app.canvas.cycle.take() {
let Some(h) = hover.and_then(|hp| list.row_at(hp)).filter(|_| picks) else { return picks };
if let Err(e) = app.session.pick_cycled(h, list.shift) {
app.session.echo(e.to_string());
}
return true;
}
let (Some(hp), Some(w)) = (hover, world) else { return false };
if crate::dyngrips::at(app, xf, hover).is_some() || grip_at(app, xf, hover).is_some() {
return false;
}
let hs = app.session.cycling_candidates(w);
let Ok(d) = app.session.doc() else { return false };
let items: Vec<_> =
hs.into_iter().filter_map(|h| d.entity(h).map(|e| (h, crate::i18n::t(e.kind.type_name()).to_string(), e.common.layer.clone()))).collect();
if items.len() < 2 {
return false;
}
app.canvas.cycle = Some(CycleList { at: hp, items, shift, rows: Vec::new() });
true
}

/// Shift+Space over overlapping objects highlights the next one under the cursor, and a click
/// picks the highlighted one, whether selection cycling is on or not; moving the cursor off the
/// pick box where it started ends it.
pub(super) fn shift_space_cycle(app: &mut CadApp, ui: &egui::Ui, hover: Option<Pos2>, world: Option<Vec2>) {
let pick_px = (app.session.settings.pickbox.max(1.0) * 1.5) as f32;
let (Some(hp), Some(w)) = (hover, world) else {
app.canvas.hover_cycle = None;
return;
};
if app.canvas.hover_cycle.as_ref().is_some_and(|(a, _, _)| a.distance(hp) > pick_px) {
app.canvas.hover_cycle = None;
}
let pressed = ui
.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key: egui::Key::Space, pressed: true, modifiers, .. } if modifiers.shift)));
if pressed {
// With the list open Shift+Space does nothing, and isn't Enter either.
let next = match app.canvas.hover_cycle.take() {
_ if app.canvas.cycle.is_some() => None,
Some((a, hs, i)) => Some((a, hs, i + 1)),
None => Some((hp, app.session.pick_candidates(w), 1)).filter(|(_, hs, _)| hs.len() > 1),
};
if next.is_some() || app.canvas.cycle.is_some() {
// Space is Enter at the command line; this one only steps the highlight.
ui.ctx().input_mut(|i| {
i.events.retain(|e| !matches!(e, egui::Event::Key { key: egui::Key::Space, .. }) && !matches!(e, egui::Event::Text(t) if t == " "))
});
}
app.canvas.hover_cycle = next;
}
if let Some((_, hs, i)) = &app.canvas.hover_cycle {
app.canvas.hover = hs.get(i % hs.len().max(1)).copied();
app.canvas.hover_at = None;
}
}

/// Selection cycling's badge beside the cursor: two overlapping squares, objects overlap here.
pub(super) fn cycle_badge(p: &egui::Painter, at: Pos2) {
let t = Tokens::get();
for off in [vec2(14.0, -22.0), vec2(19.0, -17.0)] {
let r = Rect::from_min_size(at + off, vec2(9.0, 9.0));
p.rect_filled(r, 1.0, t.cmd_bg);
p.rect_stroke(r, 1.0, Stroke::new(1.0, t.text), egui::StrokeKind::Inside);
}
}

/// The selection cycling list beside the click that opened it: a row per object, its type and
/// layer, the row under the pointer highlighted; the rows are kept for clicks.
pub(super) fn cycle_list(app: &mut CadApp, p: &egui::Painter) {
let Some(list) = app.canvas.cycle.as_mut() else { return };
let t = Tokens::get();
let font = crate::theme::small();
let galleys: Vec<_> = list
.items
.iter()
.map(|(_, ty, layer)| (p.layout_no_wrap(ty.clone(), font.clone(), t.text), p.layout_no_wrap(layer.clone(), font.clone(), t.text_dim)))
.collect();
let row_h = galleys.iter().map(|(a, _)| a.size().y).fold(12.0, f32::max) + 6.0;
let ty_w = galleys.iter().map(|(a, _)| a.size().x).fold(40.0, f32::max);
let layer_w = galleys.iter().map(|(_, b)| b.size().x).fold(20.0, f32::max);
let w = ty_w + layer_w + 36.0;
let m = Rect::from_min_size(list.at + vec2(14.0, 14.0), vec2(w, row_h * galleys.len() as f32 + 4.0));
p.rect_filled(m, 3.0, t.cmd_bg);
p.rect_stroke(m, 3.0, Stroke::new(1.0, t.cmd_border), egui::StrokeKind::Inside);
let hover = app.canvas.hover;
list.rows.clear();
for (i, ((ty, layer), (h, _, _))) in galleys.into_iter().zip(&list.items).enumerate() {
let row = Rect::from_min_size(pos2(m.left() + 2.0, m.top() + 2.0 + row_h * i as f32), vec2(w - 4.0, row_h));
if hover == Some(*h) {
p.rect_filled(row, 2.0, t.cmd_keyword_hover);
}
p.galley(pos2(row.left() + 8.0, row.center().y - ty.size().y / 2.0), ty, t.text);
p.galley(pos2(row.left() + 20.0 + ty_w, row.center().y - layer.size().y / 2.0), layer, t.text_dim);
list.rows.push(row);
}
}
Loading