pixelcoords-core 0.5.3

Platform-free core of pixelcoords: screen geometry, HiDPI and multi-monitor coordinate spaces, the session.json schema, template relocation, point verdicts, click-point resolution, region diffing, and click-code emitters. Cross-platform (macOS, Windows, Linux), no unsafe
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
//! The set of committed selections plus per-op undo and redo stacks.

use crate::geometry::{Line, Point, ResizeHandle, Shape};

/// A two-point measurement laid on the frozen image.
///
/// Deliberately not a [`Selection`]: it has no interior, so it produces
/// no crop, contributes nothing to a cutout, and has no click point for
/// `assert` or `emit` to answer about. Forcing it through the selection
/// list would make every one of those grow a special case for a thing
/// they cannot say anything useful about.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Measure {
    pub line: Line,
    pub label: String,
    /// Index into the session's monitor list. A measure lives within one
    /// monitor's frame, like every shape.
    pub monitor: usize,
}

impl Measure {
    #[must_use]
    pub const fn new(line: Line, monitor: usize) -> Self {
        Self {
            line,
            label: String::new(),
            monitor,
        }
    }
}

/// Which end of a measure a drag has hold of.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MeasureGrab {
    /// An endpoint: `true` is `a`, `false` is `b`.
    Endpoint(bool),
    /// The line itself: drag moves the whole ruler.
    Move,
}

/// What a mouse-press on the overlay grabs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GrabKind {
    /// Inside a shape: drag moves it.
    Move,
    /// On a shape's border: drag resizes it.
    Resize(ResizeHandle),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Selection {
    pub shape: Shape,
    pub label: String,
    /// Index into the session's monitor list.
    pub monitor: usize,
    /// Rotation in degrees (`0..360`) about the shape's bbox center.
    pub rot_deg: i32,
}

impl Selection {
    pub const fn new(shape: Shape, monitor: usize) -> Self {
        Self {
            shape,
            label: String::new(),
            monitor,
            rot_deg: 0,
        }
    }
}

/// State-restoring operations. Applying one yields its own inverse, which
/// is what lets a single engine drive both undo and redo.
#[derive(Debug, Clone)]
enum UndoOp {
    RemoveLast,
    Restack { from: usize, to: usize },
    RemoveAt { index: usize },
    Reinsert { index: usize, selection: Selection },
    RestoreShape { index: usize, shape: Shape },
    RestoreLabel { index: usize, label: String },
    RestoreRotation { index: usize, deg: i32 },
    // Measures ride the same stack as selections rather than a parallel
    // one, so Z undoes the last thing the user did whatever kind it was.
    // Two stacks would undo the last *shape* and leave a ruler drawn
    // after it standing, which is not what anybody means by undo.
    RemoveLastMeasure,
    ReinsertMeasure { index: usize, measure: Measure },
    RemoveMeasureAt { index: usize },
    RestoreMeasureLine { index: usize, line: Line },
    RestoreMeasureLabel { index: usize, label: String },
}

#[derive(Debug, Default)]
pub struct SelectionSet {
    items: Vec<Selection>,
    measures: Vec<Measure>,
    undo: Vec<UndoOp>,
    redo: Vec<UndoOp>,
}

impl SelectionSet {
    pub fn new() -> Self {
        Self::default()
    }

    /// A set pre-populated with existing selections — restoring a saved
    /// session. Seeding is not an edit: no undo history is created, so
    /// undo in a resumed session stops at the resume point instead of
    /// dismantling the session it reopened.
    pub fn seed(items: Vec<Selection>, measures: Vec<Measure>) -> Self {
        Self {
            items,
            measures,
            undo: Vec::new(),
            redo: Vec::new(),
        }
    }

