mirror of
https://github.com/storytold/deckcraft.git
synced 2026-12-01 10:47:56 +01:00
canvas-w10: net change of 4 commits
- canvas-w10: written by an agent - canvas-w10: finished by an agent - canvas-w10: review fixes (review-1) - canvas-w10: review fixes (review-1)
This commit is contained in:
1 parent
00f74afbb6
commit
628695bdb7
10 files changed
+485
-560
No files matched your search
@@ -23,6 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
),
|
||||
cmd!("guide.move", "Move Guide", [], None, "{index, pos: pt}", has_doc, guide_move),
|
||||
cmd!("guide.delete", "Delete Guide", [], None, "{index}", has_doc, guide_delete),
|
||||
cmd!("guide.set", "Set Guides", [], None, "{guides: [{vertical: bool, pos: pt}]} replaces all guides in one undo step", has_doc, guide_set),
|
||||
cmd!(query "guide.list", "Guides", [], None, "{} → [{vertical, pos}]", has_doc, guide_list),
|
||||
cmd!("arrange.bringToFront", "Bring to Front", ["Arrange"], Some("Cmd+Shift+]"), "{ids?}", has_selection, |s, p| order(s, p, 2)),
|
||||
cmd!("arrange.bringForward", "Bring Forward", ["Arrange"], Some("Cmd+]"), "{ids?}", has_selection, |s, p| order(s, p, 1)),
|
||||
@@ -578,6 +579,25 @@ fn guide_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
})
|
||||
}
|
||||
|
||||
fn guide_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let items = p.get("guides").and_then(Value::as_array).ok_or_else(|| bad("guide.set", "`guides` must be an array"))?;
|
||||
if items.len() > MAX_GUIDES {
|
||||
return Err(bad("guide.set", "too many guides"));
|
||||
}
|
||||
let mut guides: Vec<deckcraft_model::DrawGuide> =
|
||||
serde_json::from_value(Value::Array(items.clone())).map_err(|_| bad("guide.set", "each guide needs `vertical` and a finite `pos`"))?;
|
||||
for guide in &mut guides {
|
||||
if !guide.pos.is_finite() {
|
||||
return Err(bad("guide.set", "`pos` must be finite"));
|
||||
}
|
||||
guide.pos = guide.pos.clamp(0.0, guide_limit(s, guide.vertical)?);
|
||||
}
|
||||
s.edit(|doc, _| {
|
||||
doc.guides = guides;
|
||||
ok()
|
||||
})
|
||||
}
|
||||
|
||||
fn guide_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(serde_json::to_value(&s.doc()?.doc.guides).unwrap_or_default())
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
//! Drawing guides: commands, dragging a guide with the pointer, snapping shapes to guides, and
|
||||
//! the PPTX round trip.
|
||||
//! Drawing guides: commands, shape snapping while visible and the PPTX round trip.
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
@@ -32,17 +31,8 @@ fn drag_a_guide_drop_it_off_the_slide_and_snap_shapes_to_it() {
|
||||
let mut s = Session::with_new();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
s.execute("guide.add", &json!({"vertical": true, "pos": 300})).unwrap();
|
||||
// Hidden guides can't be grabbed: the press starts a marquee instead.
|
||||
ev(&mut s, PointerKind::Down, 300.0, 50.0);
|
||||
ev(&mut s, PointerKind::Up, 300.0, 50.0);
|
||||
assert_eq!(s.doc().unwrap().doc.guides[0].pos, 300.0);
|
||||
s.execute("guide.move", &json!({"index": 0, "pos": 350})).unwrap();
|
||||
s.tool.guides_visible = true;
|
||||
ev(&mut s, PointerKind::Down, 301.0, 50.0);
|
||||
ev(&mut s, PointerKind::Drag, 350.4, 60.0);
|
||||
assert_eq!(s.tool.guide_drag, Some((0, 350.0)), "whole points while dragging");
|
||||
ev(&mut s, PointerKind::Up, 350.4, 60.0);
|
||||
assert_eq!(s.doc().unwrap().doc.guides[0].pos, 350.0);
|
||||
assert_eq!(s.tool.guide_drag, None);
|
||||
|
||||
// A shape dragged near the guide snaps its left edge onto it.
|
||||
let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 200, 80, 60]})).unwrap()["id"].as_u64().unwrap();
|
||||
@@ -52,15 +42,43 @@ fn drag_a_guide_drop_it_off_the_slide_and_snap_shapes_to_it() {
|
||||
ev(&mut s, PointerKind::Drag, 388.0, 231.0);
|
||||
ev(&mut s, PointerKind::Up, 388.0, 231.0);
|
||||
let x = s.doc().unwrap().shapes().iter().find(|sh| sh.id.0 as u64 == id).and_then(|sh| sh.xfrm).unwrap();
|
||||
assert!((x.x - 350.0).abs() < 0.01, "{x:?}");
|
||||
let guide = s.doc().unwrap().doc.guides[0].pos;
|
||||
assert!((x.x - guide).abs() < 0.01, "{x:?}");
|
||||
|
||||
// Dropped off the slide: gone, and undo brings it back.
|
||||
ev(&mut s, PointerKind::Down, 350.0, 10.0);
|
||||
ev(&mut s, PointerKind::Drag, -40.0, 10.0);
|
||||
ev(&mut s, PointerKind::Up, -40.0, 10.0);
|
||||
s.execute("shape.setBounds", &json!({"id": id, "x": 100, "y": 200, "w": 80, "h": 60})).unwrap();
|
||||
s.tool.guides_visible = false;
|
||||
ev(&mut s, PointerKind::Down, 140.0, 230.0);
|
||||
ev(&mut s, PointerKind::Drag, 200.0, 230.0);
|
||||
ev(&mut s, PointerKind::Drag, 388.0, 231.0);
|
||||
ev(&mut s, PointerKind::Up, 388.0, 231.0);
|
||||
let hidden = s.doc().unwrap().shapes().iter().find(|sh| sh.id.0 as u64 == id).and_then(|sh| sh.xfrm).unwrap();
|
||||
assert!((hidden.x - guide).abs() > 1.0, "a hidden guide does not snap the shape: {hidden:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_guides_validates_atomically_and_undoes_the_whole_vector() {
|
||||
let mut s = Session::with_new();
|
||||
for (vertical, pos) in [(true, 100.0), (false, 150.0), (true, 200.0)] {
|
||||
s.execute("guide.add", &json!({"vertical": vertical, "pos": pos})).unwrap();
|
||||
}
|
||||
let before = s.doc().unwrap().doc.guides.clone();
|
||||
let replacement = vec![
|
||||
deckcraft_model::DrawGuide { pos: before[2].pos + 25.0, ..before[2] },
|
||||
deckcraft_model::DrawGuide { pos: before[0].pos + 15.0, ..before[0] },
|
||||
];
|
||||
s.execute("guide.set", &json!({"guides": replacement})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides, replacement, "one commit preserves the final order, moves and deletion");
|
||||
assert!(s.execute("guide.set", &json!({"guides": [before[0], {"vertical": false, "pos": null}]})).is_err());
|
||||
assert!(s.execute("guide.set", &json!({"guides": vec![before[0]; super::MAX_GUIDES + 1]})).is_err());
|
||||
assert_eq!(s.doc().unwrap().doc.guides, replacement, "a refused vector changes no guide");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides, before, "one undo restores every moved and deleted guide");
|
||||
s.execute("edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides, replacement);
|
||||
s.execute("guide.set", &json!({"guides": []})).unwrap();
|
||||
assert!(s.doc().unwrap().doc.guides.is_empty());
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.guides.len(), 1);
|
||||
assert_eq!(s.doc().unwrap().doc.guides, replacement);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -196,10 +196,6 @@ enum Drag {
|
||||
start: Point,
|
||||
add: bool,
|
||||
},
|
||||
/// Dragging drawing guide `index`.
|
||||
Guide {
|
||||
index: usize,
|
||||
},
|
||||
Create {
|
||||
start: Point,
|
||||
},
|
||||
@@ -289,12 +285,8 @@ pub struct ToolState {
|
||||
pub edit_segment_t: Option<f64>,
|
||||
/// The point type last chosen for a vertex (shape, path, index, type): handle drags follow it.
|
||||
pub vertex_kind: Option<(ShapeId, usize, usize, String)>,
|
||||
/// Drawing guides are shown (View › Guides): they can be dragged and shapes snap to them.
|
||||
/// Drawing guides are shown (View › Guides): shapes snap to them.
|
||||
pub guides_visible: bool,
|
||||
/// The guide being dragged and where it is now (slide points); `None` once dropped.
|
||||
pub guide_drag: Option<(usize, f64)>,
|
||||
/// The drawing guide under the pointer, for the cursor.
|
||||
pub guide_hover: Option<usize>,
|
||||
/// Pressure from the pointer event being handled, if the device reported one.
|
||||
pressure: Option<f32>,
|
||||
}
|
||||
|
||||
@@ -24,13 +24,6 @@ impl Session {
|
||||
}
|
||||
let Some(drag) = self.tool.drag.clone() else { return Ok(Value::Null) };
|
||||
match drag {
|
||||
Drag::Guide { index } => {
|
||||
let vertical = self.active().and_then(|d| d.doc.guides.get(index)).is_some_and(|g| g.vertical);
|
||||
let pos = if vertical { p.x } else { p.y };
|
||||
// Guides move in whole points unless snapping is off, as in PowerPoint.
|
||||
let pos = if self.prefs.snap_to_grid && !mods.alt { pos.round() } else { pos };
|
||||
self.tool.guide_drag = Some((index, pos));
|
||||
}
|
||||
Drag::Move { ids, start, origs, moved, duplicate, enter_text } => {
|
||||
return self.drag_move(MoveDrag { ids, start, origs, moved, duplicate, enter_text }, p, mods, tol);
|
||||
}
|
||||
|
||||
@@ -115,22 +115,6 @@ impl Session {
|
||||
})
|
||||
}
|
||||
|
||||
/// The drawing guide within `tol` of `p` (only while guides are shown).
|
||||
pub fn guide_at(&self, p: Point, tol: f64) -> Option<usize> {
|
||||
if !self.tool.guides_visible {
|
||||
return None;
|
||||
}
|
||||
let st = self.active()?;
|
||||
st.doc
|
||||
.guides
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, g)| (i, if g.vertical { (p.x - g.pos).abs() } else { (p.y - g.pos).abs() }))
|
||||
.filter(|(_, d)| *d <= tol.max(2.0))
|
||||
.min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
/// Smart guides: snap `r` edges/centres to the slide and other shapes. Returns the offset to
|
||||
/// apply and the guides to draw.
|
||||
pub(super) fn snap_rect(&self, r: Rect, exclude: &[ShapeId], tol: f64, enabled: bool) -> (Vec2, Vec<Guide>) {
|
||||
|
||||
@@ -14,6 +14,10 @@ impl Session {
|
||||
|
||||
/// What's under `p` on the current slide.
|
||||
pub fn hit_test(&self, p: Point, tol: f64) -> Option<Hit> {
|
||||
self.hit_test_with_transform(p, tol, true)
|
||||
}
|
||||
|
||||
fn hit_test_with_transform(&self, p: Point, tol: f64, transform: bool) -> Option<Hit> {
|
||||
let st = self.active()?;
|
||||
// In Edit Points, the edited shape's vertices come first.
|
||||
if let Some(id) = self.tool.editing_points(st)
|
||||
@@ -61,13 +65,15 @@ impl Session {
|
||||
return Some(Hit::Warp { id: *id, index: hd.index });
|
||||
}
|
||||
}
|
||||
let (pts, rot) = box_handles(&x);
|
||||
if (rot - p).hypot() <= tol * 1.8 && st.selection.text.is_none() {
|
||||
return Some(Hit::Rotate { id: *id });
|
||||
}
|
||||
for (i, q) in pts.iter().enumerate() {
|
||||
if (*q - p).hypot() <= tol * 1.6 {
|
||||
return Some(Hit::Resize { id: *id, handle: i as u8 });
|
||||
if transform {
|
||||
let (pts, rot) = box_handles(&x);
|
||||
if (rot - p).hypot() <= tol * 1.8 && st.selection.text.is_none() {
|
||||
return Some(Hit::Rotate { id: *id });
|
||||
}
|
||||
for (i, q) in pts.iter().enumerate() {
|
||||
if (*q - p).hypot() <= tol * 1.6 {
|
||||
return Some(Hit::Resize { id: *id, handle: i as u8 });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,6 +102,10 @@ impl Session {
|
||||
|
||||
/// Feed a pointer event to the active tool. Returns what happened (for agents).
|
||||
pub fn pointer(&mut self, ev: PointerEvent) -> Result<Value> {
|
||||
self.pointer_route(ev, None)
|
||||
}
|
||||
|
||||
fn pointer_route(&mut self, ev: PointerEvent, transform_hit: Option<Option<Hit>>) -> Result<Value> {
|
||||
let tol = if ev.tol > 0.0 { ev.tol } else { 4.0 };
|
||||
let p = Point::new(ev.x, ev.y);
|
||||
self.tool.pressure = ev.pressure.filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1.0));
|
||||
@@ -106,7 +116,8 @@ impl Session {
|
||||
if !matches!(ev.kind, PointerKind::Move) {
|
||||
self.settle_composition();
|
||||
}
|
||||
match ev.kind {
|
||||
let before_target = self.text_selection().map(|(shape, cell, notes, _, _)| (shape, cell, notes));
|
||||
let result = match ev.kind {
|
||||
PointerKind::Move => {
|
||||
if let Some(Drag::Freeform { points, mode, .. }) = &self.tool.drag {
|
||||
let closing = points.len() > 2 && points.first().is_some_and(|s| (*s - p).hypot() <= tol * 2.0);
|
||||
@@ -117,9 +128,7 @@ impl Session {
|
||||
self.tool.path_closing = closing;
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
self.tool.hover = self.hit_test(p, tol);
|
||||
self.tool.guide_hover =
|
||||
if self.tool.hover.is_none() && matches!(self.tool.kind, ToolKind::Select) { self.guide_at(p, tol) } else { None };
|
||||
self.tool.hover = self.pointer_hit(p, tol, transform_hit);
|
||||
let line_tool = matches!(&self.tool.kind, ToolKind::Shape { preset } if deckcraft_geom::preset::is_line_like(preset));
|
||||
if line_tool {
|
||||
self.update_sites(p, tol, None);
|
||||
@@ -129,7 +138,7 @@ impl Session {
|
||||
}
|
||||
Ok(Value::Null)
|
||||
}
|
||||
PointerKind::Down => self.down(p, ev.mods, tol),
|
||||
PointerKind::Down => self.down(p, ev.mods, tol, transform_hit),
|
||||
PointerKind::Drag => self.drag(p, ev.mods, tol),
|
||||
PointerKind::Up => self.up(p, ev.mods),
|
||||
PointerKind::DoubleClick => {
|
||||
@@ -147,6 +156,18 @@ impl Session {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
}
|
||||
};
|
||||
let after_target = self.text_selection().map(|(shape, cell, notes, _, _)| (shape, cell, notes));
|
||||
if result.is_ok() && after_target.is_some() && after_target != before_target {
|
||||
self.begin_text_edit_session()?;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn pointer_hit(&self, p: Point, tol: f64, transform_hit: Option<Option<Hit>>) -> Option<Hit> {
|
||||
match transform_hit {
|
||||
Some(hit) => hit.or_else(|| self.hit_test_with_transform(p, tol, false)),
|
||||
None => self.hit_test(p, tol),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -221,7 +242,7 @@ impl Session {
|
||||
}
|
||||
|
||||
/// Handle a pointer press and start the applicable tool interaction.
|
||||
fn down(&mut self, p: Point, mods: Mods, tol: f64) -> Result<Value> {
|
||||
fn down(&mut self, p: Point, mods: Mods, tol: f64, transform_hit: Option<Option<Hit>>) -> Result<Value> {
|
||||
if let Some(Drag::Freeform { mode, mut points, .. }) = self.tool.drag.clone() {
|
||||
// Next click of a freeform: close on the start point, else add a vertex.
|
||||
if points.len() > 2 && points.first().is_some_and(|s| (*s - p).hypot() <= tol * 2.0) {
|
||||
@@ -266,12 +287,15 @@ impl Session {
|
||||
}
|
||||
// Clicking inside the text being edited moves the caret / starts a text selection.
|
||||
let before = self.text_selection();
|
||||
if let Some((shape, pos)) = self.place_caret(p, tol, mods.shift)? {
|
||||
let canonical_transform = matches!(transform_hit, Some(Some(Hit::Resize { .. } | Hit::Rotate { .. })));
|
||||
if !canonical_transform
|
||||
&& let Some((shape, pos)) = self.place_caret(p, tol, mods.shift)?
|
||||
{
|
||||
let press = self.doc()?.selection.text.clone();
|
||||
self.tool.drag = Some(Drag::TextSelect { shape, before, press });
|
||||
return Ok(json!({"caret": [pos.0, pos.1]}));
|
||||
}
|
||||
let hit = self.hit_test(p, tol);
|
||||
let hit = self.pointer_hit(p, tol, transform_hit);
|
||||
// Edit Points: drag a vertex, Ctrl-click one to delete it or the outline to add one;
|
||||
// a click anywhere else leaves Edit Points.
|
||||
if let Some(eid) = self.doc().ok().and_then(|st| self.tool.editing_points(st)) {
|
||||
@@ -420,14 +444,6 @@ impl Session {
|
||||
let _ = self.execute("animation.painterApply", &json!({"ids": [id]}));
|
||||
}
|
||||
}
|
||||
None if self.guide_at(p, tol).is_some() => {
|
||||
// Away from every shape a press on a guide picks the guide up.
|
||||
if let Some(index) = self.guide_at(p, tol) {
|
||||
let pos = st.doc.guides.get(index).map(|g| g.pos).unwrap_or(0.0);
|
||||
self.tool.drag = Some(Drag::Guide { index });
|
||||
self.tool.guide_drag = Some((index, pos));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let add = mods.shift || mods.cmd;
|
||||
self.select(|_, sel| {
|
||||
@@ -452,18 +468,6 @@ impl Session {
|
||||
self.tool.glue = None;
|
||||
let mut out = Value::Null;
|
||||
match drag {
|
||||
Some(Drag::Guide { index }) => {
|
||||
// Dropped off the slide: the guide is deleted.
|
||||
let (_, pos) = self.tool.guide_drag.take().unwrap_or((index, 0.0));
|
||||
let size = self.doc()?.doc.slide_size;
|
||||
let vertical = self.doc()?.doc.guides.get(index).is_some_and(|g| g.vertical);
|
||||
let limit = if vertical { size.width } else { size.height };
|
||||
out = if pos < 0.0 || pos > limit {
|
||||
self.execute("guide.delete", &json!({"index": index}))?
|
||||
} else {
|
||||
self.execute("guide.move", &json!({"index": index, "pos": pos}))?
|
||||
};
|
||||
}
|
||||
Some(Drag::Move { moved: false, enter_text: Some((id, at)), .. })
|
||||
// Plain click on text: caret at the click (in a table, in the clicked cell).
|
||||
if self.edit_text_at(id, at)? => {
|
||||
@@ -603,10 +607,9 @@ impl Session {
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Uses the canonical canvas transform hit for hover and press gestures.
|
||||
/// Keeps ordinary document hits while suppressing transform re-hits on this route.
|
||||
pub fn pointer_with_hit(&mut self, ev: crate::tools::PointerEvent, transform_hit: Option<crate::tools::Hit>) -> crate::Result<serde_json::Value> {
|
||||
let _ = (ev, transform_hit);
|
||||
todo!("cv.A13")
|
||||
/// Uses the canvas's canonical resize/rotate hit for hover and press, preserving its chosen drag on drag/up.
|
||||
/// `None` suppresses transform re-hits while retaining ordinary shape, text and edit-point hits.
|
||||
pub fn pointer_with_hit(&mut self, ev: PointerEvent, transform_hit: Option<Hit>) -> Result<Value> {
|
||||
self.pointer_route(ev, Some(transform_hit))
|
||||
}
|
||||
}
|
||||
@@ -1,110 +1,112 @@
|
||||
use super::{Color32, CornerRadius, Point, Rect, SlideApp, Stroke, Tokens, Xf, pos2, theme};
|
||||
use craft::behavior::kurbo::{Point, Rect, Vec2};
|
||||
use craft::behavior::{Axis, EditEvent};
|
||||
use craft::ui::canvas::{CanvasSpace, Guide, GuideKey, GuideLine};
|
||||
use craft::ui::canvas_controls::{CanvasGrid, GridCrowding, GuideReadout, Guides};
|
||||
use craft::ui::contract::{Bind, Show as _};
|
||||
use deckcraft_engine::ToolKind;
|
||||
use deckcraft_model::DrawGuide;
|
||||
use serde_json::json;
|
||||
|
||||
/// Selected guide indices for the active document, cleared on a document switch or unexpected guide-list change.
|
||||
/// This selection is transient and never saved.
|
||||
use crate::SlideApp;
|
||||
|
||||
/// Selected guide indices and the document guide list they identify; never saved.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[allow(dead_code)] // P3(canvas-w10): cv.A14
|
||||
pub(crate) struct GuideSelection {
|
||||
/// The active document whose guides are selected.
|
||||
/// The document whose guides are selected.
|
||||
pub(crate) uid: Option<u64>,
|
||||
/// Indices passed to the guide control and updated from its selection output.
|
||||
/// Indices passed to the control and updated from its selection output.
|
||||
pub(crate) guides: Vec<usize>,
|
||||
represented: Vec<DrawGuide>,
|
||||
}
|
||||
|
||||
/// The presentation's drawing guides; the one being dragged at its new place, labelled with its
|
||||
/// distance from the slide's centre in points.
|
||||
pub(super) fn draw_guides(app: &SlideApp, painter: &egui::Painter, xf: Xf, slide: Rect, t: &Tokens) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let size = st.doc.slide_size;
|
||||
let drag = app.session.tool.guide_drag;
|
||||
for (i, g) in st.doc.guides.iter().enumerate() {
|
||||
let (pos, active) = match drag {
|
||||
Some((di, p)) if di == i => (p, true),
|
||||
_ => (g.pos, app.session.tool.guide_hover == Some(i)),
|
||||
};
|
||||
let col = if active { t.accent } else { Color32::from_rgba_unmultiplied(120, 120, 120, 170) };
|
||||
let stroke = Stroke::new(1.0, col);
|
||||
let (a, b) = if g.vertical {
|
||||
let x = xf.to_screen(Point::new(pos, 0.0)).x;
|
||||
(pos2(x, slide.min.y), pos2(x, slide.max.y))
|
||||
} else {
|
||||
let y = xf.to_screen(Point::new(0.0, pos)).y;
|
||||
(pos2(slide.min.x, y), pos2(slide.max.x, y))
|
||||
};
|
||||
// Dashed, like PowerPoint's guides.
|
||||
let len = (b - a).length();
|
||||
let dir = (b - a) / len.max(1.0);
|
||||
let mut d = 0.0;
|
||||
while d < len {
|
||||
painter.line_segment([a + dir * d, a + dir * (d + 4.0).min(len)], stroke);
|
||||
d += 7.0;
|
||||
}
|
||||
if drag.is_some_and(|(di, _)| di == i) {
|
||||
let centre = if g.vertical { size.width / 2.0 } else { size.height / 2.0 };
|
||||
let off = pos - centre;
|
||||
let side = match (g.vertical, off < 0.0, off > 0.0) {
|
||||
(true, true, _) => " left of centre",
|
||||
(true, _, true) => " right of centre",
|
||||
(false, true, _) => " above centre",
|
||||
(false, _, true) => " below centre",
|
||||
_ => " (centre)",
|
||||
};
|
||||
let label = format!("{:.0} pt{side}", off.abs());
|
||||
let at = if g.vertical { pos2(a.x + 6.0, slide.min.y + 6.0) } else { pos2(slide.min.x + 6.0, a.y + 4.0) };
|
||||
let galley = painter.layout_no_wrap(label, theme::font(11.0), t.text);
|
||||
let r = Rect::from_min_size(at, galley.size()).expand(3.0);
|
||||
painter.rect_filled(r, CornerRadius::same(3), t.card);
|
||||
painter.galley(at, galley, t.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Screen-point distance between grid lines. `spacing` is the grid spacing in slide points;
|
||||
/// `scale` maps slide points onto the screen. `None` when the grid would not be a finite set of
|
||||
/// lines (bad inputs, or so fine that a line would land on every pixel).
|
||||
pub(super) fn grid_line_step(spacing: f64, scale: f32) -> Option<f32> {
|
||||
if !spacing.is_finite() || !(1.0..=288.0).contains(&spacing) || !scale.is_finite() || scale <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let step = (spacing as f32) * scale;
|
||||
if !step.is_finite() || step < 1.0 {
|
||||
return None;
|
||||
}
|
||||
Some(step)
|
||||
}
|
||||
|
||||
pub(super) fn draw_grid(painter: &egui::Painter, slide: Rect, step: f32) {
|
||||
let stroke = Stroke::new(0.5, Color32::from_black_alpha(40));
|
||||
// A denser grid than this paints a grey slab and costs a frame. Skip it.
|
||||
if !grid_fits(slide.width(), step) || !grid_fits(slide.height(), step) {
|
||||
/// Shows the document grid within the slide's bounds.
|
||||
pub(crate) fn show_grid(app: &mut SlideApp, ui: &mut egui::Ui, space: &CanvasSpace) {
|
||||
if !app.ui.gridlines {
|
||||
return;
|
||||
}
|
||||
let mut x = slide.min.x + step;
|
||||
while x < slide.max.x {
|
||||
painter.line_segment([pos2(x, slide.min.y), pos2(x, slide.max.y)], stroke);
|
||||
x += step;
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let size = st.doc.slide_size;
|
||||
let spacing = app.session.prefs.grid_spacing;
|
||||
let _ = CanvasGrid::new("Grid")
|
||||
.spacing(Vec2::new(spacing, spacing))
|
||||
.origin(Point::ZERO)
|
||||
.bounds(Rect::new(0.0, 0.0, size.width, size.height))
|
||||
.crowding(GridCrowding::Thin)
|
||||
.show_at(ui, space.view.rect);
|
||||
}
|
||||
|
||||
/// Shows guides keyed by their engine indices and commits the control's edits through commands.
|
||||
pub(crate) fn show_guides(app: &mut SlideApp, ui: &mut egui::Ui, space: &CanvasSpace, canvas: egui::Id) {
|
||||
app.session.tool.guides_visible = app.ui.guides;
|
||||
let Some(st) = app.session.active() else {
|
||||
app.guide_selection = GuideSelection::default();
|
||||
return;
|
||||
};
|
||||
let (uid, original, size) = (st.uid, st.doc.guides.clone(), st.doc.slide_size);
|
||||
let interactive = app.ui.guides && matches!(app.session.tool.kind, ToolKind::Select);
|
||||
let selection = &mut app.guide_selection;
|
||||
if selection.uid != Some(uid) || selection.represented != original || !interactive {
|
||||
selection.guides.clear();
|
||||
}
|
||||
let mut y = slide.min.y + step;
|
||||
while y < slide.max.y {
|
||||
painter.line_segment([pos2(slide.min.x, y), pos2(slide.max.x, y)], stroke);
|
||||
y += step;
|
||||
selection.uid = Some(uid);
|
||||
selection.represented.clone_from(&original);
|
||||
if !app.ui.guides {
|
||||
return;
|
||||
}
|
||||
let selected: Vec<_> = selection.guides.iter().map(|&index| GuideKey::new(index as u64)).collect();
|
||||
let guides: Vec<_> = original
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, guide)| {
|
||||
let mut value = Guide::new(GuideKey::new(index as u64), if guide.vertical { Axis::Y } else { Axis::X }, guide.pos);
|
||||
value.line = GuideLine::Dashed;
|
||||
value.span = Some((0.0, if guide.vertical { size.height } else { size.width }));
|
||||
value
|
||||
})
|
||||
.collect();
|
||||
let output = Guides::new("Guides", canvas, Bind::given(guides))
|
||||
.interactive(interactive)
|
||||
.selected_guides(&selected)
|
||||
.bounds(Rect::new(0.0, 0.0, size.width, size.height))
|
||||
.readout(GuideReadout::FromCentre)
|
||||
.show_at(ui, space.view.rect);
|
||||
let mut selected = output.select.map_or_else(
|
||||
|| app.guide_selection.guides.clone(),
|
||||
|key| key.and_then(|key| usize::try_from(key.get()).ok()).into_iter().collect(),
|
||||
);
|
||||
for event in &output.edit.events {
|
||||
if let EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } = event {
|
||||
let round = app.session.prefs.snap_to_grid && !craft::ui::runtime::pointer::frame(ui.ctx()).pick_mods.alt;
|
||||
match commit_guides(app, &original, after, round) {
|
||||
Ok(keys) => {
|
||||
selected = selected.into_iter().filter_map(|index| keys.iter().position(|key| key.get() == index as u64)).collect();
|
||||
app.guide_selection.represented = app.session.active().map(|st| st.doc.guides.clone()).unwrap_or_default();
|
||||
}
|
||||
Err(error) => {
|
||||
app.set_status(error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if interactive {
|
||||
app.guide_selection.guides = selected;
|
||||
}
|
||||
}
|
||||
|
||||
fn grid_fits(span: f32, step: f32) -> bool {
|
||||
span.is_finite() && span > 0.0 && step >= 1.0 && span / step <= 800.0
|
||||
}
|
||||
|
||||
/// Paints or hosts this canvas part over the slide picture.
|
||||
#[allow(dead_code)] // P3(canvas-w10): cv.A3
|
||||
pub(crate) fn show_grid(app: &mut crate::SlideApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace) {
|
||||
let _ = (app, ui, space);
|
||||
todo!("cv.A3")
|
||||
}
|
||||
|
||||
/// Paints or hosts this canvas part over the slide picture.
|
||||
#[allow(dead_code)] // P3(canvas-w10): cv.A3
|
||||
pub(crate) fn show_guides(app: &mut crate::SlideApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace) {
|
||||
let _ = (app, ui, space);
|
||||
todo!("cv.A3")
|
||||
fn commit_guides(app: &mut SlideApp, before: &[DrawGuide], after: &[Guide], round: bool) -> Result<Vec<GuideKey>, String> {
|
||||
let guides: Vec<_> = after
|
||||
.iter()
|
||||
.map(|guide| {
|
||||
let original = usize::try_from(guide.key.get()).ok().and_then(|index| before.get(index));
|
||||
// A click or an unmoved member of a group keeps its fractional position.
|
||||
let moved = original.is_none_or(|old| old.pos != guide.position);
|
||||
DrawGuide { vertical: guide.along == Axis::Y, pos: if round && moved { guide.position.round() } else { guide.position } }
|
||||
})
|
||||
.collect();
|
||||
if guides != before {
|
||||
app.run("guide.set", json!({"guides": guides}))?;
|
||||
}
|
||||
// Keys identify the input vector; surviving selections must follow the committed order.
|
||||
Ok(after.iter().map(|guide| guide.key).collect())
|
||||
}
|
||||
@@ -1,71 +1,96 @@
|
||||
//! Drawing guides driven with the mouse: View › Guides adds the centre guides, dragging one
|
||||
//! moves it (with its distance from the centre shown), dropping it off the slide deletes it.
|
||||
//! Guide commits preserve engine indices, round moved positions and ignore hidden guides.
|
||||
|
||||
use craft::ui::canvas_controls::CanvasControlWords;
|
||||
use craft::ui::runtime::env::Env;
|
||||
use deckcraft_engine::Session;
|
||||
use egui::{Modifiers, PointerButton};
|
||||
use egui_kittest::Harness;
|
||||
use egui::{Modifiers, PointerButton, Pos2};
|
||||
use egui_kittest::{Harness, kittest::Queryable as _};
|
||||
use serde_json::json;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use crate::{Services, SlideApp};
|
||||
|
||||
fn drag(h: &mut Harness<'_, SlideApp>, from: Pos2, to: Pos2) {
|
||||
h.hover_at(from);
|
||||
h.run_steps(1);
|
||||
h.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
for step in 1..=10 {
|
||||
h.event(egui::Event::PointerMoved(from.lerp(to, step as f32 / 10.0)));
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turn_guides_on_drag_one_and_drop_it_off_the_slide() {
|
||||
let _gpu = crate::gpu_lock::gpu_lock();
|
||||
let mut s = Session::with_new();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
// P3(canvas-w10): sh.A2
|
||||
let app = SlideApp::new_base(s, Services::default());
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut SlideApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
let mut session = Session::with_new();
|
||||
session.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
session.prefs.snap_to_grid = true;
|
||||
let mut h = crate::test_harness::harness_with(
|
||||
session,
|
||||
Services::default(),
|
||||
Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0),
|
||||
|_| {},
|
||||
);
|
||||
let words = Arc::new(OnceLock::new());
|
||||
let resolved_words = words.clone();
|
||||
h.ctx.on_end_pass(
|
||||
"guide commit rerun",
|
||||
Arc::new(move |ui: &mut egui::Ui| {
|
||||
resolved_words.get_or_init(|| Env::of(ui).words::<CanvasControlWords>());
|
||||
if ui.ctx().current_pass_index() == 0 {
|
||||
ui.ctx().request_discard("exercise guide commits across two passes");
|
||||
}
|
||||
}),
|
||||
);
|
||||
h.run_steps(3);
|
||||
let words = words.get().unwrap();
|
||||
h.state_mut().run("view.guides", json!({"on": true})).unwrap();
|
||||
h.run_steps(2);
|
||||
let guides = |h: &Harness<'_, SlideApp>| h.state().session.active().unwrap().doc.guides.clone();
|
||||
assert_eq!(guides(&h).len(), 2, "the two centre guides");
|
||||
let (slide, k) = (h.state().slide_rect.unwrap(), h.state().canvas_scale);
|
||||
let at = |x: f32, y: f32| slide.min + egui::vec2(x * k, y * k);
|
||||
let before = guides(&h);
|
||||
let vertical = before.iter().position(|guide| guide.vertical).unwrap();
|
||||
let horizontal = before.iter().position(|guide| !guide.vertical).unwrap();
|
||||
let (slide, scale) = (h.state().slide_rect().unwrap(), h.state().canvas_scale());
|
||||
let at = |x: f64, y: f64| slide.min + egui::vec2(x as f32 * scale, y as f32 * scale);
|
||||
let target = before[vertical].pos - 179.6;
|
||||
drag(&mut h, at(before[vertical].pos, 100.0), at(target, 100.0));
|
||||
let moved = guides(&h);
|
||||
assert!(moved[vertical].pos < before[vertical].pos);
|
||||
assert!((moved[vertical].pos - target.round()).abs() < 0.01, "the committed position rounds the drop to whole points");
|
||||
assert_eq!(moved[horizontal], before[horizontal], "the key moves only its own engine index");
|
||||
assert_eq!(h.state().guide_selection.guides.as_slice(), &[vertical]);
|
||||
|
||||
// Grab the vertical guide away from the horizontal one and drag it left.
|
||||
let start = at(480.0, 100.0);
|
||||
h.hover_at(start);
|
||||
drag(&mut h, at(700.0, before[horizontal].pos), at(700.0, -30.0));
|
||||
let remaining = guides(&h);
|
||||
assert_eq!(remaining.len(), before.len() - 1);
|
||||
assert!(remaining.iter().all(|guide| guide.vertical));
|
||||
assert!(h.query_by_label(words.vertical.as_str()).is_some());
|
||||
let on_guide = at(remaining[0].pos, 100.0);
|
||||
drag(&mut h, on_guide, on_guide);
|
||||
assert_eq!(h.state().guide_selection.guides.as_slice(), &[0]);
|
||||
|
||||
// A click has no geometry edit, even when the stored guide is between whole points.
|
||||
h.state_mut().run("guide.move", json!({"index": 0, "pos": target.round() + 0.25})).unwrap();
|
||||
h.run_steps(30);
|
||||
assert!(h.state().guide_selection.guides.is_empty(), "an external guide edit invalidates the old selection identity");
|
||||
let before_click = guides(&h);
|
||||
let press = at(before_click[0].pos, 100.0);
|
||||
h.event(egui::Event::PointerButton { pos: press, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
h.event(egui::Event::PointerButton { pos: start, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
for i in 1..=10 {
|
||||
h.event(egui::Event::PointerMoved(at(480.0 - 18.0 * i as f32, 100.0)));
|
||||
h.run_steps(1);
|
||||
}
|
||||
assert_eq!(h.state().session.tool.guide_drag, Some((0, 300.0)));
|
||||
if let Ok(img) = h.render() {
|
||||
let _ = img.save("/tmp/guides.png");
|
||||
}
|
||||
h.event(egui::Event::PointerButton { pos: at(300.0, 100.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.event(egui::Event::PointerButton { pos: press, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert_eq!(guides(&h)[0].pos, 300.0);
|
||||
assert_eq!(guides(&h), before_click);
|
||||
assert_eq!(h.state().guide_selection.guides.as_slice(), &[0]);
|
||||
|
||||
// Off the top of the slide with the horizontal guide: deleted.
|
||||
let g = at(700.0, 270.0);
|
||||
h.hover_at(g);
|
||||
h.run_steps(1);
|
||||
h.event(egui::Event::PointerButton { pos: g, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
for i in 1..=10 {
|
||||
h.event(egui::Event::PointerMoved(at(700.0, 270.0 - 30.0 * i as f32)));
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.event(egui::Event::PointerButton { pos: at(700.0, -30.0), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
assert_eq!(guides(&h).len(), 1);
|
||||
assert!(guides(&h)[0].vertical);
|
||||
|
||||
// Hidden guides stay in the file but aren't drawn or grabbed.
|
||||
h.state_mut().run("view.guides", json!({"on": false})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert!(!h.state().session.tool.guides_visible);
|
||||
assert_eq!(guides(&h).len(), 1);
|
||||
assert!(h.state().guide_selection.guides.is_empty());
|
||||
assert!(h.query_by_label(words.vertical.as_str()).is_none());
|
||||
drag(&mut h, at(before_click[0].pos, 100.0), at(before_click[0].pos - 80.0, 100.0));
|
||||
assert_eq!(guides(&h), before_click, "a hidden guide cannot be grabbed");
|
||||
}
|
||||
@@ -1,23 +1,32 @@
|
||||
//! The ruler's indent and tab markers driven with the mouse while editing text.
|
||||
//! Ruler and dialog edits map point positions, indents and tab kinds to one engine undo step.
|
||||
|
||||
use craft::text::ui::ruler::TextRulerWords;
|
||||
use craft::ui::runtime::env::Env;
|
||||
use deckcraft_engine::Session;
|
||||
use egui::{Modifiers, PointerButton, Pos2};
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::{Harness, kittest::Queryable as _};
|
||||
use serde_json::json;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use crate::{Services, SlideApp};
|
||||
|
||||
fn drag(h: &mut Harness<'_, SlideApp>, a: Pos2, b: Pos2) {
|
||||
drag_with_modifiers(h, a, b, Modifiers::NONE);
|
||||
}
|
||||
|
||||
fn drag_with_modifiers(h: &mut Harness<'_, SlideApp>, a: Pos2, b: Pos2, modifiers: Modifiers) {
|
||||
h.event(egui::Event::ModifiersChanged(modifiers));
|
||||
h.hover_at(a);
|
||||
h.run_steps(1);
|
||||
h.event(egui::Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE });
|
||||
h.event(egui::Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers });
|
||||
h.run_steps(1);
|
||||
for i in 1..=8 {
|
||||
h.event(egui::Event::PointerMoved(a + (b - a) * (i as f32 / 8.0)));
|
||||
h.run_steps(1);
|
||||
}
|
||||
h.event(egui::Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE });
|
||||
h.event(egui::Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers });
|
||||
h.run_steps(2);
|
||||
h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, SlideApp>, at: Pos2) {
|
||||
@@ -35,131 +44,148 @@ fn ruler(h: &mut Harness<'_, SlideApp>) -> serde_json::Value {
|
||||
#[test]
|
||||
fn drag_indents_add_move_and_remove_tabs_on_the_ruler() {
|
||||
let _gpu = crate::gpu_lock::gpu_lock();
|
||||
let mut s = Session::with_new();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let id = s.execute("insert.textBox", &json!({"rect": [100, 150, 500, 40]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.edit", &json!({"id": id})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "Name\tRole\tTeam"})).unwrap();
|
||||
// P3(canvas-w10): sh.A2
|
||||
let mut app = SlideApp::new_base(s, Services::default());
|
||||
app.ui.ruler = true;
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut SlideApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
let mut h = editing_harness();
|
||||
let words = Arc::new(OnceLock::new());
|
||||
let resolved_words = words.clone();
|
||||
h.ctx.on_end_pass(
|
||||
"ruler words",
|
||||
Arc::new(move |ui: &mut egui::Ui| {
|
||||
resolved_words.get_or_init(|| Env::of(ui).words::<TextRulerWords>());
|
||||
}),
|
||||
);
|
||||
h.run_steps(3);
|
||||
let (slide, k) = (h.state().slide_rect.unwrap(), h.state().canvas_scale);
|
||||
let x0 = ruler(&mut h)["x"].as_f64().unwrap() as f32;
|
||||
// The horizontal ruler runs along the top of the canvas.
|
||||
let top = h.state().canvas_rect.unwrap().min.y;
|
||||
let rx = |q: f32| slide.min.x + (x0 + q) * k;
|
||||
h.run_steps(1);
|
||||
let words = words.get().unwrap();
|
||||
let initial = ruler(&mut h);
|
||||
let (slide, scale) = (h.state().slide_rect().unwrap(), h.state().canvas_scale());
|
||||
let x0 = initial["x"].as_f64().unwrap() as f32;
|
||||
let rx = |q: f32| slide.min.x + (x0 + q) * scale;
|
||||
|
||||
// First-line indent triangle (top) to 36 pt.
|
||||
drag(&mut h, Pos2::new(rx(0.0), top + 3.0), Pos2::new(rx(36.0), top + 3.0));
|
||||
let first = h.get_by_label(words.first_line_indent.as_str()).rect().center();
|
||||
drag(&mut h, first, Pos2::new(rx(36.0), first.y));
|
||||
let r = ruler(&mut h);
|
||||
assert!((r["indent"].as_f64().unwrap() - 36.0).abs() <= 1.0, "{r}");
|
||||
assert_eq!(r["marginLeft"].as_f64(), Some(0.0));
|
||||
let first_line = r["marginLeft"].as_f64().unwrap() + r["indent"].as_f64().unwrap();
|
||||
assert!(r["indent"].as_f64().unwrap() > initial["indent"].as_f64().unwrap());
|
||||
assert!((first_line - 36.0).abs() <= 1.0, "the first marker follows the drop");
|
||||
assert_eq!(r["marginLeft"], initial["marginLeft"]);
|
||||
|
||||
// Hanging triangle (middle) to 18 pt: the first line stays at 36.
|
||||
drag(&mut h, Pos2::new(rx(0.0), top + 8.0), Pos2::new(rx(18.0), top + 8.0));
|
||||
let hanging = h.get_by_label(words.hanging_indent.as_str()).rect().center();
|
||||
drag(&mut h, hanging, Pos2::new(rx(18.0), hanging.y));
|
||||
let r = ruler(&mut h);
|
||||
let (ml, ind) = (r["marginLeft"].as_f64().unwrap(), r["indent"].as_f64().unwrap());
|
||||
assert!((ml - 18.0).abs() <= 1.0 && (ml + ind - 36.0).abs() <= 1.0, "{r}");
|
||||
let (left, indent) = (r["marginLeft"].as_f64().unwrap(), r["indent"].as_f64().unwrap());
|
||||
assert!((left - 18.0).abs() <= 1.0 && (left + indent - first_line).abs() <= 1.0, "hanging preserves the absolute first line: {r}");
|
||||
|
||||
// Click on the ruler: a left tab; drag it along; drag it off to remove it.
|
||||
click(&mut h, Pos2::new(rx(150.0), top + 12.0));
|
||||
let strip_y = h.get_by_label(words.left_indent.as_str()).rect().center().y;
|
||||
click(&mut h, Pos2::new(rx(144.0), strip_y));
|
||||
let r = ruler(&mut h);
|
||||
assert_eq!(r["tabs"].as_array().unwrap().len(), 1, "{r}");
|
||||
let pos = r["tabs"][0]["pos"].as_f64().unwrap() as f32;
|
||||
assert!((pos - 150.0).abs() <= 1.0);
|
||||
drag(&mut h, Pos2::new(rx(pos), top + 12.0), Pos2::new(rx(220.0), top + 12.0));
|
||||
let pos = ruler(&mut h)["tabs"][0]["pos"].as_f64().unwrap() as f32;
|
||||
assert!((pos - 220.0).abs() <= 1.0, "{pos}");
|
||||
if let Ok(img) = h.render() {
|
||||
let _ = img.save("/tmp/ruler.png");
|
||||
assert_eq!(r["tabs"].as_array().unwrap().len(), initial["tabs"].as_array().unwrap().len() + 1);
|
||||
let added = r["tabs"][0]["pos"].as_f64().unwrap() as f32;
|
||||
assert!((added - 144.0).abs() <= 1.0);
|
||||
let before_move = r["tabs"].clone();
|
||||
drag(&mut h, Pos2::new(rx(added), strip_y), Pos2::new(rx(216.0), strip_y));
|
||||
let r = ruler(&mut h);
|
||||
let moved = r["tabs"][0]["pos"].as_f64().unwrap() as f32;
|
||||
assert!(moved > added && (moved - 216.0).abs() <= 1.0);
|
||||
h.state_mut().session.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(ruler(&mut h)["tabs"], before_move, "a tab move is one undo step across both passes");
|
||||
h.state_mut().session.execute("edit.redo", &json!({})).unwrap();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().session.active().unwrap().selection.text.is_some());
|
||||
drag(&mut h, Pos2::new(rx(moved), strip_y), Pos2::new(rx(moved), strip_y + 80.0));
|
||||
assert_eq!(ruler(&mut h)["tabs"], initial["tabs"], "dragging off removes the stop");
|
||||
|
||||
h.state_mut()
|
||||
.session
|
||||
.execute("format.tabs", &json!({"set": [{"pos": 72}, {"pos": 144, "align": "ctr"}, {"pos": 216, "align": "dec"}]}))
|
||||
.unwrap();
|
||||
h.run_steps(2);
|
||||
let before_all = ruler(&mut h)["tabs"].clone();
|
||||
drag_with_modifiers(
|
||||
&mut h,
|
||||
Pos2::new(rx(72.0), strip_y),
|
||||
Pos2::new(rx(108.0), strip_y),
|
||||
Modifiers { ctrl: true, command: true, ..Modifiers::NONE },
|
||||
);
|
||||
let after_all = ruler(&mut h)["tabs"].clone();
|
||||
assert_eq!(after_all.as_array().unwrap().len(), before_all.as_array().unwrap().len());
|
||||
let shift = after_all[0]["pos"].as_f64().unwrap() - before_all[0]["pos"].as_f64().unwrap();
|
||||
assert!(shift > 0.0);
|
||||
for (before, after) in before_all.as_array().unwrap().iter().zip(after_all.as_array().unwrap()) {
|
||||
assert!((after["pos"].as_f64().unwrap() - before["pos"].as_f64().unwrap() - shift).abs() < 0.01);
|
||||
assert_eq!(after["align"], before["align"], "moving all stops preserves each kind");
|
||||
}
|
||||
assert!(h.state().session.active().unwrap().selection.text.is_some(), "still editing the text");
|
||||
drag(&mut h, Pos2::new(rx(pos), top + 12.0), Pos2::new(rx(pos), top + 80.0));
|
||||
assert!(ruler(&mut h)["tabs"].as_array().unwrap().is_empty());
|
||||
h.state_mut().session.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(ruler(&mut h)["tabs"], before_all, "moving all stops replaces the final vector in one undo step");
|
||||
}
|
||||
|
||||
fn editing_harness() -> Harness<'static, SlideApp> {
|
||||
let mut s = Session::with_new();
|
||||
s.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let id = s.execute("insert.textBox", &json!({"rect": [100, 150, 500, 40]})).unwrap()["id"].as_u64().unwrap();
|
||||
s.execute("text.edit", &json!({"id": id})).unwrap();
|
||||
s.execute("text.insert", &json!({"text": "Item\t9.50"})).unwrap();
|
||||
// P3(canvas-w10): sh.A2
|
||||
let mut app = SlideApp::new_base(s, Services::default());
|
||||
app.ui.ruler = true;
|
||||
let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut SlideApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
let mut session = Session::with_new();
|
||||
session.execute("slide.new", &json!({"layout": "blank"})).unwrap();
|
||||
let id = session.execute("insert.textBox", &json!({"rect": [100, 150, 500, 40]})).unwrap()["id"].as_u64().unwrap();
|
||||
session.execute("text.edit", &json!({"id": id})).unwrap();
|
||||
session.execute("text.insert", &json!({"text": "Item\t9.50"})).unwrap();
|
||||
let mut h = crate::test_harness::harness_with(
|
||||
session,
|
||||
Services::default(),
|
||||
Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0),
|
||||
|_| {},
|
||||
);
|
||||
h.state_mut().ui.ruler = true;
|
||||
h.ctx.on_end_pass(
|
||||
"ruler commit rerun",
|
||||
std::sync::Arc::new(|ui: &mut egui::Ui| {
|
||||
if ui.ctx().current_pass_index() == 0 {
|
||||
ui.ctx().request_discard("exercise ruler edits across two passes");
|
||||
}
|
||||
}),
|
||||
);
|
||||
h.run_steps(3);
|
||||
h
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tab_selector_picks_the_kind_of_stop_a_click_sets() {
|
||||
let _gpu = crate::gpu_lock::gpu_lock();
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut h = editing_harness();
|
||||
let (slide, k) = (h.state().slide_rect.unwrap(), h.state().canvas_scale);
|
||||
let x0 = ruler(&mut h)["x"].as_f64().unwrap() as f32;
|
||||
let top = h.state().canvas_rect.unwrap().min.y;
|
||||
let rx = |q: f32| slide.min.x + (x0 + q) * k;
|
||||
let corner = h.state().canvas_rect.unwrap().min + egui::vec2(8.0, 8.0);
|
||||
assert!(h.query_by_label("Left Tab").is_some());
|
||||
for _ in 0..3 {
|
||||
click(&mut h, corner);
|
||||
}
|
||||
assert!(h.query_by_label("Decimal Tab").is_some());
|
||||
click(&mut h, Pos2::new(rx(200.0), top + 12.0));
|
||||
let r = ruler(&mut h);
|
||||
assert_eq!(r["tabs"][0]["align"], "dec", "{r}");
|
||||
if let Ok(img) = h.render() {
|
||||
let _ = img.save("/tmp/ruler_decimal.png");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tabs_dialog_sets_clears_and_applies_on_ok() {
|
||||
let _gpu = crate::gpu_lock::gpu_lock();
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut h = editing_harness();
|
||||
h.state_mut().session.execute("format.tabs", &json!({"add": {"pos": 36}})).unwrap();
|
||||
h.state_mut().dialog = Some(crate::dialogs::Dialog::new("tabs"));
|
||||
let before = ruler(&mut h);
|
||||
h.state_mut().open_dialog("tabs", json!({}));
|
||||
h.run_steps(3);
|
||||
assert!(h.query_by_label_contains("0.50\"").is_some(), "the existing stop is listed");
|
||||
let d = h.state_mut().dialog.as_mut().unwrap();
|
||||
d.fields.insert("newpos".into(), "2".into());
|
||||
d.fields.insert("default".into(), "0.5".into());
|
||||
let ctx = h.ctx.clone();
|
||||
let new_stop = json!({"position": 144.0, "align": "center", "leader": "none"});
|
||||
let default_interval = 36.0;
|
||||
crate::dialogs::control(
|
||||
h.state_mut(),
|
||||
&ctx,
|
||||
"ui.dialog.set",
|
||||
&json!({"dialog": "top", "field": "stops", "value": [
|
||||
{"position": 36.0, "align": "left", "leader": "none"}, new_stop.clone()
|
||||
]}),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
crate::dialogs::control(h.state_mut(), &ctx, "ui.dialog.set", &json!({"dialog": "top", "field": "default_interval", "value": default_interval}))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
h.run_steps(1);
|
||||
assert_eq!(ruler(&mut h), before, "draft stops stay in the dialog until OK");
|
||||
crate::dialogs::control(
|
||||
h.state_mut(),
|
||||
&ctx,
|
||||
"ui.dialog.set",
|
||||
&json!({"dialog": "top", "field": "stops", "value": [new_stop.clone()]}),
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
h.run_steps(1);
|
||||
h.get_by_label("Center").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Set").click();
|
||||
h.run_steps(2);
|
||||
if let Ok(img) = h.render() {
|
||||
let _ = img.save("/tmp/tabs_dialog.png");
|
||||
}
|
||||
// Nothing changes until OK.
|
||||
assert_eq!(ruler(&mut h)["tabs"].as_array().unwrap().len(), 1);
|
||||
h.query_all_by_label("Clear").next().expect("a Clear button per stop").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("OK").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().dialog.is_none());
|
||||
assert!(!crate::dialogs::modal_open(&ctx));
|
||||
let r = ruler(&mut h);
|
||||
assert_eq!(r["tabs"].as_array().unwrap().len(), 1, "{r}");
|
||||
assert_eq!((r["tabs"][0]["pos"].as_f64(), r["tabs"][0]["align"].as_str()), (Some(144.0), Some("ctr")));
|
||||
assert_eq!(r["defaultTab"].as_f64(), Some(36.0));
|
||||
assert_eq!(r["tabs"].as_array().unwrap().len(), before["tabs"].as_array().unwrap().len());
|
||||
assert_eq!(r["tabs"][0]["pos"], new_stop["position"], "dialog point positions survive the app mapping");
|
||||
assert_eq!(r["tabs"][0]["align"], "ctr", "the framework Center maps to the engine's center code");
|
||||
assert!(r["defaultTab"].as_f64().unwrap() < before["defaultTab"].as_f64().unwrap());
|
||||
assert_eq!(r["defaultTab"], json!(default_interval));
|
||||
h.state_mut().session.execute("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(ruler(&mut h)["tabs"][0]["pos"].as_f64(), Some(36.0), "one undo step");
|
||||
assert_eq!(ruler(&mut h), before, "one undo restores both the stops and the default interval");
|
||||
}
|
||||
@@ -1,249 +1,111 @@
|
||||
use super::{Align2, Color32, CornerRadius, Point, Pos2, Rect, Sense, SlideApp, Stroke, Tokens, Ui, Xf, json, pos2, theme, vec2};
|
||||
use craft::behavior::kurbo::Point;
|
||||
use craft::behavior::{EditEvent, RulerUnits, Ticks};
|
||||
use craft::text::ui::DocUnit;
|
||||
use craft::text::ui::ruler::{ParagraphModel, RulerValues, TabAlign, TabLeader, TabStop, TextRuler};
|
||||
use craft::ui::canvas::{CanvasSpace, RulerText, Rulers};
|
||||
use craft::ui::contract::{Bind, Show as _};
|
||||
use craft::ui::runtime::env::UnitKind;
|
||||
use deckcraft_geom::Unit;
|
||||
use serde_json::json;
|
||||
|
||||
/// The ruler's numbered step in points and the ticks per step: quarter inches, or half
|
||||
/// centimetres. Any other unit (only a hand-edited `prefs.json` gives one) keeps inches, since a
|
||||
/// tick per point or pixel would be a solid bar.
|
||||
pub(crate) fn ruler_steps(unit: deckcraft_geom::Unit) -> (f64, u32) {
|
||||
match unit {
|
||||
deckcraft_geom::Unit::Centimeters => (unit.points_per_unit(), 2),
|
||||
_ => (72.0, 4),
|
||||
}
|
||||
}
|
||||
use crate::SlideApp;
|
||||
|
||||
pub(super) fn ruler(p: &egui::Painter, avail: Rect, slide: Rect, scale: f32, unit: deckcraft_geom::Unit, t: &Tokens) {
|
||||
let top = Rect::from_min_max(avail.min, pos2(avail.max.x, avail.min.y + 16.0));
|
||||
let left = Rect::from_min_max(avail.min, pos2(avail.min.x + 16.0, avail.max.y));
|
||||
p.rect_filled(top, CornerRadius::ZERO, t.card);
|
||||
p.rect_filled(left, CornerRadius::ZERO, t.card);
|
||||
let (step, sub) = ruler_steps(unit);
|
||||
let tick = step as f32 * scale / sub as f32;
|
||||
let len = |k: u32| {
|
||||
if k.is_multiple_of(sub) {
|
||||
8.0
|
||||
} else if k.is_multiple_of(2) {
|
||||
5.0
|
||||
} else {
|
||||
3.0
|
||||
}
|
||||
/// The document's unit scale and tick rule for both canvas rulers.
|
||||
// PLAN: plan error: canvas-w6 must supply ruler_text(prefs.units) to Canvas::rulers; Rulers owns no unit prop.
|
||||
pub(super) fn ruler_text(unit: Unit) -> RulerText {
|
||||
let kind = match unit {
|
||||
Unit::Inches => UnitKind::Inches,
|
||||
Unit::Centimeters => UnitKind::Centimetres,
|
||||
Unit::Points => UnitKind::Points,
|
||||
Unit::Pixels => UnitKind::Pixels,
|
||||
};
|
||||
let mut k = 0;
|
||||
loop {
|
||||
let x = slide.min.x + k as f32 * tick;
|
||||
if x > slide.max.x {
|
||||
break;
|
||||
}
|
||||
let h = len(k);
|
||||
p.line_segment([pos2(x, top.max.y - h), pos2(x, top.max.y)], Stroke::new(1.0, t.text_faint));
|
||||
if k.is_multiple_of(sub) {
|
||||
p.text(pos2(x + 2.0, top.min.y + 1.0), Align2::LEFT_TOP, format!("{}", k / sub), theme::font(8.0), t.text_dim);
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
let mut k = 0;
|
||||
loop {
|
||||
let y = slide.min.y + k as f32 * tick;
|
||||
if y > slide.max.y {
|
||||
break;
|
||||
}
|
||||
let w = len(k);
|
||||
p.line_segment([pos2(left.max.x - w, y), pos2(left.max.x, y)], Stroke::new(1.0, t.text_faint));
|
||||
k += 1;
|
||||
}
|
||||
RulerText::new(RulerUnits::new(1.0 / unit.points_per_unit(), Ticks::decimal(unit == Unit::Pixels)), kind)
|
||||
}
|
||||
|
||||
/// What is being dragged on the ruler.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum RulerDrag {
|
||||
/// First-line indent (the top triangle).
|
||||
First,
|
||||
/// Hanging indent (the bottom triangle): moves the left indent, the first line stays put.
|
||||
Hanging,
|
||||
/// Left indent (the box under the hanging triangle): moves both together.
|
||||
Left,
|
||||
/// The tab stop that was at this position (pt from the text area's left).
|
||||
Tab(f64),
|
||||
/// Builds display-only rulers whose origin stays at the slide origin.
|
||||
pub(crate) fn rulers(app: &SlideApp) -> Option<Rulers<'static>> {
|
||||
app.ui.ruler.then(|| Rulers::new("Rulers", Bind::given(Point::ZERO)).origin_locked(true).interactive(false))
|
||||
}
|
||||
|
||||
/// The paragraph's indents and tab stops on the horizontal ruler while text is being edited,
|
||||
/// draggable as in PowerPoint; a click on the ruler adds a left tab, dragging a tab off the
|
||||
/// ruler removes it.
|
||||
pub(super) fn ruler_markers(app: &mut SlideApp, ui: &mut Ui, p: &egui::Painter, avail: Rect, xf: Xf, t: &Tokens) {
|
||||
if app.session.active().is_none_or(|d| d.selection.text.is_none()) {
|
||||
/// Hosts the paragraph ruler over the full canvas's top strip, outside the clipped picture body.
|
||||
pub(crate) fn show_text_ruler(app: &mut SlideApp, ui: &mut egui::Ui, space: &CanvasSpace, full: egui::Rect) {
|
||||
if !app.ui.ruler || app.session.active().is_none_or(|st| st.selection.text.is_none()) {
|
||||
return;
|
||||
}
|
||||
let Ok(info) = app.session.execute("format.ruler", &json!({})) else { return };
|
||||
if info["rotated"].as_bool().unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let f = |k: &str| info[k].as_f64().filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let (x0, width, ml, ind) = (f("x"), f("width"), f("marginLeft"), f("indent"));
|
||||
let tabs: Vec<(f64, String)> = info["tabs"]
|
||||
let number = |key: &str| info[key].as_f64().filter(|v| v.is_finite()).unwrap_or(0.0);
|
||||
let mut values = RulerValues::default();
|
||||
values.left_indent = number("marginLeft") as f32;
|
||||
values.first_line_indent = number("indent") as f32;
|
||||
values.stops = info["tabs"]
|
||||
.as_array()
|
||||
.map(|a| a.iter().filter_map(|t| Some((t["pos"].as_f64()?, t["align"].as_str().unwrap_or("l").to_string()))).collect())
|
||||
.unwrap_or_default();
|
||||
let top = Rect::from_min_max(pos2(avail.min.x + 16.0, avail.min.y), pos2(avail.max.x, avail.min.y + 16.0));
|
||||
let sx = |q: f64| xf.to_screen(Point::new(x0 + q, 0.0)).x;
|
||||
let to_q = |x: f32| ((xf.to_slide(pos2(x, 0.0)).x - x0).clamp(0.0, width.max(0.0)) * 2.0).round() / 2.0;
|
||||
// The text area's span, outlined on the ruler.
|
||||
let area = Rect::from_min_max(pos2(sx(0.0), top.min.y + 2.0), pos2(sx(width), top.max.y - 1.0)).intersect(top);
|
||||
p.rect_stroke(area, CornerRadius::ZERO, Stroke::new(1.0, t.text_faint.gamma_multiply(0.5)), egui::StrokeKind::Inside);
|
||||
|
||||
let resp = ui.interact(top, ui.scope_id().with("ruler_markers"), Sense::click_and_drag());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, "Text ruler"));
|
||||
let id = ui.scope_id().with("ruler_drag");
|
||||
let mut drag: Option<RulerDrag> = ui.data(|d| d.get_temp::<RulerDrag>(id));
|
||||
let pointer = resp.interact_pointer_pos().or(resp.hover_pos());
|
||||
if resp.drag_started()
|
||||
&& let Some(at) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos())
|
||||
{
|
||||
let near = |q: f64| (sx(q) - at.x).abs() <= 5.0;
|
||||
let y = at.y - top.min.y;
|
||||
drag = if let Some((pos, _)) = tabs.iter().find(|(pos, _)| near(*pos) && y >= 8.0) {
|
||||
Some(RulerDrag::Tab(*pos))
|
||||
} else if y < 6.0 && near(ml + ind) {
|
||||
Some(RulerDrag::First)
|
||||
} else if (6.0..11.0).contains(&y) && near(ml) {
|
||||
Some(RulerDrag::Hanging)
|
||||
} else if y >= 11.0 && near(ml) {
|
||||
Some(RulerDrag::Left)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
ui.data_mut(|d| match drag {
|
||||
Some(v) => {
|
||||
d.insert_temp(id, v);
|
||||
}
|
||||
None => {
|
||||
d.remove::<RulerDrag>(id);
|
||||
}
|
||||
});
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|stop| {
|
||||
let position = stop["pos"].as_f64()? as f32;
|
||||
Some(TabStop::new(position, tab_align(stop["align"].as_str().unwrap_or("l")), TabLeader::None))
|
||||
})
|
||||
.collect();
|
||||
let (top, _, corner) = Rulers::strips(ui, full);
|
||||
let unit = app.session.prefs.units;
|
||||
let output = TextRuler::new("Text ruler", Bind::given(values.clone()), number("width") as f32)
|
||||
.model(ParagraphModel::TextBox)
|
||||
.corner(corner)
|
||||
.scale(space.view.zoom as f32)
|
||||
.origin(space.view.to_screen(Point::new(number("x"), 0.0)).x)
|
||||
.unit(DocUnit::new(ruler_text(unit).kind, UnitKind::POINTS_PER_INCH / Unit::Pixels.points_per_unit()))
|
||||
.kind(app.ruler_tab_kind)
|
||||
.show_at(ui, top.union(corner));
|
||||
if let Some(kind) = output.kind {
|
||||
app.ruler_tab_kind = kind;
|
||||
}
|
||||
// Where each marker is drawn: the dragged one follows the pointer.
|
||||
let live = drag.zip(pointer.filter(|_| resp.dragged())).map(|(d, at)| (d, to_q(at.x), at.y > top.max.y + 20.0));
|
||||
let (mut first, mut left) = (ml + ind, ml);
|
||||
match live {
|
||||
Some((RulerDrag::First, q, _)) => first = q,
|
||||
Some((RulerDrag::Hanging, q, _)) => left = q,
|
||||
Some((RulerDrag::Left, q, _)) => {
|
||||
first = q + ind;
|
||||
left = q;
|
||||
}
|
||||
_ => {}
|
||||
if output.open_tabs_dialog {
|
||||
app.open_dialog("tabs", json!({}));
|
||||
}
|
||||
let col = t.text_dim;
|
||||
let tri = |x: f32, y0: f32, down: bool| {
|
||||
let (a, b) = if down { (y0, y0 + 5.0) } else { (y0 + 5.0, y0) };
|
||||
p.add(egui::Shape::convex_polygon(vec![pos2(x - 4.0, a), pos2(x + 4.0, a), pos2(x, b)], t.card, Stroke::new(1.0, col)));
|
||||
};
|
||||
tri(sx(first), top.min.y + 1.0, true);
|
||||
tri(sx(left), top.min.y + 6.0, false);
|
||||
p.rect(
|
||||
Rect::from_min_max(pos2(sx(left) - 4.0, top.min.y + 11.5), pos2(sx(left) + 4.0, top.max.y - 0.5)),
|
||||
CornerRadius::ZERO,
|
||||
t.card,
|
||||
Stroke::new(1.0, col),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
for (pos, align) in &tabs {
|
||||
let (q, gone) = match live {
|
||||
Some((RulerDrag::Tab(from), q, off)) if (from - pos).abs() < 0.5 => (q, off),
|
||||
_ => (*pos, false),
|
||||
};
|
||||
if gone {
|
||||
continue;
|
||||
}
|
||||
tab_glyph(p, pos2(sx(q), top.max.y - 2.0), align, t.text);
|
||||
}
|
||||
// The tab selector in the ruler's corner: a click cycles left, center, right, decimal; a click
|
||||
// on the ruler then sets that kind of stop.
|
||||
let kind_id = ui.scope_id().with("ruler_tab_kind");
|
||||
let mut kind: usize = ui.data(|d| d.get_temp(kind_id)).unwrap_or(0);
|
||||
let corner = Rect::from_min_size(avail.min, vec2(16.0, 16.0));
|
||||
let cr = ui.interact(corner, ui.scope_id().with("ruler_tab_selector"), Sense::click());
|
||||
const KINDS: [(&str, &str); 4] = [("l", "Left Tab"), ("ctr", "Center Tab"), ("r", "Right Tab"), ("dec", "Decimal Tab")];
|
||||
if cr.clicked() {
|
||||
kind = (kind + 1) % KINDS.len();
|
||||
ui.data_mut(|d| d.insert_temp(kind_id, kind));
|
||||
}
|
||||
let (kind_align, kind_label) = KINDS[kind % KINDS.len()];
|
||||
cr.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, kind_label));
|
||||
let cr = cr.on_hover_text(format!("{kind_label} (click to change)"));
|
||||
p.rect_stroke(
|
||||
corner.shrink(2.0),
|
||||
CornerRadius::same(2),
|
||||
Stroke::new(1.0, if cr.hovered() { t.accent } else { t.text_faint }),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
tab_glyph(p, pos2(corner.center().x - 1.0, corner.center().y + 3.0), kind_align, t.text);
|
||||
if drag.is_some() {
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
|
||||
}
|
||||
|
||||
// Commit on release; a click on bare ruler adds a left tab.
|
||||
if resp.drag_stopped() {
|
||||
if let (Some(d), Some(at)) = (drag, pointer) {
|
||||
let q = to_q(at.x);
|
||||
let r = match d {
|
||||
RulerDrag::First => app.run("format.paragraph", json!({"indentFirst": q - ml})),
|
||||
RulerDrag::Hanging => app.run("format.paragraph", json!({"indentLeft": q, "indentFirst": ml + ind - q})),
|
||||
RulerDrag::Left => app.run("format.paragraph", json!({"indentLeft": q})),
|
||||
RulerDrag::Tab(from) if at.y > top.max.y + 20.0 => app.run("format.tabs", json!({"remove": from})),
|
||||
RulerDrag::Tab(from) => app.run("format.tabs", json!({"move": {"from": from, "to": q}})),
|
||||
};
|
||||
if let Err(e) = r {
|
||||
app.set_status(e);
|
||||
}
|
||||
}
|
||||
ui.data_mut(|d| d.remove::<RulerDrag>(id));
|
||||
} else if resp.clicked()
|
||||
&& let Some(at) = resp.interact_pointer_pos()
|
||||
&& at.x >= area.min.x
|
||||
&& at.x <= area.max.x
|
||||
{
|
||||
let near_tab = tabs.iter().any(|(pos, _)| (sx(*pos) - at.x).abs() <= 5.0);
|
||||
if resp.double_clicked() || near_tab {
|
||||
// A double-click on a stop opens the Tabs dialog, as in PowerPoint.
|
||||
if resp.double_clicked() {
|
||||
app.dialog = Some(crate::dialogs::Dialog::new("tabs"));
|
||||
}
|
||||
} else {
|
||||
let _ = app.run("format.tabs", json!({"add": {"pos": to_q(at.x), "align": kind_align}}));
|
||||
for event in &output.edit.events {
|
||||
if let EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } = event
|
||||
&& let Err(error) = commit_values(app, &values, after)
|
||||
{
|
||||
app.set_status(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A tab-stop mark with its foot at `at`: └ left, ┴ center, ┘ right, ┴ with a dot decimal.
|
||||
fn tab_glyph(p: &egui::Painter, at: Pos2, align: &str, col: Color32) {
|
||||
let (x, y) = (at.x, at.y);
|
||||
let st = Stroke::new(1.5, col);
|
||||
p.line_segment([pos2(x, y - 6.0), pos2(x, y)], st);
|
||||
match align {
|
||||
"r" => {
|
||||
p.line_segment([pos2(x - 5.0, y), pos2(x, y)], st);
|
||||
fn commit_values(app: &mut SlideApp, before: &RulerValues, after: &RulerValues) -> Result<(), String> {
|
||||
let left = after.left_indent != before.left_indent;
|
||||
let first = after.first_line_indent != before.first_line_indent;
|
||||
if left || first {
|
||||
let mut params = json!({});
|
||||
if left {
|
||||
params["indentLeft"] = json!(after.left_indent);
|
||||
}
|
||||
"ctr" => {
|
||||
p.line_segment([pos2(x - 4.0, y), pos2(x + 4.0, y)], st);
|
||||
}
|
||||
"dec" => {
|
||||
p.line_segment([pos2(x - 4.0, y), pos2(x + 4.0, y)], st);
|
||||
p.circle_filled(pos2(x + 3.0, y - 4.0), 1.0, col);
|
||||
}
|
||||
_ => {
|
||||
p.line_segment([pos2(x, y), pos2(x + 5.0, y)], st);
|
||||
if first {
|
||||
// First is relative to Left: hanging from ml to q keeps ml + ind fixed.
|
||||
params["indentFirst"] = json!(after.first_line_indent);
|
||||
}
|
||||
app.run("format.paragraph", params)?;
|
||||
}
|
||||
if after.stops != before.stops {
|
||||
let stops: Vec<_> = after.stops.iter().map(|stop| json!({"pos": stop.position, "align": align_code(stop.align)})).collect();
|
||||
app.run("format.tabs", json!({"set": stops}))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Paints or hosts this canvas part over the slide picture.
|
||||
#[allow(dead_code)] // P3(canvas-w10): cv.A3
|
||||
pub(crate) fn show_text_ruler(app: &mut crate::SlideApp, ui: &mut egui::Ui, space: &craft::ui::canvas::CanvasSpace) {
|
||||
let _ = (app, ui, space);
|
||||
todo!("cv.A3")
|
||||
const TAB_ALIGNS: [(&str, TabAlign); 4] = [
|
||||
("l", TabAlign::Left),
|
||||
("ctr", TabAlign::Center),
|
||||
("r", TabAlign::Right),
|
||||
("dec", TabAlign::Decimal),
|
||||
];
|
||||
|
||||
fn tab_align(code: &str) -> TabAlign {
|
||||
TAB_ALIGNS.iter().find(|(name, _)| *name == code).map_or(TabAlign::Left, |(_, align)| *align)
|
||||
}
|
||||
|
||||
/// Builds the canvas rulers with owned values.
|
||||
#[allow(dead_code)] // P3(canvas-w10): cv.A3
|
||||
pub(crate) fn rulers(app: &crate::SlideApp) -> Option<craft::ui::canvas::Rulers<'static>> {
|
||||
let _ = app;
|
||||
todo!("cv.A3")
|
||||
fn align_code(align: TabAlign) -> &'static str {
|
||||
TAB_ALIGNS.iter().find(|(_, kind)| *kind == align).map_or("l", |(code, _)| *code)
|
||||
}
|
||||
Reference in new issue
Block a user