Shapes: select, resize from every handle and rotate (#1321)

* Shapes: rotation in the model, XLSX and object.move

Shape gains `rotation` (degrees clockwise about its centre, serde
default 0 so older workbooks load). XLSX reads and writes it as the
shape's `a:xfrm rot`. `object.move` takes `rotation` for shapes and
refuses it for charts, pictures and slicers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* UI: select, resize and rotate shapes with a full frame

A selected shape showed no frame, so clicking it looked like nothing
happened; only text boxes drew one. Every selected object now draws
the frame with eight resize handles (corners only on small frames),
and shapes add a rotation handle above the top edge.

- Each handle resizes from its own side; the opposite side stays put.
  Shift keeps the aspect ratio on a corner.
- The rotation handle turns the shape; Shift snaps to 15 degrees.
- A turned shape paints, hit-tests and resizes along its own axes.
- Each handle shows the cursor for its direction; the body shows Move.
- Arrow keys nudge the selected object 6 pt (Ctrl/Alt: 1 pt), Escape
  deselects it, Enter/F2 edits a text box.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Shape text test: the new rotation field starts at zero

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Shapes: keep flat lines flat, Ctrl+arrow nudges, finite rotation, ink does not rotate

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Shapes: no resize handles on ink, handles act only over cells, arrows follow the screen on right-to-left sheets

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Merge upstream main into fix/shape-select-rotate

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Print rotated shapes and shape text

* Fix rotated PDF regression assertion

* Fix protected rotation and flat-line resizing

* Format shape rotation regression changes

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Fluorine <joseph.anglada92@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-11-19 00:00:18 -06:00
1 parent 3b06206327
commit 952a3b3f34
25 files changed
+908 -29

No files matched your search

+1
View File
@@ -96,6 +96,7 @@ fn stroke(s: &mut Session, p: &Json) -> Result<Json> {
line: Color::from_hex(&color).unwrap_or(Color::rgb(0x1F, 0x5F, 0xC9)),
text,
format: Default::default(),
rotation: 0.0,
};
edit(s, |cx| {
cx.sheet_mut(si)?.shapes.push(shape);
+1
View File
@@ -95,6 +95,7 @@ fn insert_equation(s: &mut Session, p: &Json) -> Result<Json> {
text: latex.to_string(),
format: Default::default(),
math: Default::default(),
rotation: 0.0,
};
shape.math.refresh(latex);
let sheet = d.wb.active_sheet();
+1 -1
View File
@@ -164,7 +164,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Move Object",
[],
None,
"{kind: chart|image|shape|slicer|equation|control, id, at?: \"C3\", dx?, dy?, width?, height? (each at most 10,000 points, or the object's current size when a file made it larger)}",
"{kind: chart|image|shape|slicer|equation|control, id, at?: \"C3\", dx?, dy?, width?, height? (each at most 10,000 points, or the object's current size when a file made it larger), rotation?: degrees clockwise (shapes, not ink)}",
has_doc,
move_object
),
@@ -358,6 +358,7 @@ pub(super) fn insert_icon(s: &mut Session, p: &Json) -> Result<Json> {
line: Color::Auto,
text: name,
format: Default::default(),
rotation: 0.0,
math: Default::default(),
};
let sheet = d.wb.active_sheet();
+16
View File
@@ -163,6 +163,7 @@ pub(super) fn insert_shape(s: &mut Session, p: &Json) -> Result<Json> {
line,
text: str_param(p, "text").unwrap_or("").into(),
format: Default::default(),
rotation: 0.0,
math: Default::default(),
};
let sheet = d.wb.active_sheet();
@@ -237,6 +238,16 @@ pub(super) fn delete_object(s: &mut Session, p: &Json) -> Result<Json> {
pub(super) fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
let (sheet, o) = object_param(s, p, "object.move")?;
let at = cell_param(s, p, "at")?;
let rotation = f64_param(p, "rotation").filter(|v| v.is_finite());
if rotation.is_some() {
let ink = s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.shapes.iter().any(|x| x.id == o.id && x.kind == ShapeKind::Ink));
if o.kind != ObjKind::Shape || ink {
return Err(bad("object.move", "only shapes other than ink rotate"));
}
if s.doc()?.wb.sheet(sheet).is_some_and(|sh| sh.is_protected()) {
return Err(EngineError::Other(PROTECTED.into()));
}
}
edit(s, |cx| {
let Some(a) = cx.sheet_mut(sheet)?.object_anchor_mut(o) else { return Err(bad("object.move", "no such object")) };
if let Some(at) = at {
@@ -254,6 +265,11 @@ pub(super) fn move_object(s: &mut Session, p: &Json) -> Result<Json> {
if let Some(v) = f64_param(p, "height") {
a.height = v.clamp(0.0, size_cap(a.height)) as f32;
}
if let Some(r) = rotation
&& let Some(shape) = cx.sheet_mut(sheet)?.shapes.iter_mut().find(|x| x.id == o.id)
{
shape.rotation = r.rem_euclid(360.0) as f32;
}
Ok(Json::Null)
})
}
+26 -10
View File
@@ -1,6 +1,6 @@
use super::draw::{Block, PdfMeasure, Xf, draw_prims, rgb_of};
use super::text::wrap_lines;
use super::{Anchor, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook};
use super::{Anchor, Baseline, Font, Page, Point, RangeRef, Rect, ShapeKind, Sheet, TextDirection, Value, Workbook};
/// Cell pictures fit the current cell (or merged-cell) rectangle without changing aspect ratio.
pub(super) fn draw_cell_picture(pg: &mut Page, data: &[u8], rect: (f32, f32, f32, f32), k: f32) {
@@ -175,29 +175,42 @@ fn draw_sparklines(pg: &mut Page, wb: &Workbook, si: usize, sh: &Sheet, b: &Bloc
fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Block, (x, y, w, h): (f32, f32, f32, f32)) {
let fill = rgb_of(shp.fill, wb);
let line = rgb_of(shp.line, wb).filter(|_| !shp.format.no_line).map(|c| (c, (0.75 * b.k).max(0.25)));
let angle = if shp.rotation.is_finite() { shp.rotation.to_radians() } else { 0.0 };
let (sn, cs) = angle.sin_cos();
let (cx, cy) = (x + w / 2.0, y + h / 2.0);
let turn = |[px, py]: [f32; 2]| {
let (dx, dy) = (px - cx, py - cy);
[cx + dx * cs - dy * sn, cy + dx * sn + dy * cs]
};
match shp.kind {
ShapeKind::Ellipse => {
let pts: Vec<[f32; 2]> = (0..72)
.map(|i| {
let a = i as f32 / 72.0 * std::f32::consts::TAU;
[x + w / 2.0 + w / 2.0 * a.cos(), y + h / 2.0 + h / 2.0 * a.sin()]
turn([x + w / 2.0 + w / 2.0 * a.cos(), y + h / 2.0 + h / 2.0 * a.sin()])
})
.collect();
pg.polygon(&pts, fill, line);
}
ShapeKind::Triangle => pg.polygon(&[[x + w / 2.0, y], [x + w, y + h], [x, y + h]], fill, line),
ShapeKind::Triangle => {
let pts = [[x + w / 2.0, y], [x + w, y + h], [x, y + h]].map(turn);
pg.polygon(&pts, fill, line);
}
ShapeKind::Line | ShapeKind::Arrow => {
let c = line.map(|l| l.0).or(fill).unwrap_or([0, 0, 0]);
pg.stroke_line(x, y, x + w, y + h, (1.0 * b.k).max(0.3), c);
let [x0, y0] = turn([x, y]);
let [x1, y1] = turn([x + w, y + h]);
pg.stroke_line(x0, y0, x1, y1, (1.0 * b.k).max(0.3), c);
if shp.kind == ShapeKind::Arrow {
let ang = h.atan2(w);
let al = 8.0 * b.k;
let p = |da: f32| [x + w - al * (ang + da).cos(), y + h - al * (ang + da).sin()];
pg.polygon(&[[x + w, y + h], p(0.4), p(-0.4)], Some(c), None);
let p = |da: f32| turn([x + w - al * (ang + da).cos(), y + h - al * (ang + da).sin()]);
pg.polygon(&[turn([x + w, y + h]), p(0.4), p(-0.4)], Some(c), None);
}
}
_ => {
pg.polygon(&[[x, y], [x + w, y], [x + w, y + h], [x, y + h]], fill, line);
let pts = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]].map(turn);
pg.polygon(&pts, fill, line);
}
}
if shp.text.is_empty() {
@@ -228,7 +241,8 @@ fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Bl
// WordArt's drop shadow: the line again, offset, in the shadow colour (under the text).
if let Some(sc) = fm.text_shadow.and_then(|c| rgb_of(c, wb)) {
let off = (size * 0.06).max(0.5);
pg.text_with_direction(Point::new(lx + off, yy + off), size, font, sc, &l.text, l.direction);
let [sx, sy] = turn([lx + off, yy + off]);
pg.text_rotated_with_direction(Baseline { origin: Point::new(sx, sy), angle }, size, font, sc, &l.text, l.direction);
}
// WordArt's text outline, as on screen: the line in the outline colour, offset in eight
// directions by half the outline width, under the filled text.
@@ -237,10 +251,12 @@ fn draw_shape(pg: &mut Page, wb: &Workbook, shp: &gridcraft_model::Shape, b: &Bl
{
let d = (ow * b.scale / 2.0).clamp(0.25, 20.0);
for (dx, dy) in [(-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (-1.0, 0.0), (1.0, 0.0), (-1.0, 1.0), (0.0, 1.0), (1.0, 1.0)] {
pg.text_with_direction(Point::new(lx + dx * d, yy + dy * d), size, font, oc, &l.text, l.direction);
let [ox, oy] = turn([lx + dx * d, yy + dy * d]);
pg.text_rotated_with_direction(Baseline { origin: Point::new(ox, oy), angle }, size, font, oc, &l.text, l.direction);
}
}
pg.text_with_direction(Point::new(lx, yy), size, font, color, &l.text, l.direction);
let [tx, ty] = turn([lx, yy]);
pg.text_rotated_with_direction(Baseline { origin: Point::new(tx, ty), angle }, size, font, color, &l.text, l.direction);
yy += size * 1.2;
}
}
+28
View File
@@ -88,6 +88,34 @@ fn pdf_export_keeps_safe_links_on_their_printed_pages() {
assert!(!cropped.contains("/Dest ["));
}
#[test]
fn pdf_export_rotates_a_shape_outline_and_its_text() {
let make_page = |rotation| {
let mut s = s();
let id = s
.execute(
"insert.shape",
json!({"kind": "rectangle", "at": "A1", "width": 120, "height": 60, "text": "TURNED", "fill": "#FF0000", "line": "#0000FF"}),
)
.unwrap()["shape"]
.as_u64()
.unwrap();
if rotation != 0 {
s.execute("object.move", json!({"kind": "shape", "id": id, "at": "A1", "rotation": rotation})).unwrap();
}
pdf_pages(&mut s).remove(0)
};
let upright = make_page(0);
let turned = make_page(90);
let red_path = |page: &str| {
let start = page.find("1 0 0 rg").expect("red rectangle fill");
let tail = &page[start..];
let end = tail.find(" B").expect("filled and stroked rectangle path") + 2;
tail[..end].to_string()
};
assert_ne!(red_path(&upright), red_path(&turned), "the rectangle's printed outline is rotated");
assert!(turned.contains("0 -1 1 0") && turned.contains("(TURNED) Tj"), "shape text uses the rotation matrix: {turned}");
}
#[test]
fn arabic_with_characters_its_font_lacks_still_exports() {
let mut s = s();
+1
View File
@@ -194,6 +194,7 @@ fn insert_word_art(s: &mut Session, p: &Json) -> Result<Json> {
text: text.clone(),
format: ShapeFormat { no_line: true, align: Some(ShapeTextAlign::Center), anchor: Some(ShapeTextAnchor::Middle), ..Default::default() },
math: Default::default(),
rotation: 0.0,
};
apply("insert.wordArt", &mut shape, Some(style), p)?;
// Default box: the longest line at the font size (about 0.62 em per character) plus padding.
+50
View File
@@ -5790,6 +5790,56 @@ fn filtered_copy_with_many_runs_moves_notes_and_merges_with_their_rows() {
assert_eq!(sh.merges.iter().filter(|m| m.start.col >= 7).count(), 1);
}
#[test]
fn object_move_refuses_to_rotate_ink() {
let mut s = s();
let id = s.execute("draw.stroke", json!({"points": [[0, 0], [30, 20], [60, 5]]})).unwrap()["shape"].clone();
assert!(s.execute("object.move", json!({"kind": "shape", "id": id, "rotation": 45})).is_err());
assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 0.0);
}
#[test]
fn object_move_rotates_shapes_only() {
let mut s = s();
let id = s.execute("insert.shape", json!({"kind": "rectangle"})).unwrap()["shape"].clone();
s.execute("object.move", json!({"kind": "shape", "id": id, "rotation": -30})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 330.0);
s.execute("edit.undo", json!({})).unwrap();
assert_eq!(s.doc().unwrap().wb.active().unwrap().shapes[0].rotation, 0.0);
s.execute("selection.set", json!({"range": "A1"})).unwrap();
s.execute("cell.set", json!({"cell": "A1", "input": "1"})).unwrap();
let chart = s.execute("insert.chart", json!({"type": "column"})).unwrap()["chart"].clone();
assert!(s.execute("object.move", json!({"kind": "chart", "id": chart, "rotation": 45})).is_err());
}
#[test]
fn object_move_rotation_respects_sheet_protection() {
let mut s = s();
let id = s.execute("insert.shape", json!({"kind": "rectangle", "at": "A1"})).unwrap()["shape"].clone();
let id_num = id.as_u64().unwrap() as u32;
let shape_state = |session: &Session| {
let doc = session.doc().unwrap();
let shape = doc.wb.active().unwrap().shapes.iter().find(|shape| shape.id == id_num).unwrap();
(shape.anchor, shape.rotation)
};
// Rotation remains available on an unprotected sheet.
s.execute("object.move", json!({"kind": "shape", "id": id_num, "at": "B2", "rotation": 45})).unwrap();
let (anchor, rotation) = shape_state(&s);
assert_eq!(rotation, 45.0);
assert_eq!(anchor.cell, CellRef::parse("B2").unwrap());
s.execute("edit.undo", json!({})).unwrap();
s.execute("review.protectSheet", json!({})).unwrap();
let before = shape_state(&s);
let undo_len = s.doc().unwrap().undo.len();
let result = s.execute("object.move", json!({"kind": "shape", "id": id_num, "at": "C3", "rotation": 90}));
assert!(result.is_err(), "rotation should be rejected on a protected sheet");
assert_eq!(shape_state(&s), before, "a rejected rotation leaves the shape unchanged");
assert_eq!(s.doc().unwrap().undo.len(), undo_len);
}
#[test]
fn editing_quote_prefixed_text_keeps_it_text() {
let mut s = s();
+3
View File
@@ -690,6 +690,9 @@ pub struct Shape {
/// Outline visibility and text formatting (DrawingML `a:ln`, `a:bodyPr`, `a:pPr`, `a:rPr`).
#[serde(default)]
pub format: ShapeFormat,
/// Degrees clockwise about the anchor rect's centre, in `[0, 360)`.
#[serde(default)]
pub rotation: f32,
/// An equation's layout, rebuilt from `text` and never saved.
#[serde(skip)]
pub math: EquationCache,
+1
View File
@@ -946,6 +946,7 @@ mod tests {
fill: Color::default(),
line: Color::default(),
text: String::new(),
rotation: 0.0,
format: ShapeFormat::default(),
math: EquationCache::default(),
}),
+96 -11
View File
@@ -388,6 +388,9 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
if label && !sp.text.is_empty() && !app.editing_text_box(sp.id) {
paint_shape_text(p, wb, sp, r, geo.z);
}
if sp.rotation != 0.0 {
turn_painted(p, start, r.center(), sp.rotation);
}
done(start, r);
}
for im in &sh.images {
@@ -431,11 +434,13 @@ pub(crate) fn paint_objects(app: &SheetApp, p: &Painter, geo: &Geo, wb: &Arc<Wor
}
// The selected object's frame and handles go over every object, and move with it on a
// right-to-left sheet.
if let Some(r) = app.selected_object.and_then(|o| object_rect(geo, sh, o))
if let Some(o) = app.selected_object
&& let Some(r) = object_rect(geo, sh, o)
&& r.intersects(p.clip_rect())
{
let start = p.add(egui::Shape::Noop);
selection_frame(p, r);
let (deg, rotates, resizes) = frame_of(sh, o);
crate::frame::paint(p, r, deg, rotates, resizes);
done(start, r);
}
painted
@@ -543,13 +548,12 @@ pub fn slicer_click(geo: &Geo, sh: &Sheet, wb: &Workbook, si: usize, p: Pos2) ->
None
}
fn selection_frame(p: &Painter, r: Rect) {
let t = Tokens::get(p.ctx());
p.rect_stroke(r, 0.0, Stroke::new(1.0, t.sheet_control_border), StrokeKind::Outside);
for h in crate::objects::Handle::ALL {
let c = h.pos(r);
p.circle_filled(c, 4.0, t.sheet_control_bg);
p.circle_stroke(c, 4.0, Stroke::new(1.0, t.sheet_control_border));
/// The selected object's turn in degrees, and whether its frame shows a rotation handle and
/// resize handles (an ink stroke shows neither).
pub fn frame_of(sh: &Sheet, o: ObjRef) -> (f32, bool, bool) {
match sh.shapes.iter().find(|s| o.kind == ObjKind::Shape && s.id == o.id) {
Some(s) => (s.rotation, s.kind != ShapeKind::Ink, s.kind != ShapeKind::Ink),
None => (0.0, false, true),
}
}
@@ -650,7 +654,22 @@ pub fn selected_handle(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option
}
let o = app.selected_object?;
let r = object_rect(geo, sh, o)?;
crate::objects::handle_at(r, p).map(|h| (o, r, h))
let (deg, _, resizes) = frame_of(sh, o);
if !resizes {
return None;
}
crate::objects::handle_at(r, crate::frame::turn(p, r.center(), -deg)).map(|h| (o, r, h))
}
/// The selected object and its rect when `p` is on its rotation handle.
pub fn selected_rotate(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(ObjRef, Rect)> {
if !geo.cells.contains(p) || app.session.active().is_some_and(|d| objects_hidden(&d.wb)) {
return None;
}
let o = app.selected_object?;
let r = object_rect(geo, sh, o)?;
let (deg, rotates, _) = frame_of(sh, o);
(rotates && matches!(crate::frame::grab_at(r, deg, true, p), Some(crate::frame::Grab::Rotate))).then_some((o, r))
}
/// The topmost object under `p` and its rect: form controls paint on top, so they are hit first,
@@ -686,7 +705,7 @@ pub fn hit(app: &SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) -> Option<(ObjRef, Re
}
for s in sh.shapes.iter().rev() {
let r = anchor_rect(geo, sh, &s.anchor);
if r.expand(3.0).contains(p) {
if r.expand(3.0).contains(crate::frame::turn(p, r.center(), -s.rotation)) {
let kind = if s.kind == ShapeKind::Equation { ObjKind::Equation } else { ObjKind::Shape };
return Some((ObjRef::new(kind, s.id), r));
}
@@ -700,6 +719,72 @@ pub(crate) fn ink_color(line: Color32, width_pt: f32) -> Color32 {
if width_pt > 8.0 { line.gamma_multiply(0.45) } else { line }
}
/// Turn everything painted on `p`'s layer since `start` by `deg` clockwise about `c`.
fn turn_painted(p: &Painter, start: egui::layers::ShapeIdx, c: Pos2, deg: f32) {
let end = p.add(egui::Shape::Noop).0;
let clip = p.clip_rect();
p.ctx().graphics_mut(|g| {
let list = g.entry(p.layer_id());
for i in start.0..end {
list.mutate_shape(egui::layers::ShapeIdx(i), |cs| {
// A turned shape reaches past its own box: clip it to the sheet only.
cs.clip_rect = clip;
turn_shape(&mut cs.shape, c, deg);
});
}
});
}
fn turn_shape(shape: &mut egui::Shape, c: Pos2, deg: f32) {
use egui::Shape;
let t = |q: &mut Pos2| *q = crate::frame::turn(*q, c, deg);
match shape {
Shape::Noop | Shape::Callback(_) | Shape::Band(_) => {}
Shape::Vec(v) => v.iter_mut().for_each(|s| turn_shape(s, c, deg)),
Shape::Circle(k) => t(&mut k.center),
Shape::Ellipse(e) => {
let pts = (0..64)
.map(|i| {
let a = i as f32 / 64.0 * std::f32::consts::TAU;
crate::frame::turn(e.center + vec2(e.radius.x * a.cos(), e.radius.y * a.sin()), c, deg)
})
.collect();
*shape = Shape::Path(PathShape::convex_polygon(pts, e.fill, e.stroke));
}
Shape::LineSegment { points, .. } => points.iter_mut().for_each(t),
Shape::Path(path) => path.points.iter_mut().for_each(t),
Shape::Rect(r) => {
let pts = rounded_rect_points(r.rect, f32::from(r.corner_radius.nw)).into_iter().map(|q| crate::frame::turn(q, c, deg)).collect();
*shape = Shape::Path(PathShape::convex_polygon(pts, r.fill, r.stroke));
}
Shape::Text(text) => {
t(&mut text.pos);
text.angle += deg.to_radians();
}
Shape::Mesh(m) => std::sync::Arc::make_mut(m).vertices.iter_mut().for_each(|v| t(&mut v.pos)),
Shape::QuadraticBezier(b) => b.points.iter_mut().for_each(t),
Shape::CubicBezier(b) => b.points.iter_mut().for_each(t),
}
}
/// The outline of `r` with corners rounded by `radius`, clockwise from the top left.
fn rounded_rect_points(r: Rect, radius: f32) -> Vec<Pos2> {
let rad = radius.min(r.width() / 2.0).min(r.height() / 2.0).max(0.0);
if rad < 0.5 {
return vec![r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()];
}
let corners = [
(pos2(r.left() + rad, r.top() + rad), 180.0_f32),
(pos2(r.right() - rad, r.top() + rad), 270.0),
(pos2(r.right() - rad, r.bottom() - rad), 0.0),
(pos2(r.left() + rad, r.bottom() - rad), 90.0),
];
corners
.into_iter()
.flat_map(|(o, from)| (0..=8).map(move |i| (from + i as f32 * 90.0 / 8.0).to_radians()).map(move |a| o + vec2(a.cos(), a.sin()) * rad))
.collect()
}
#[cfg(test)]
pub(crate) mod tests {
use std::cell::Cell;
+262
View File
@@ -0,0 +1,262 @@
//! The selection frame around a floating object (chart, picture, shape, slicer): its eight
//! handles, the rotation handle above a shape, which one a press grabs, and the rect a handle
//! drag gives. A turned frame is the rect turned about its centre, `deg` clockwise.
use egui::{CursorIcon, Painter, Pos2, Rect, Stroke, StrokeKind, pos2, vec2};
/// Handle radius and the radius a press grabs a handle within (screen points).
pub const HANDLE_R: f32 = 4.0;
const GRAB_R: f32 = 10.0;
/// Frames smaller than this (screen points) show only corner handles on that axis.
const EDGE_HANDLES_FROM: f32 = 40.0;
/// How far the rotation handle sits above the frame's top edge (screen points), and the step
/// Shift snaps the angle to (degrees).
const ROTATE_GAP: f32 = 22.0;
pub const SNAP_DEG: f32 = 15.0;
/// Screen point `p` turned `deg` degrees clockwise about `c`.
pub fn turn(p: Pos2, c: Pos2, deg: f32) -> Pos2 {
let (s, k) = deg.to_radians().sin_cos();
let (u, v) = (p.x - c.x, p.y - c.y);
pos2(c.x + u * k - v * s, c.y + u * s + v * k)
}
/// One of the eight handles: `x` / `y` are -1 (left/top), 0 (middle) or 1 (right/bottom).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Handle {
pub x: i8,
pub y: i8,
}
impl Handle {
pub const ALL: [Handle; 8] = [
Handle { x: -1, y: -1 },
Handle { x: 0, y: -1 },
Handle { x: 1, y: -1 },
Handle { x: 1, y: 0 },
Handle { x: 1, y: 1 },
Handle { x: 0, y: 1 },
Handle { x: -1, y: 1 },
Handle { x: -1, y: 0 },
];
pub fn is_corner(self) -> bool {
self.x != 0 && self.y != 0
}
/// The resize cursor, picked for the handle's direction on a frame turned `deg`.
pub fn cursor(self, deg: f32) -> CursorIcon {
let a = f32::from(self.y).atan2(f32::from(self.x)).to_degrees() + deg;
// Eight compass sectors of 45°; opposite sectors share a cursor.
match ((a / 45.0).round() as i32).rem_euclid(4) {
0 => CursorIcon::ResizeHorizontal,
1 => CursorIcon::ResizeNwSe,
2 => CursorIcon::ResizeVertical,
_ => CursorIcon::ResizeNeSw,
}
}
pub fn at(self, f: Rect) -> Pos2 {
let k = |v: i8| (f32::from(v) + 1.0) / 2.0;
pos2(f.min.x + f.width() * k(self.x), f.min.y + f.height() * k(self.y))
}
pub fn at_turned(self, f: Rect, deg: f32) -> Pos2 {
turn(self.at(f), f.center(), deg)
}
}
/// What a press on a selected object grabbed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Grab {
Move,
Resize(Handle),
Rotate,
}
impl Grab {
pub fn cursor(self, deg: f32) -> CursorIcon {
match self {
Grab::Move => CursorIcon::Move,
Grab::Resize(h) => h.cursor(deg),
Grab::Rotate => CursorIcon::Crosshair,
}
}
}
/// The handles a frame shows: corners always, edge middles when there's room.
pub fn handles(f: Rect) -> impl Iterator<Item = Handle> {
let (wide, tall) = (f.width() >= EDGE_HANDLES_FROM, f.height() >= EDGE_HANDLES_FROM);
Handle::ALL.into_iter().filter(move |h| (h.x != 0 || wide) && (h.y != 0 || tall))
}
/// Where the rotation handle of frame `f` turned `deg` is: above the middle of its top edge.
pub fn rotate_handle(f: Rect, deg: f32) -> Pos2 {
turn(pos2(f.center().x, f.min.y - ROTATE_GAP), f.center(), deg)
}
/// The handle of frame `f` turned `deg` under screen point `p`; `rotate` offers the rotation
/// handle too.
pub fn grab_at(f: Rect, deg: f32, rotate: bool, p: Pos2) -> Option<Grab> {
if rotate && rotate_handle(f, deg).distance(p) <= GRAB_R {
return Some(Grab::Rotate);
}
let d = |h: &Handle| h.at_turned(f, deg).distance(p);
handles(f).filter(|h| d(h) <= GRAB_R).min_by(|a, b| d(a).total_cmp(&d(b))).map(Grab::Resize)
}
/// The angle (degrees clockwise, `[0, 360)`) that points frame `f`'s rotation handle at `p`,
/// by whole degrees or, with `snap`, by [`SNAP_DEG`].
pub fn angle_to(f: Rect, p: Pos2, snap: bool) -> f32 {
let d = p - f.center();
// The handle is straight up (-90°) when unturned.
let deg = d.y.atan2(d.x).to_degrees() + 90.0;
let step = if snap { SNAP_DEG } else { 1.0 };
((deg / step).round() * step).rem_euclid(360.0)
}
/// Draw frame `f` turned `deg`: outline, handles and, with `rotate`, the rotation handle.
pub fn paint(p: &Painter, f: Rect, deg: f32, rotate: bool, resize: bool) {
let line = Stroke::new(1.0, egui::Color32::from_gray(120));
if deg == 0.0 {
p.rect_stroke(f, 0.0, line, StrokeKind::Outside);
} else {
let c = f.center();
let pts = [f.left_top(), f.right_top(), f.right_bottom(), f.left_bottom(), f.left_top()].map(|q| turn(q, c, deg));
p.add(egui::Shape::line(pts.to_vec(), line));
}
let knob = |c: Pos2| {
p.circle_filled(c, HANDLE_R, egui::Color32::WHITE);
p.circle_stroke(c, HANDLE_R, Stroke::new(1.0, egui::Color32::from_gray(100)));
};
if rotate {
let r = rotate_handle(f, deg);
p.line_segment([turn(f.center_top(), f.center(), deg), r], line);
knob(r);
// A circling arrow: three quarters of a ring.
let ring: Vec<Pos2> = (0..=12).map(|i| r + vec2((i as f32 * 0.4).cos(), (i as f32 * 0.4).sin()) * (HANDLE_R * 0.55)).collect();
p.add(egui::Shape::line(ring, Stroke::new(1.0, egui::Color32::from_gray(80))));
}
if resize {
for h in handles(f) {
knob(h.at_turned(f, deg));
}
}
}
/// [`resized`] for a frame turned `deg`: the drag is taken along the frame's own axes, and the
/// handle opposite the grabbed one stays where it is.
pub fn resized_turned(r: Rect, deg: f32, h: Handle, d: egui::Vec2, min: f32, keep_aspect: bool) -> Rect {
resized_turned_by_min(r, deg, h, d, egui::Vec2::splat(min), keep_aspect)
}
/// Axis-aware version for objects with a zero-height or zero-width minimum.
pub(crate) fn resized_turned_by_min(r: Rect, deg: f32, h: Handle, d: egui::Vec2, min: egui::Vec2, keep_aspect: bool) -> Rect {
if deg == 0.0 {
return resized_by_min(r, h, d, min, keep_aspect);
}
let local = turn(pos2(d.x, d.y), Pos2::ZERO, -deg).to_vec2();
let n = resized_by_min(r, h, local, min, keep_aspect);
let opp = Handle { x: -h.x, y: -h.y };
n.translate(opp.at_turned(r, deg) - opp.at_turned(n, deg))
}
/// `r` with handle `h` dragged by `d`; the opposite edges stay put. Never smaller than `min`;
/// `keep_aspect` keeps the proportions when a corner is dragged.
pub fn resized(r: Rect, h: Handle, d: egui::Vec2, min: f32, keep_aspect: bool) -> Rect {
resized_by_min(r, h, d, egui::Vec2::splat(min), keep_aspect)
}
fn resized_by_min(r: Rect, h: Handle, d: egui::Vec2, min: egui::Vec2, keep_aspect: bool) -> Rect {
let (mut x0, mut y0, mut x1, mut y1) = (r.min.x, r.min.y, r.max.x, r.max.y);
match h.x {
-1 => x0 = (x0 + d.x).min(x1 - min.x),
1 => x1 = (x1 + d.x).max(x0 + min.x),
_ => {}
}
match h.y {
-1 => y0 = (y0 + d.y).min(y1 - min.y),
1 => y1 = (y1 + d.y).max(y0 + min.y),
_ => {}
}
if keep_aspect && h.is_corner() && r.width() > 0.0 && r.height() > 0.0 {
// Follow whichever side changed more.
let (kx, ky) = ((x1 - x0) / r.width(), (y1 - y0) / r.height());
let k = if (kx - 1.0).abs() >= (ky - 1.0).abs() { kx } else { ky };
let k = k.max(min.x / r.width()).max(min.y / r.height());
let (w, hh) = (r.width() * k, r.height() * k);
if h.x < 0 {
x0 = x1 - w;
} else {
x1 = x0 + w;
}
if h.y < 0 {
y0 = y1 - hh;
} else {
y1 = y0 + hh;
}
}
Rect::from_min_max(pos2(x0, y0), pos2(x1, y1))
}
#[cfg(test)]
mod tests {
use super::*;
use egui::vec2;
fn r() -> Rect {
Rect::from_min_size(pos2(100.0, 100.0), vec2(200.0, 100.0))
}
#[test]
fn the_left_handle_moves_only_the_left_edge() {
let n = resized(r(), Handle { x: -1, y: 0 }, vec2(-30.0, 50.0), 20.0, false);
assert_eq!(n, Rect::from_min_max(pos2(70.0, 100.0), pos2(300.0, 200.0)));
}
#[test]
fn the_top_left_corner_never_crosses_the_opposite_edges() {
let n = resized(r(), Handle { x: -1, y: -1 }, vec2(500.0, 500.0), 20.0, false);
assert_eq!(n, Rect::from_min_max(pos2(280.0, 180.0), pos2(300.0, 200.0)));
}
#[test]
fn shift_keeps_the_proportions() {
let n = resized(r(), Handle { x: 1, y: 1 }, vec2(200.0, 0.0), 20.0, true);
assert_eq!(n.size(), vec2(400.0, 200.0));
assert_eq!(n.min, r().min);
}
#[test]
fn small_frames_drop_the_edge_handles() {
let small = Rect::from_min_size(pos2(0.0, 0.0), vec2(30.0, 100.0));
assert!(handles(small).all(|h| h.x != 0));
assert_eq!(handles(r()).count(), 8);
}
#[test]
fn cursors_follow_the_turned_handle() {
let right = Handle { x: 1, y: 0 };
assert_eq!(right.cursor(0.0), CursorIcon::ResizeHorizontal);
assert_eq!(right.cursor(90.0), CursorIcon::ResizeVertical);
assert_eq!(right.cursor(45.0), CursorIcon::ResizeNwSe);
assert_eq!(Handle { x: 1, y: -1 }.cursor(0.0), CursorIcon::ResizeNeSw);
}
#[test]
fn the_rotation_handle_points_at_the_pointer() {
let c = r().center();
assert_eq!(angle_to(r(), c + vec2(0.0, -50.0), false), 0.0);
assert_eq!(angle_to(r(), c + vec2(50.0, 0.0), false), 90.0);
assert_eq!(angle_to(r(), c + vec2(-50.0, 0.0), false), 270.0);
assert_eq!(angle_to(r(), c + vec2(50.0, -40.0), true), 45.0);
assert_eq!(grab_at(r(), 0.0, true, rotate_handle(r(), 0.0)), Some(Grab::Rotate));
assert_eq!(grab_at(r(), 0.0, false, rotate_handle(r(), 0.0)), None);
}
#[test]
fn a_turned_resize_keeps_the_opposite_handle_in_place() {
let h = Handle { x: 1, y: 0 };
let n = resized_turned(r(), 90.0, h, vec2(0.0, 40.0), 20.0, false);
// Turned 90°, the right handle points down: a downward drag widens the frame.
assert!((n.width() - 240.0).abs() < 0.01, "{n:?}");
let opp = Handle { x: -1, y: 0 };
assert!((opp.at_turned(n, 90.0) - opp.at_turned(r(), 90.0)).length() < 0.01);
}
}
+6
View File
@@ -151,6 +151,12 @@ pub enum Drag {
/// step of an earlier drag.
stepped: bool,
},
/// Turning a shape about the centre of `rect` (its screen rect as the drag began).
Rotate {
obj: gridcraft_engine::model::ObjRef,
rect: Rect,
stepped: bool,
},
/// Dragging a corner of the selected chart's values outline (#4389): `to` is the previewed
/// block, which the release gives the chart.
ChartData {
+9 -2
View File
@@ -57,6 +57,7 @@ fn drag_cursor(drag: &Drag, rtl: bool) -> Option<CursorIcon> {
Drag::ResizeCol { .. } => Some(CursorIcon::ResizeColumn),
Drag::ResizeRow { .. } => Some(CursorIcon::ResizeRow),
Drag::Freeze { cols, .. } => Some(if *cols { CursorIcon::ResizeHorizontal } else { CursorIcon::ResizeVertical }),
Drag::Rotate { .. } => Some(CursorIcon::Crosshair),
Drag::Object { handle: Some(h), .. } | Drag::ChartData { corner: h, .. } => Some(h.cursor(rtl)),
}
}
@@ -81,7 +82,7 @@ fn hover_cursor(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, poin
let on_cur_border = on_border(cur_rect, p) && border_panes.iter().any(|r| r.contains(p));
// The selected object's handles resize it; any object's body moves it.
let idle = app.grid.drag == Drag::None && app.editor.is_none();
let object_handle = if idle { crate::chartview::selected_handle(app, geo, sh, p).map(|(.., h)| h) } else { None };
let object_handle = if idle { crate::chartview::selected_handle(app, geo, sh, p) } else { None };
let hit = if idle { crate::chartview::hit(app, geo, sh, p) } else { None };
// A form control works on click unless it is selected (or Ctrl or Cmd is held).
let mods = ctx.input(|i| i.modifiers);
@@ -89,7 +90,13 @@ fn hover_cursor(app: &SheetApp, ctx: &egui::Context, resp: &egui::Response, poin
let on_object = hit.is_some();
// A corner of the selected chart's values outline resizes the chart's data, where no object covers it.
let data_handle = if idle && !on_object { crate::chartview::chart_data_handle(app, geo, sh, p).map(|(.., h)| h) } else { None };
if let Some(h) = object_handle.or(data_handle) {
let on_rotate = idle && crate::chartview::selected_rotate(app, geo, sh, p).is_some();
if on_rotate {
ctx.set_cursor_icon(CursorIcon::Crosshair);
} else if let Some((o, _, h)) = object_handle {
let deg = crate::chartview::frame_of(sh, o).0;
ctx.set_cursor_icon(if deg == 0.0 { h.cursor(geo.rtl) } else { crate::frame::Handle { x: h.sides().0, y: h.sides().1 }.cursor(deg) });
} else if let Some(h) = data_handle {
ctx.set_cursor_icon(h.cursor(geo.rtl));
} else if works {
ctx.set_cursor_icon(CursorIcon::PointingHand);
+63
View File
@@ -136,6 +136,13 @@ pub(super) fn interact(app: &mut SheetApp, ui: &mut egui::Ui, resp: &egui::Respo
if primary_drag || primary_clicked {
// A drag is recognised only after the pointer has moved, so grab the object where the press began.
let at = if primary_drag { pointer.press_origin().map(|p| geo.mirror_pos(p)).or(pos) } else { pos };
if primary_drag
&& let Some(p) = at
&& let Some((obj, rect)) = crate::chartview::selected_rotate(app, geo, sh, p)
{
app.grid.drag = Drag::Rotate { obj, rect, stepped: false };
return;
}
// The selected object's handles reach a little outside it, so they win over hit-testing.
// Only they resize: a press anywhere on another object selects and moves it, as the
// hover cursor shows.
@@ -764,6 +771,7 @@ fn handle_dragging(app: &mut SheetApp, input: &InteractionInput<'_>) {
scroll_by(app, auto);
}
Drag::Object { .. } => drag_object(app, geo, sh, p),
Drag::Rotate { obj, rect, .. } => rotate_object(app, obj, rect, p, input.modifiers.shift),
Drag::ChartData { .. } => {
drag_chart_data(app, geo, sh, p);
scroll_by(app, auto);
@@ -1202,6 +1210,52 @@ pub(super) fn hidden_row_edge(geo: &Geo, sh: &Sheet, y: f32) -> Option<u32> {
row_edge(geo, sh, y).map(|(r, _)| r).filter(|&r| sh.row_height(r) <= 0.0)
}
/// Arrow-key nudge of a selected object, sheet points (Ctrl/Alt: fine).
const NUDGE: f32 = 6.0;
/// Arrow keys aimed at the selected object rather than the cells: they nudge it.
pub(super) fn object_key(app: &mut SheetApp, sh: &Sheet, key: egui::Key, m: egui::Modifiers) -> bool {
use egui::Key;
let Some(o) = app.selected_object else { return false };
let step = if m.ctrl || m.alt { 1.0 } else { NUDGE };
// Arrows follow the screen: a right-to-left sheet is mirrored.
let sx = if sh.right_to_left { -step } else { step };
let d = match key {
Key::ArrowLeft => vec2(-sx, 0.0),
Key::ArrowRight => vec2(sx, 0.0),
Key::ArrowUp => vec2(0.0, -step),
Key::ArrowDown => vec2(0.0, step),
_ => return false,
};
// On Windows and Linux egui sets `command` with `ctrl`: only the Mac Command key opts out.
if m.shift || m.mac_cmd {
return false;
}
let Some(a) = sh.object_anchor(o) else { return false };
let x0 = (sh.col_left(a.cell.col) as f32 + a.dx + d.x).max(0.0);
let y0 = (sh.row_top(a.cell.row) as f32 + a.dy + d.y).max(0.0);
let nc = CellRef::new(sh.row_at(f64::from(y0)), sh.col_at(f64::from(x0)));
let params =
json!({"kind": o.kind.name(), "id": o.id, "at": nc.a1(), "dx": x0 - sh.col_left(nc.col) as f32, "dy": y0 - sh.row_top(nc.row) as f32});
app.run_or_alert("object.move", params);
true
}
/// Turns the dragged shape so its rotation handle points at `p`; the drag is one undo step.
fn rotate_object(app: &mut SheetApp, obj: ObjRef, rect: Rect, p: Pos2, snap: bool) {
let deg = crate::frame::angle_to(rect, p, snap);
let revision = app.session.active().map(|d| d.revision);
let _ = app.session.run("object.move", json!({"kind": obj.kind.name(), "id": obj.id, "rotation": deg}));
let Drag::Rotate { stepped, .. } = app.grid.drag else { return };
if stepped {
coalesce_last_undo(app);
} else if app.session.active().map(|d| d.revision) != revision
&& let Drag::Rotate { stepped, .. } = &mut app.grid.drag
{
*stepped = true;
}
}
/// Moves the dragged object, or resizes it from the grabbed handle, to follow the pointer at `p`
/// (logical coordinates). The whole drag coalesces into one undo step of its own.
fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
@@ -1210,7 +1264,16 @@ fn drag_object(app: &mut SheetApp, geo: &Geo, sh: &Sheet, p: Pos2) {
let (cell, dx, dy, w, h) = orig;
let x0 = sh.col_left(cell.col) as f32 + dx;
let y0 = sh.row_top(cell.row) as f32 + dy;
let frame_deg = crate::chartview::frame_of(sh, obj).0;
let [x0, y0, x1, y1] = match handle {
Some(hd) if frame_deg != 0.0 => {
let fh = crate::frame::Handle { x: hd.sides().0, y: hd.sides().1 };
let r0 = Rect::from_min_max(pos2(x0, y0), pos2(x0 + w, y0 + h));
let min = crate::objects::min_size(sh, obj);
let r = crate::frame::resized_turned_by_min(r0, frame_deg, fh, d, min, false);
let (nx, ny) = (r.min.x.max(0.0), r.min.y.max(0.0));
[nx, ny, r.max.x.max(nx + min.x), r.max.y.max(ny + min.y)]
}
Some(hd) => crate::objects::resized([x0, y0, x0 + w, y0 + h], hd, d, crate::objects::min_size(sh, obj)),
None => {
let (x0, y0) = ((x0 + d.x).max(0.0), (y0 + d.y).max(0.0));
+4 -2
View File
@@ -1,4 +1,5 @@
use super::geo::Geo;
use super::interact::object_key;
use super::menus::is_checkbox;
use super::{CellRef, Drag, Sheet, SheetApp, json};
@@ -81,8 +82,9 @@ pub(super) fn keyboard(app: &mut SheetApp, ctx: &egui::Context, resp: &egui::Res
}
egui::Event::Key { key, physical_key, pressed: true, modifiers: m, .. } => {
use egui::Key;
if crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) {
shortcut_ran = true;
let nudged = object_key(app, sh, key, m);
if nudged || crate::keymap::dispatch(app, ctx, key, physical_key, m, geo, sh) {
shortcut_ran |= !nudged;
continue;
}
let cmd = m.command;
+1
View File
@@ -36,6 +36,7 @@ pub mod fonts;
pub mod form_controls;
pub mod formula_bar;
mod formula_locale;
pub mod frame;
pub mod function_library;
pub mod grid;
pub mod i18n;
+305
View File
@@ -0,0 +1,305 @@
//! Selecting, moving and resizing an inserted shape through real pointer input.
use egui::{Event, Modifiers, PointerButton, vec2};
use gridcraft_engine::Session;
use gridcraft_engine::core::CellRef;
use gridcraft_engine::model::Anchor;
use gridcraft_ui_egui::{SheetApp, grid::Geo};
use serde_json::json;
type Harness = egui_kittest::Harness<'static, SheetApp>;
fn fixture() -> (Harness, u32) {
fixture_of("rectangle")
}
fn fixture_of(kind: &str) -> (Harness, u32) {
let mut session = Session::new();
session.new_workbook();
let id = if kind == "ink" {
session.execute("draw.stroke", json!({"points": [[300, 100], [420, 200]]})).unwrap();
let sh = session.doc().unwrap().wb.active().unwrap();
sh.shapes.iter().find(|s| s.kind == gridcraft_engine::model::ShapeKind::Ink).unwrap().id
} else {
let height = if matches!(kind, "line" | "arrow") { 0 } else { 100 };
let shape = session.execute("insert.shape", json!({"kind": kind, "at": "D3", "width": 160, "height": height})).unwrap();
shape["shape"].as_u64().unwrap() as u32
};
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state(
|ui, app: &mut SheetApp| {
let ctx = ui.ctx().clone();
app.logic(&ctx);
app.ui(ui);
},
SheetApp::new(session, Default::default()),
);
h.run_steps(4);
h.state_mut().selected_object = None;
h.run_steps(2);
(h, id)
}
fn anchor(h: &Harness, id: u32) -> Anchor {
h.state().session.doc().unwrap().wb.active().unwrap().shapes.iter().find(|s| s.id == id).unwrap().anchor
}
fn rect(h: &Harness, id: u32) -> egui::Rect {
let app = h.state();
let sh = app.session.doc().unwrap().wb.active().unwrap();
let geo = Geo::new(sh, app.grid.rect.unwrap(), app.view().scroll);
let a = anchor(h, id);
let min = geo.cell_rect(sh, a.cell).min + vec2(a.dx, a.dy) * geo.z;
egui::Rect::from_min_size(min, vec2(a.width, a.height) * geo.z)
}
fn button(h: &mut Harness, pos: egui::Pos2, pressed: bool) {
h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
h.run_steps(2);
}
fn drag(h: &mut Harness, from: egui::Pos2, to: egui::Pos2) {
h.input_mut().events.push(Event::PointerMoved(from));
h.run_steps(2);
button(h, from, true);
h.input_mut().events.push(Event::PointerMoved(to));
h.run_steps(3);
button(h, to, false);
}
#[test]
fn clicking_a_shape_selects_it() {
let (mut h, id) = fixture();
let c = rect(&h, id).center();
h.input_mut().events.push(Event::PointerMoved(c));
h.run_steps(2);
button(&mut h, c, true);
button(&mut h, c, false);
assert_eq!(h.state().selected_object.map(|o| o.id), Some(id));
assert_eq!(h.state().session.active().unwrap().selection.current().start, CellRef::parse("A1").unwrap());
}
fn handle_at(h: &Harness, at: egui::Pos2) -> bool {
h.output().shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Circle(k) if (k.center - at).length() < 1.0 && k.radius == 4.0))
}
#[test]
fn a_selected_shape_shows_its_handles() {
let (mut h, id) = fixture();
let r = rect(&h, id);
assert!(!handle_at(&h, r.center_top()), "no handles before selecting");
h.input_mut().events.push(Event::PointerMoved(r.center()));
h.run_steps(2);
button(&mut h, r.center(), true);
button(&mut h, r.center(), false);
for at in [r.left_top(), r.center_top(), r.right_bottom()] {
assert!(handle_at(&h, at), "handle at {at:?}");
}
}
#[test]
fn dragging_a_shape_moves_it() {
let (mut h, id) = fixture();
let before = rect(&h, id);
drag(&mut h, before.center(), before.center() + vec2(120.0, 80.0));
let after = rect(&h, id);
assert!((after.min - before.min - vec2(120.0, 80.0)).length() < 4.0, "moved from {before:?} to {after:?}");
assert_eq!(after.size(), before.size());
}
fn select(h: &mut Harness, id: u32) {
let c = rect(h, id).center();
select_at(h, c);
}
fn select_at(h: &mut Harness, c: egui::Pos2) {
h.input_mut().events.push(Event::PointerMoved(c));
h.run_steps(2);
button(h, c, true);
button(h, c, false);
}
#[test]
fn every_handle_shows_its_resize_cursor() {
let (mut h, id) = fixture();
select(&mut h, id);
let r = rect(&h, id);
for (at, cursor) in [
(r.left_top(), egui::CursorIcon::ResizeNwSe),
(r.right_top(), egui::CursorIcon::ResizeNeSw),
(r.left_center(), egui::CursorIcon::ResizeHorizontal),
(r.center_bottom(), egui::CursorIcon::ResizeVertical),
] {
h.input_mut().events.push(Event::PointerMoved(at));
h.run_steps(2);
assert_eq!(h.output().platform_output.cursor_icon, cursor, "at {at:?}");
}
}
#[test]
fn dragging_the_left_handle_moves_only_the_left_edge() {
let (mut h, id) = fixture();
select(&mut h, id);
let before = rect(&h, id);
drag(&mut h, before.left_center(), before.left_center() + vec2(-50.0, 40.0));
let after = rect(&h, id);
assert!((after.left() - (before.left() - 50.0)).abs() < 2.0, "{before:?} -> {after:?}");
assert!((after.right() - before.right()).abs() < 2.0, "{before:?} -> {after:?}");
assert!((after.top() - before.top()).abs() < 2.0 && (after.bottom() - before.bottom()).abs() < 2.0, "{before:?} -> {after:?}");
}
#[test]
fn dragging_the_top_left_handle_keeps_the_bottom_right_corner() {
let (mut h, id) = fixture();
select(&mut h, id);
let before = rect(&h, id);
drag(&mut h, before.left_top(), before.left_top() + vec2(30.0, 20.0));
let after = rect(&h, id);
assert!((after.right_bottom() - before.right_bottom()).length() < 2.0, "{before:?} -> {after:?}");
assert!((after.left_top() - before.left_top() - vec2(30.0, 20.0)).length() < 2.0, "{before:?} -> {after:?}");
}
#[test]
fn dragging_the_corner_resizes_a_shape() {
let (mut h, id) = fixture();
select(&mut h, id);
let before = rect(&h, id);
drag(&mut h, before.right_bottom(), before.right_bottom() + vec2(60.0, 30.0));
let after = rect(&h, id);
assert!(after.width() > before.width() + 40.0 && after.height() > before.height() + 20.0, "{before:?} -> {after:?}");
}
fn rotation(h: &Harness, id: u32) -> f32 {
h.state().session.doc().unwrap().wb.active().unwrap().shapes.iter().find(|s| s.id == id).unwrap().rotation
}
#[test]
fn dragging_the_rotation_handle_turns_the_shape() {
let (mut h, id) = fixture();
select(&mut h, id);
let r = rect(&h, id);
let knob = gridcraft_ui_egui::frame::rotate_handle(r, 0.0);
assert!(handle_at(&h, knob), "the rotation handle shows");
h.input_mut().events.push(Event::PointerMoved(knob));
h.run_steps(2);
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Crosshair);
drag(&mut h, knob, r.center() + vec2(200.0, 0.0));
assert_eq!(rotation(&h, id), 90.0);
assert_eq!(rect(&h, id), r, "turning keeps the box");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(rotation(&h, id), 0.0, "one drag is one undo step");
}
#[test]
fn a_turned_shape_is_hit_inside_its_turned_outline() {
let (mut h, id) = fixture();
h.state_mut().run("object.move", json!({"kind": "shape", "id": id, "rotation": 90})).unwrap();
h.run_steps(2);
let r = rect(&h, id);
// Turned 90°, the shape reaches half its width above and below its centre.
let below = r.center() + vec2(0.0, r.width() / 2.0 - 5.0);
assert!(!r.contains(below));
h.input_mut().events.push(Event::PointerMoved(below));
h.run_steps(2);
button(&mut h, below, true);
button(&mut h, below, false);
assert_eq!(h.state().selected_object.map(|o| o.id), Some(id));
}
fn key(h: &mut Harness, key: egui::Key, modifiers: Modifiers) {
h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });
h.run_steps(2);
}
#[test]
fn arrow_keys_nudge_the_selected_shape_not_the_cell_cursor() {
let (mut h, id) = fixture();
select(&mut h, id);
let before = anchor(&h, id);
key(&mut h, egui::Key::ArrowRight, Modifiers::NONE);
key(&mut h, egui::Key::ArrowDown, Modifiers { ctrl: true, command: true, ..Default::default() });
let after = anchor(&h, id);
let x = |a: &Anchor| h.state().session.doc().unwrap().wb.active().unwrap().col_left(a.cell.col) as f32 + a.dx;
let y = |a: &Anchor| h.state().session.doc().unwrap().wb.active().unwrap().row_top(a.cell.row) as f32 + a.dy;
assert!((x(&after) - x(&before) - 6.0).abs() < 0.01 && (y(&after) - y(&before) - 1.0).abs() < 0.01, "{before:?} -> {after:?}");
assert_eq!(h.state().session.active().unwrap().selection.current().start, CellRef::parse("A1").unwrap());
}
#[test]
fn escape_deselects_the_shape() {
let (mut h, id) = fixture();
select(&mut h, id);
key(&mut h, egui::Key::Escape, Modifiers::NONE);
assert_eq!(h.state().selected_object, None);
}
#[test]
fn the_body_of_a_shape_shows_the_move_cursor() {
let (mut h, id) = fixture();
let c = rect(&h, id).center();
h.input_mut().events.push(Event::PointerMoved(c));
h.run_steps(2);
assert_eq!(h.output().platform_output.cursor_icon, egui::CursorIcon::Move);
}
#[test]
fn resizing_a_flat_line_keeps_it_flat() {
let (mut h, id) = fixture_of("line");
select(&mut h, id);
let before = rect(&h, id);
assert_eq!(before.height(), 0.0, "a new line has no height");
drag(&mut h, before.right_bottom(), before.right_bottom() + vec2(50.0, 40.0));
let after = rect(&h, id);
assert!(after.width() > before.width() + 40.0, "{before:?} -> {after:?}");
assert_eq!(after.height(), 0.0, "{before:?} -> {after:?}");
}
#[test]
fn resizing_rotated_flat_lines_and_arrows_keeps_them_flat_and_undoes() {
for kind in ["line", "arrow"] {
let (mut h, id) = fixture_of(kind);
h.state_mut().run("object.move", json!({"kind": "shape", "id": id, "rotation": 90})).unwrap();
h.run_steps(2);
h.state_mut().selected_object = Some(gridcraft_engine::model::ObjRef::new(gridcraft_engine::model::ObjKind::Shape, id));
h.run_steps(2);
let before_anchor = anchor(&h, id);
let before = rect(&h, id);
assert_eq!(before.height(), 0.0, "{kind} starts flat: {before:?}");
let handle = gridcraft_ui_egui::frame::Handle { x: 1, y: 1 }.at_turned(before, 90.0);
drag(&mut h, handle, handle + vec2(0.0, 50.0));
let after = rect(&h, id);
assert!(after.width() > before.width() + 40.0, "{kind}: {before:?} -> {after:?}");
assert_eq!(after.height(), 0.0, "{kind}: {before:?} -> {after:?}");
assert_eq!(rotation(&h, id), 90.0);
h.state_mut().run("edit.undo", json!({})).unwrap();
h.run_steps(2);
assert_eq!(anchor(&h, id), before_anchor, "{kind} undo restores its anchor");
assert_eq!(rotation(&h, id), 90.0, "{kind} undo preserves rotation");
}
}
#[test]
fn arrow_keys_follow_the_screen_on_a_right_to_left_sheet() {
let (mut h, id) = fixture();
h.state_mut().session.execute("view.rightToLeft", json!({"on": true})).unwrap();
h.run_steps(2);
h.state_mut().selected_object = Some(gridcraft_engine::model::ObjRef::new(gridcraft_engine::model::ObjKind::Shape, id));
h.run_steps(2);
let x = |h: &Harness| {
let a = anchor(h, id);
h.state().session.doc().unwrap().wb.active().unwrap().col_left(a.cell.col) as f32 + a.dx
};
let before = x(&h);
key(&mut h, egui::Key::ArrowRight, Modifiers::NONE);
let moved = x(&h) - before;
assert!((moved + 6.0).abs() < 0.01, "moved {moved}");
}
#[test]
fn an_ink_stroke_shows_no_resize_handles() {
let (mut h, id) = fixture_of("ink");
select(&mut h, id);
let r = rect(&h, id);
assert!(!handle_at(&h, r.right_bottom()), "ink does not scale with its frame");
}
+17 -3
View File
@@ -266,6 +266,7 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
line: ink,
text,
format: Default::default(),
rotation: 0.0,
math: Default::default(),
});
}
@@ -274,7 +275,13 @@ fn read_shape(obj: &El, anchor: Anchor) -> Option<Shape> {
let text = obj.child("txBody").map(body_text).unwrap_or_default();
let mut format = read_text_format(obj.child("txBody"));
format.no_line = ln.is_some_and(|l| l.child("noFill").is_some());
Some(Shape { id: 0, kind, anchor, fill, line, text, format, math: Default::default() })
let rotation = sp
.child("xfrm")
.and_then(|x| x.attr("rot"))
.and_then(|r| r.parse::<f64>().ok())
.filter(|r| r.is_finite())
.map_or(0.0, |r| ((r / 60000.0).rem_euclid(360.0)) as f32);
Some(Shape { id: 0, kind, anchor, fill, line, text, format, rotation, math: Default::default() })
}
/// A shape's text formatting: vertical anchor (`a:bodyPr anchor`), the first paragraph's
@@ -452,8 +459,15 @@ fn anchor_open(sheet: &Sheet, a: &Anchor) -> (String, &'static str) {
}
fn xfrm(a: &Anchor, tag: &str) -> String {
xfrm_rot(a, tag, 0.0)
}
/// `deg` is written as `rot`, in 60000ths of a degree.
fn xfrm_rot(a: &Anchor, tag: &str, deg: f32) -> String {
let e = |v: f32| ((v.max(0.0) as f64) * EMU_PER_PX).round() as i64;
format!("<{tag}><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{}\" cy=\"{}\"/></{tag}>", e(a.width), e(a.height))
let rot = (f64::from(deg.rem_euclid(360.0)) * 60000.0).round() as i64;
let rot = if rot > 0 { format!(" rot=\"{rot}\"") } else { String::new() };
format!("<{tag}{rot}><a:off x=\"0\" y=\"0\"/><a:ext cx=\"{}\" cy=\"{}\"/></{tag}>", e(a.width), e(a.height))
}
pub fn srgb(c: &Color, theme: &Theme) -> Option<String> {
@@ -545,7 +559,7 @@ pub fn write_drawing(sheet: &Sheet, theme: &Theme, objs: &[Obj<'_>]) -> String {
"<xdr:sp macro=\"\" textlink=\"\"><xdr:nvSpPr><xdr:cNvPr id=\"{id}\" name=\"Shape {}\"/><xdr:cNvSpPr{}/></xdr:nvSpPr><xdr:spPr>{}<a:prstGeom prst=\"{prst}\"><a:avLst/></a:prstGeom>",
id - 1,
if tx { " txBox=\"1\"" } else { "" },
xfrm(&sh.anchor, "a:xfrm")
xfrm_rot(&sh.anchor, "a:xfrm", sh.rotation)
);
if let Some(c) = srgb(&sh.fill, theme) {
let _ = write!(s, "<a:solidFill>{c}</a:solidFill>");
+1
View File
@@ -187,6 +187,7 @@ pub(super) fn read(obj: &El, anchor: Anchor) -> Option<Shape> {
line,
text,
format: Default::default(),
rotation: 0.0,
math: Default::default(),
})
}
+2
View File
@@ -20,6 +20,7 @@ fn equation(id: u32, cell: &str, latex: &str, ink: Color) -> Shape {
text: latex.into(),
format: Default::default(),
math: Default::default(),
rotation: 0.0,
}
}
@@ -161,6 +162,7 @@ fn a_text_box_stays_a_text_box_and_hostile_sources_survive() {
text: "plain".into(),
format: Default::default(),
math: Default::default(),
rotation: 0.0,
});
wb.sheets[0] = Arc::new(sh);
let (back, _) = read_xlsx(&write_xlsx(&wb).unwrap()).unwrap();
+1
View File
@@ -62,6 +62,7 @@ fn exported_ink_has_a_visible_unfilled_path_and_correct_stroke() {
line: Color::Rgb(0xA12BCD),
text: "-10.0,5.0;50.0,40.0;90.0,10.0".into(),
format: Default::default(),
rotation: 0.0,
math: Default::default(),
});
}
+3
View File
@@ -369,6 +369,7 @@ fn sample() -> Workbook {
line: Color::Rgb(0x000000),
text: "Hi\nthere".into(),
format: Default::default(),
rotation: 30.0,
});
s.shapes.push(Shape {
math: Default::default(),
@@ -379,6 +380,7 @@ fn sample() -> Workbook {
line: Color::Rgb(0xFF0000),
text: String::new(),
format: Default::default(),
rotation: 0.0,
});
s.shapes.push(Shape {
math: Default::default(),
@@ -401,6 +403,7 @@ fn sample() -> Workbook {
anchor: Some(ShapeTextAnchor::Bottom),
rtl: true,
},
rotation: 0.0,
});
let base_chart = Chart {
id: 20,
+9
View File
@@ -45,6 +45,7 @@ fn text_box(text: &str, format: ShapeFormat) -> Workbook {
line: Color::Auto,
text: text.into(),
format,
rotation: 0.0,
math: Default::default(),
});
Workbook { sheets: vec![Arc::new(sheet)], ..Default::default() }
@@ -86,6 +87,14 @@ fn shape_text_without_rtl_writes_unchanged_ppr() {
assert!(!xml.contains("<a:pPr"), "no paragraph properties without alignment or direction: {xml}");
}
#[test]
fn a_rotation_that_is_not_a_finite_number_reads_as_zero() {
for rot in ["NaN", "inf", "-inf"] {
let wb = read_drawing(&ARABIC_TEXT_BOX.replace("<a:xfrm>", &format!("<a:xfrm rot=\"{rot}\">")));
assert_eq!(wb.sheet(0).unwrap().shapes[0].rotation, 0.0, "rot={rot}");
}
}
#[test]
fn word_art_keeps_right_to_left_paragraphs() {
let mut wb = text_box("مرحبا\nبالعالم", ShapeFormat { rtl: true, align: Some(ShapeTextAlign::Right), ..Default::default() });