    pub fn items(&self) -> &[Selection] {
        &self.items
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub fn get(&self, index: usize) -> Option<&Selection> {
        self.items.get(index)
    }

    /// Topmost selection on `monitor` containing `p` (most recent wins),
    /// respecting each selection's rotation.
    pub fn hit_topmost(&self, monitor: usize, p: Point) -> Option<usize> {
        self.items
            .iter()
            .enumerate()
            .rev()
            .find(|(_, s)| s.monitor == monitor && s.shape.hit_test_rotated(s.rot_deg, p))
            .map(|(i, _)| i)
    }

    /// What a press at `p` grabs, topmost selection first: a border within
    /// `tolerance` resizes, an interior moves. A shape's border outranks
    /// its own interior; a topmost shape outranks anything beneath it.
    pub fn grab_topmost(
        &self,
        monitor: usize,
        p: Point,
        tolerance: i32,
    ) -> Option<(usize, GrabKind)> {
        self.items
            .iter()
            .enumerate()
            .rev()
            .filter(|(_, s)| s.monitor == monitor)
            .find_map(|(i, s)| {
                if let Some(handle) = s.shape.resize_grab_rotated(s.rot_deg, p, tolerance) {
                    return Some((i, GrabKind::Resize(handle)));
                }
                if s.shape.hit_test_rotated(s.rot_deg, p) {
                    return Some((i, GrabKind::Move));
                }
                None
            })
    }

    /// Rotate a selection by `delta` degrees about its bbox center; circles
    /// are inherently rotation-free and are left untouched. Returns the new
    /// rotation, or `None` if nothing changed.
    pub fn rotate(&mut self, index: usize, delta: i32) -> Option<i32> {
        let s = self.items.get_mut(index)?;
        if matches!(s.shape, Shape::Circle { .. }) || delta == 0 {
            return None;
        }
        let previous = s.rot_deg;
        s.rot_deg = crate::geometry::normalize_deg(s.rot_deg + delta);
        self.undo.push(UndoOp::RestoreRotation {
            index,
            deg: previous,
        });
        self.redo.clear();
        Some(self.items[index].rot_deg)
    }

    pub fn measures(&self) -> &[Measure] {
        &self.measures
    }

    pub fn add_measure(&mut self, measure: Measure) {
        self.measures.push(measure);
        self.undo.push(UndoOp::RemoveLastMeasure);
        self.redo.clear();
    }

    pub fn delete_measure(&mut self, index: usize) -> bool {
        if index >= self.measures.len() {
            return false;
        }
        let measure = self.measures.remove(index);
        self.undo.push(UndoOp::ReinsertMeasure { index, measure });
        self.redo.clear();
        true
    }

    /// Topmost measure on `monitor` that a press at `p` grabs — an
    /// endpoint first, then the line itself. Most recent wins, as with
    /// selections.
    pub fn grab_measure(
        &self,
        monitor: usize,
        p: Point,
        tolerance: i32,
    ) -> Option<(usize, MeasureGrab)> {
        self.measures
            .iter()
            .enumerate()
            .rev()
            .filter(|(_, m)| m.monitor == monitor)
            .find_map(|(i, m)| {
                if let Some(is_a) = m.line.endpoint_grab(p, tolerance) {
                    return Some((i, MeasureGrab::Endpoint(is_a)));
                }
                m.line
                    .hit_test(p, tolerance)
                    .then_some((i, MeasureGrab::Move))
            })
    }

    /// Update a measure mid-drag without recording history; pair with
    /// `commit_measure` when the drag ends.
    pub fn set_measure_line_live(&mut self, index: usize, line: Line) {
        if let Some(m) = self.measures.get_mut(index) {
            m.line = line;
        }
    }

    /// Record a finished measure edit. `original` is the line as it stood
    /// when the drag began; a drag that ended where it started records
    /// nothing and does not dirty the session.
    pub fn commit_measure(&mut self, index: usize, original: Line) -> bool {
        let Some(m) = self.measures.get(index) else {
            return false;
        };
        if m.line == original {
            return false;
        }
        self.undo.push(UndoOp::RestoreMeasureLine {
            index,
            line: original,
        });
        self.redo.clear();
        true
    }

    /// Set a measure's label. An unchanged label records nothing, the
    /// same rule the selection labels follow.
    pub fn label_measure(&mut self, index: usize, label: String) -> bool {
        let Some(m) = self.measures.get_mut(index) else {
            return false;
        };
        if m.label == label {
            return false;
        }
        let previous = std::mem::replace(&mut m.label, label);
        self.undo.push(UndoOp::RestoreMeasureLabel {
            index,
            label: previous,
        });
        self.redo.clear();
        true
    }

    pub fn add(&mut self, selection: Selection) {
        self.items.push(selection);
        self.undo.push(UndoOp::RemoveLast);
        self.redo.clear();
    }

    pub fn delete(&mut self, index: usize) -> bool {
        if index >= self.items.len() {
            return false;
        }
        let selection = self.items.remove(index);
        self.undo.push(UndoOp::Reinsert { index, selection });
        self.redo.clear();
        true
    }

    /// Update a shape mid-drag without recording undo history; pair with
    /// `commit_move` when the drag ends.
    pub fn set_shape_live(&mut self, index: usize, shape: Shape) {
        if let Some(s) = self.items.get_mut(index) {
            s.shape = shape;
        }
    }

    /// Record a completed move: `original` is the shape as it was when the
    /// drag started. No-op if the shape ended up back where it began.
    /// Returns whether the shape actually changed — a no-op move records
    /// nothing and shouldn't dirty the session.
    pub fn commit_move(&mut self, index: usize, original: Shape) -> bool {
        let Some(s) = self.items.get(index) else {
            return false;
        };
        if s.shape == original {
            return false;
        }
        self.undo.push(UndoOp::RestoreShape {
            index,
            shape: original,
        });
        self.redo.clear();
        true
    }

    /// Returns whether the label actually changed — committing the editor
    /// without edits records nothing.
    pub fn set_label(&mut self, index: usize, label: String) -> bool {
        let Some(s) = self.items.get_mut(index) else {
            return false;
        };
        if s.label == label {
            return false;
        }
        let previous = std::mem::replace(&mut s.label, label);
        self.undo.push(UndoOp::RestoreLabel {
            index,
            label: previous,
        });
        self.redo.clear();
        true
    }

    /// Send the topmost shape under `p` to the bottom of the stack, so
    /// the next grab reaches what was beneath it. Returns false when
    /// fewer than two shapes are under the point. Stacking order is also
    /// save order, so this is an undoable edit like any other.
    pub fn cycle_at(&mut self, monitor: usize, p: Point) -> bool {
        let hits: Vec<usize> = self
            .items
            .iter()
            .enumerate()
            .filter(|(_, s)| s.monitor == monitor && s.shape.hit_test_rotated(s.rot_deg, p))
            .map(|(i, _)| i)
            .collect();
        let (Some(&bottom), Some(&top)) = (hits.first(), hits.last()) else {
            return false;
        };
        if bottom == top {
            return false;
        }
        let selection = self.items.remove(top);
        self.items.insert(bottom, selection);
        self.undo.push(UndoOp::Restack {
            from: bottom,
            to: top,
        });
        self.redo.clear();
        true
    }

    /// Undo the most recent operation. Returns false when there is nothing
    /// to undo.
    pub fn undo(&mut self) -> bool {
        let Some(op) = self.undo.pop() else {
            return false;
        };
        if let Some(inverse) = self.apply(op) {
            self.redo.push(inverse);
        }
        true
    }

    /// Re-apply the most recently undone operation. Returns false when
    /// there is nothing to redo — any new edit empties the redo branch.
    pub fn redo(&mut self) -> bool {
        let Some(op) = self.redo.pop() else {
            return false;
        };
        if let Some(inverse) = self.apply(op) {
            self.undo.push(inverse);
        }
        true
    }

    /// Apply a state-restoring op and return its inverse — the op that
    /// puts things back exactly as they were before this call.
    fn apply(&mut self, op: UndoOp) -> Option<UndoOp> {
        match op {
            UndoOp::Restack { from, to } => {
                if from >= self.items.len() {
                    return None;
                }
                let selection = self.items.remove(from);
                let to = to.min(self.items.len());
                self.items.insert(to, selection);
                Some(UndoOp::Restack { from: to, to: from })
            }
            UndoOp::RemoveLast => {
                let selection = self.items.pop()?;
                Some(UndoOp::Reinsert {
                    index: self.items.len(),
                    selection,
                })
            }
            UndoOp::RemoveAt { index } => {
                if index >= self.items.len() {
                    return None;
                }
                let selection = self.items.remove(index);
                Some(UndoOp::Reinsert { index, selection })
            }
            UndoOp::Reinsert { index, selection } => {
                let index = index.min(self.items.len());
                self.items.insert(index, selection);
                Some(UndoOp::RemoveAt { index })
            }
            UndoOp::RestoreShape { index, shape } => {
                let s = self.items.get_mut(index)?;
                let previous = std::mem::replace(&mut s.shape, shape);
                Some(UndoOp::RestoreShape {
                    index,
                    shape: previous,
                })
            }
            UndoOp::RestoreLabel { index, label } => {
                let s = self.items.get_mut(index)?;
                let previous = std::mem::replace(&mut s.label, label);
                Some(UndoOp::RestoreLabel {
                    index,
                    label: previous,
                })
            }
            UndoOp::RestoreRotation { index, deg } => {
                let s = self.items.get_mut(index)?;
                let previous = std::mem::replace(&mut s.rot_deg, deg);
                Some(UndoOp::RestoreRotation {
                    index,
                    deg: previous,
                })
            }
            UndoOp::RemoveLastMeasure => {
                let measure = self.measures.pop()?;
                Some(UndoOp::ReinsertMeasure {
                    index: self.measures.len(),
                    measure,
                })
            }
            UndoOp::ReinsertMeasure { index, measure } => {
                let index = index.min(self.measures.len());
                self.measures.insert(index, measure);
                Some(UndoOp::RemoveMeasureAt { index })
            }
            UndoOp::RemoveMeasureAt { index } => {
                if index >= self.measures.len() {
                    return None;
                }
                let measure = self.measures.remove(index);
                Some(UndoOp::ReinsertMeasure { index, measure })
            }
            UndoOp::RestoreMeasureLine { index, line } => {
                let m = self.measures.get_mut(index)?;
                let previous = m.line;
                m.line = line;
                Some(UndoOp::RestoreMeasureLine {
                    index,
                    line: previous,
                })
            }
            UndoOp::RestoreMeasureLabel { index, label } => {
                let m = self.measures.get_mut(index)?;
                let previous = std::mem::replace(&mut m.label, label);
                Some(UndoOp::RestoreMeasureLabel {
                    index,
                    label: previous,
                })
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn measures_and_selections_share_one_undo_stack() {
        // The reason they share it: Z should undo the last thing done,
        // whatever kind it was. Two stacks would undo the last *shape*
        // and leave a ruler drawn after it standing.
        let mut set = SelectionSet::new();
        set.add(Selection::new(Shape::Rect(Rect::new(0, 0, 10, 10)), 0));
        set.add_measure(Measure::new(
            Line::new(Point::new(0, 0), Point::new(50, 0)),
            0,
        ));
        assert_eq!((set.len(), set.measures().len()), (1, 1));

        assert!(set.undo(), "undoes the measure, the most recent edit");
        assert_eq!((set.len(), set.measures().len()), (1, 0));
        assert!(set.undo(), "then the selection");
        assert_eq!((set.len(), set.measures().len()), (0, 0));

        assert!(set.redo());
        assert!(set.redo());
        assert_eq!((set.len(), set.measures().len()), (1, 1));
    }

    #[test]
    fn a_deleted_measure_comes_back_where_it_was() {
        let mut set = SelectionSet::new();
        for x in [10, 20, 30] {
            set.add_measure(Measure::new(
                Line::new(Point::new(x, 0), Point::new(x, 40)),
                0,
            ));
        }
        assert!(set.delete_measure(1));
        assert_eq!(set.measures().len(), 2);
        assert!(set.undo());
        assert_eq!(set.measures()[1].line.a.x, 20, "restored in position");
    }

    #[test]
    fn a_measure_drag_that_ends_where_it_began_records_nothing() {
        let mut set = SelectionSet::new();
        let line = Line::new(Point::new(0, 0), Point::new(60, 20));
        set.add_measure(Measure::new(line, 0));
        set.set_measure_line_live(0, Line::new(Point::new(0, 0), Point::new(99, 99)));
        set.set_measure_line_live(0, line);
        assert!(
            !set.commit_measure(0, line),
            "a no-op drag must not dirty the session"
        );
        // The only history is the add, so one undo empties it.
        assert!(set.undo());
        assert!(set.measures().is_empty());
        assert!(!set.undo());
    }

    #[test]
    fn relabeling_a_measure_is_undoable_and_a_no_op_label_is_not() {
        let mut set = SelectionSet::new();
        set.add_measure(Measure::new(
            Line::new(Point::new(0, 0), Point::new(10, 0)),
            0,
        ));
        assert!(set.label_measure(0, "gap".into()));
        assert!(!set.label_measure(0, "gap".into()), "unchanged label");
        assert!(set.undo());
        assert_eq!(set.measures()[0].label, "");
    }

    #[test]
    fn grabbing_prefers_an_endpoint_over_the_line_and_respects_the_monitor() {
        let mut set = SelectionSet::new();
        set.add_measure(Measure::new(
            Line::new(Point::new(0, 0), Point::new(100, 0)),
            0,
        ));
        assert_eq!(
            set.grab_measure(0, Point::new(1, 1), 6),
            Some((0, MeasureGrab::Endpoint(true)))
        );
        assert_eq!(
            set.grab_measure(0, Point::new(50, 2), 6),
            Some((0, MeasureGrab::Move))
        );
        assert_eq!(set.grab_measure(0, Point::new(50, 40), 6), None);
        assert_eq!(
            set.grab_measure(1, Point::new(1, 1), 6),
            None,
            "a measure belongs to one monitor's frame"
        );
    }
    use crate::geometry::Rect;

    fn rect_at(x: i32) -> Shape {
        Shape::Rect(Rect::new(x, 0, 100, 100))
    }

    #[test]
    fn hit_topmost_prefers_most_recent() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        set.add(Selection::new(rect_at(50), 0));
        // (60, 10) is inside both; the later one wins.
        assert_eq!(set.hit_topmost(0, Point::new(60, 10)), Some(1));
        assert_eq!(set.hit_topmost(0, Point::new(10, 10)), Some(0));
        assert_eq!(set.hit_topmost(0, Point::new(500, 500)), None);
    }

    #[test]
    fn hit_topmost_filters_by_monitor() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 1));
        assert_eq!(set.hit_topmost(0, Point::new(10, 10)), None);
        assert_eq!(set.hit_topmost(1, Point::new(10, 10)), Some(0));
    }

    #[test]
    fn undo_add_removes_it() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        assert!(set.undo());
        assert!(set.is_empty());
    }

    #[test]
    fn undo_delete_reinserts_at_original_position() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        set.add(Selection::new(rect_at(200), 0));
        set.add(Selection::new(rect_at(400), 0));
        assert!(set.delete(1));
        assert_eq!(set.len(), 2);
        assert!(set.undo());
        assert_eq!(set.items()[1].shape, rect_at(200));
    }

    #[test]
    fn undo_move_restores_original_shape() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        let original = set.items()[0].shape.clone();
        set.set_shape_live(0, rect_at(300));
        set.commit_move(0, original.clone());
        assert!(set.undo());
        assert_eq!(set.items()[0].shape, original);
    }

    #[test]
    fn commit_move_without_change_records_nothing() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        let original = set.items()[0].shape.clone();
        set.commit_move(0, original.clone());
        // Only the add is on the stack: one undo empties the set.
        assert!(set.undo());
        assert!(set.is_empty());
        assert!(!set.undo());
    }

    #[test]
    fn noop_label_and_move_record_nothing() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        // Committing the same label (including empty -> empty) is a no-op.
        assert!(!set.set_label(0, String::new()));
        assert!(set.set_label(0, "named".into()));
        assert!(!set.set_label(0, "named".into()));
        // An unchanged move is a no-op.
        let original = set.items()[0].shape.clone();
        assert!(!set.commit_move(0, original));
        // Stack: label change, then the add — exactly two undos.
        assert!(set.undo());
        assert_eq!(set.items()[0].label, "");
        assert!(set.undo());
        assert!(!set.undo());
    }

    #[test]
    fn undo_label_restores_previous_text() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        set.set_label(0, "first".into());
        set.set_label(0, "second".into());
        assert!(set.undo());
        assert_eq!(set.items()[0].label, "first");
        assert!(set.undo());
        assert_eq!(set.items()[0].label, "");
    }

    #[test]
    fn cycling_overlap_reaches_the_shape_beneath_and_undoes() {
        let mut set = SelectionSet::new();
        let mut below = Selection::new(Shape::Rect(Rect::new(0, 0, 100, 100)), 0);
        below.label = "below".into();
        let mut above = Selection::new(Shape::Rect(Rect::new(10, 10, 50, 50)), 0);
        above.label = "above".into();
        set.add(below);
        set.add(above);
        let p = Point::new(20, 20);
        assert_eq!(set.items()[set.hit_topmost(0, p).unwrap()].label, "above");

        assert!(set.cycle_at(0, p));
        assert_eq!(
            set.items()[set.hit_topmost(0, p).unwrap()].label,
            "below",
            "the shape beneath is now grabbable"
        );
        // Cycling again comes back around.
        assert!(set.cycle_at(0, p));
        assert_eq!(set.items()[set.hit_topmost(0, p).unwrap()].label, "above");
        // And the whole dance unwinds.
        assert!(set.undo());
        assert!(set.undo());
        assert_eq!(set.items()[set.hit_topmost(0, p).unwrap()].label, "above");
        assert_eq!(set.items()[0].label, "below", "original order restored");
    }

    #[test]
    fn get_returns_the_selection_or_nothing() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(Shape::Rect(Rect::new(1, 1, 2, 2)), 0));
        assert!(set.get(0).is_some());
        assert!(set.get(1).is_none());
    }

    #[test]
    fn cycling_needs_at_least_two_shapes_under_the_point() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(Shape::Rect(Rect::new(0, 0, 10, 10)), 0));
        assert!(
            !set.cycle_at(0, Point::new(5, 5)),
            "one shape: nothing to cycle"
        );
        assert!(
            !set.cycle_at(0, Point::new(50, 50)),
            "no shape: nothing to cycle"
        );
    }

    #[test]
    fn seeding_restores_items_without_undo_history() {
        let mut sel = Selection::new(Shape::Rect(Rect::new(1, 2, 3, 4)), 0);
        sel.label = "kept".into();
        sel.rot_deg = 30;
        let mut set = SelectionSet::seed(vec![sel], Vec::new());
        assert_eq!(set.len(), 1);
        assert_eq!(set.items()[0].label, "kept");
        assert!(!set.undo(), "the resume point is the floor of history");
        // Edits after seeding behave normally.
        set.delete(0);
        assert!(set.undo());
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn redo_reapplies_undone_edits_across_every_op_kind() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(Shape::Rect(Rect::new(0, 0, 10, 10)), 0));
        set.set_label(0, "a".into());
        set.rotate(0, 45);
        set.set_shape_live(0, Shape::Rect(Rect::new(5, 5, 10, 10)));
        set.commit_move(0, Shape::Rect(Rect::new(0, 0, 10, 10)));
        set.delete(0);
        while set.undo() {}
        assert!(set.is_empty(), "everything unwinds");
        while set.redo() {}
        assert!(set.is_empty(), "the final delete replays too");
        // One more undo brings the deleted selection back fully formed.
        assert!(set.undo());
        let s = &set.items()[0];
        assert_eq!(s.label, "a");
        assert_eq!(s.rot_deg, 45);
        assert_eq!(s.shape, Shape::Rect(Rect::new(5, 5, 10, 10)));
    }

    #[test]
    fn a_new_edit_empties_the_redo_branch() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(Shape::Rect(Rect::new(0, 0, 10, 10)), 0));
        assert!(set.undo());
        set.add(Selection::new(Shape::Rect(Rect::new(9, 9, 5, 5)), 0));
        assert!(!set.redo(), "a new edit forked history; redo is gone");
    }

    #[test]
    fn redo_with_nothing_undone_is_false() {
        let mut set = SelectionSet::new();
        assert!(!set.redo());
        set.add(Selection::new(Shape::Rect(Rect::new(0, 0, 4, 4)), 0));
        assert!(!set.redo(), "un-undone edits leave nothing to redo");
    }

    #[test]
    fn undo_is_lifo_across_mixed_ops() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        set.set_label(0, "a".into());
        set.delete(0);
        assert!(set.undo()); // reinsert with label "a"
        assert_eq!(set.items()[0].label, "a");
        assert!(set.undo()); // label back to ""
        assert_eq!(set.items()[0].label, "");
        assert!(set.undo()); // remove the add
        assert!(set.is_empty());
        assert!(!set.undo());
    }

    #[test]
    fn delete_out_of_range_is_false() {
        let mut set = SelectionSet::new();
        assert!(!set.delete(0));
    }

    #[test]
    fn rotate_records_undo_and_skips_circles() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0));
        set.add(Selection::new(Shape::Circle { cx: 0, cy: 0, r: 9 }, 0));

        assert_eq!(set.rotate(0, 15), Some(15));
        assert_eq!(set.rotate(0, -30), Some(345));
        assert_eq!(set.rotate(1, 15), None, "circles don't rotate");
        assert_eq!(set.rotate(0, 0), None, "zero delta is a no-op");

        assert!(set.undo());
        assert_eq!(set.items()[0].rot_deg, 15);
        assert!(set.undo());
        assert_eq!(set.items()[0].rot_deg, 0);
    }

    #[test]
    fn rotated_selection_hit_follows_rotation() {
        let mut set = SelectionSet::new();
        // Wide flat rect at (0,0) 100x20... rect_at gives 100x100; use a
        // custom flat one so rotation visibly changes the hit region.
        set.add(Selection::new(Shape::Rect(Rect::new(100, 100, 200, 20)), 0));
        set.rotate(0, 90);
        assert_eq!(set.hit_topmost(0, Point::new(200, 30)), Some(0));
        assert_eq!(set.hit_topmost(0, Point::new(290, 110)), None);
    }

    #[test]
    fn grab_prefers_border_resize_over_interior_move() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0)); // (0,0,100,100)
        // On the left edge: resize.
        let Some((0, GrabKind::Resize(_))) = set.grab_topmost(0, Point::new(1, 50), 5) else {
            panic!("expected a resize grab on the edge");
        };
        // Deep inside: move.
        assert_eq!(
            set.grab_topmost(0, Point::new(50, 50), 5),
            Some((0, GrabKind::Move))
        );
        // Far away: nothing.
        assert_eq!(set.grab_topmost(0, Point::new(500, 500), 5), None);
    }

    #[test]
    fn grab_topmost_shape_shadows_lower_border() {
        let mut set = SelectionSet::new();
        set.add(Selection::new(rect_at(0), 0)); // right edge at x=100
        set.add(Selection::new(Shape::Rect(Rect::new(50, 0, 200, 100)), 0)); // covers it
        // (100, 50) is the lower rect's edge but the upper rect's interior:
        // the topmost shape wins with a move grab.
        assert_eq!(
            set.grab_topmost(0, Point::new(100, 50), 5),
            Some((1, GrabKind::Move))
        );
    }
}