Skip to main content

rofd_editor/
payload_util.rs

1use rofd_dom::{AnnotationPayload, Color, PathCommand, Point, Rect, ShapeKind};
2
3/// Shift an annotation's geometry by (dx, dy).
4pub fn move_payload(p: &mut AnnotationPayload, dx: f64, dy: f64) {
5    match p {
6        AnnotationPayload::Markup { quad_points, .. } => {
7            for pt in quad_points {
8                pt.x += dx;
9                pt.y += dy;
10            }
11        }
12        AnnotationPayload::Freehand { path, .. } => {
13            for cmd in &mut path.commands {
14                shift_cmd(cmd, dx, dy);
15            }
16        }
17        AnnotationPayload::Shape { rect, points, .. } => {
18            rect.x += dx;
19            rect.y += dy;
20            // Line/Arrow/Polygon/PolyLine endpoints must move with the bbox,
21            // else the geometry stays put while the bbox slides away.
22            for pt in points {
23                pt.x += dx;
24                pt.y += dy;
25            }
26        }
27        AnnotationPayload::Note { rect, .. }
28        | AnnotationPayload::TextBox { rect, .. }
29        | AnnotationPayload::Stamp { rect, .. }
30        | AnnotationPayload::Watermark { rect, .. } => {
31            rect.x += dx;
32            rect.y += dy;
33        }
34    }
35}
36
37/// Set the rect (for resize). No-op for Markup/Freehand (no single rect).
38///
39/// For `Shape`, the endpoint `points` are rescaled from the old rect to the
40/// new rect (proportional, per-axis), preserving each point's relative
41/// position within the bbox. This keeps a Line/Arrow's direction and a
42/// Polygon/PolyLine's shape intact across resize. A degenerate old rect
43/// (zero size on an axis) degrades to translating points by the origin delta.
44pub fn resize_payload(p: &mut AnnotationPayload, new_rect: Rect) {
45    match p {
46        AnnotationPayload::Shape { rect, points, .. } => {
47            let old = *rect;
48            if !points.is_empty() {
49                let sx = if old.w != 0.0 {
50                    new_rect.w / old.w
51                } else {
52                    1.0
53                };
54                let sy = if old.h != 0.0 {
55                    new_rect.h / old.h
56                } else {
57                    1.0
58                };
59                for pt in points {
60                    pt.x = new_rect.x + (pt.x - old.x) * sx;
61                    pt.y = new_rect.y + (pt.y - old.y) * sy;
62                }
63            }
64            *rect = new_rect;
65        }
66        AnnotationPayload::Note { rect, .. }
67        | AnnotationPayload::TextBox { rect, .. }
68        | AnnotationPayload::Stamp { rect, .. }
69        | AnnotationPayload::Watermark { rect, .. } => {
70            *rect = new_rect;
71        }
72        AnnotationPayload::Markup { .. } | AnnotationPayload::Freehand { .. } => { /* no-op v1 */ }
73    }
74}
75
76/// Move vertex `index` of a point-based Shape payload to `new_point` and
77/// recompute `rect` as the points' bounding box (hit-test / selection frame /
78/// resize all read `rect`). Returns false -- payload untouched -- for
79/// rect-based Shape kinds (Rect/Ellipse), non-Shape payloads, or an
80/// out-of-range index.
81///
82/// Line/Arrow with NO points first seeds the endpoints from the rect's
83/// TL->BR diagonal (mirroring render's `line_endpoints` fallback) so external
84/// OFD that carries only a boundary is still editable. A 1-point Line/Arrow
85/// is degenerate and is a clean no-op (returns false, payload untouched) -
86/// seeding it would corrupt the geometry to 3 points while rendering reads
87/// `points[0..2]`. Seeding only happens when `index` is reachable (< 2), so
88/// a false return never leaves a partially seeded payload behind.
89pub fn move_vertex_payload(p: &mut AnnotationPayload, index: usize, new_point: (f64, f64)) -> bool {
90    let AnnotationPayload::Shape {
91        kind, rect, points, ..
92    } = p
93    else {
94        return false;
95    };
96    if !matches!(
97        kind,
98        ShapeKind::Line | ShapeKind::Arrow | ShapeKind::Polygon | ShapeKind::PolyLine
99    ) {
100        return false;
101    }
102    if matches!(kind, ShapeKind::Line | ShapeKind::Arrow) {
103        if points.is_empty() && index < 2 {
104            points.push(Point {
105                x: rect.x,
106                y: rect.y,
107            });
108            points.push(Point {
109                x: rect.x + rect.w,
110                y: rect.y + rect.h,
111            });
112        }
113        if points.len() < 2 {
114            // Degenerate 1-point Line/Arrow: no meaningful vertex geometry to
115            // edit. Nothing was seeded above, so return a clean no-op.
116            return false;
117        }
118    }
119    let Some(pt) = points.get_mut(index) else {
120        return false;
121    };
122    pt.x = new_point.0;
123    pt.y = new_point.1;
124    let (mut minx, mut miny, mut maxx, mut maxy) = (
125        f64::INFINITY,
126        f64::INFINITY,
127        f64::NEG_INFINITY,
128        f64::NEG_INFINITY,
129    );
130    for p in points.iter() {
131        minx = minx.min(p.x);
132        miny = miny.min(p.y);
133        maxx = maxx.max(p.x);
134        maxy = maxy.max(p.y);
135    }
136    *rect = Rect {
137        x: minx,
138        y: miny,
139        w: maxx - minx,
140        h: maxy - miny,
141    };
142    true
143}
144
145fn shift_cmd(cmd: &mut PathCommand, dx: f64, dy: f64) {
146    match cmd {
147        PathCommand::M(x, y) | PathCommand::L(x, y) => {
148            *x += dx;
149            *y += dy;
150        }
151        PathCommand::C(x1, y1, x2, y2, x, y) => {
152            *x1 += dx;
153            *y1 += dy;
154            *x2 += dx;
155            *y2 += dy;
156            *x += dx;
157            *y += dy;
158        }
159        PathCommand::Q(x1, y1, x, y) => {
160            *x1 += dx;
161            *y1 += dy;
162            *x += dx;
163            *y += dy;
164        }
165        PathCommand::A(_a, _b, _c, _d, x, y) => {
166            *x += dx;
167            *y += dy;
168        }
169        PathCommand::Z => {}
170    }
171}
172
173/// Set the primary color of an annotation (no-op for Stamp which has no color).
174pub fn set_color(p: &mut AnnotationPayload, color: Color) {
175    match p {
176        AnnotationPayload::Markup { color: c, .. } => *c = color,
177        AnnotationPayload::Freehand { color: c, .. } => *c = color,
178        AnnotationPayload::Shape { stroke: c, .. } => *c = color,
179        AnnotationPayload::Note { color: c, .. } => *c = color,
180        AnnotationPayload::TextBox { color: c, .. } => *c = color,
181        AnnotationPayload::Watermark { color: c, .. } => *c = color,
182        AnnotationPayload::Stamp { .. } => { /* no color */ }
183    }
184}
185
186/// Set the stroke width (Freehand/Shape only; no-op otherwise).
187pub fn set_width(p: &mut AnnotationPayload, width: f64) {
188    match p {
189        AnnotationPayload::Freehand { width: w, .. } => *w = width,
190        AnnotationPayload::Shape { width: w, .. } => *w = width,
191        _ => {}
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    use super::*;
198    use rofd_dom::{Color, PathData, Point, ShapeKind};
199
200    #[test]
201    fn move_note_shifts_rect() {
202        let mut p = AnnotationPayload::Note {
203            rect: Rect {
204                x: 10.0,
205                y: 10.0,
206                w: 5.0,
207                h: 5.0,
208            },
209            color: Color::Rgb(0, 0, 0),
210            content: "".into(),
211            icon: rofd_dom::NoteIcon::Note,
212        };
213        move_payload(&mut p, 3.0, 4.0);
214        assert!(matches!(
215            p,
216            AnnotationPayload::Note {
217                rect: Rect {
218                    x: 13.0,
219                    y: 14.0,
220                    ..
221                },
222                ..
223            }
224        ));
225    }
226
227    #[test]
228    fn resize_shape_sets_rect() {
229        let mut p = AnnotationPayload::Shape {
230            kind: rofd_dom::ShapeKind::Rect,
231            rect: Rect {
232                x: 0.0,
233                y: 0.0,
234                w: 1.0,
235                h: 1.0,
236            },
237            stroke: Color::Rgb(0, 0, 0),
238            fill: None,
239            width: 1.0,
240            points: vec![],
241        };
242        resize_payload(
243            &mut p,
244            Rect {
245                x: 5.0,
246                y: 5.0,
247                w: 2.0,
248                h: 2.0,
249            },
250        );
251        assert!(matches!(
252            p,
253            AnnotationPayload::Shape {
254                rect: Rect {
255                    x: 5.0,
256                    y: 5.0,
257                    w: 2.0,
258                    h: 2.0
259                },
260                ..
261            }
262        ));
263    }
264
265    #[test]
266    fn move_freehand_shifts_path_points() {
267        let mut p = AnnotationPayload::Freehand {
268            path: PathData {
269                commands: vec![PathCommand::M(1.0, 2.0), PathCommand::L(3.0, 4.0)],
270            },
271            color: Color::Rgb(0, 0, 0),
272            width: 1.0,
273        };
274        move_payload(&mut p, 10.0, 20.0);
275        if let AnnotationPayload::Freehand { path, .. } = &p {
276            assert!(matches!(path.commands[0], PathCommand::M(11.0, 22.0)));
277            assert!(matches!(path.commands[1], PathCommand::L(13.0, 24.0)));
278        } else {
279            panic!("expected Freehand");
280        }
281    }
282
283    #[test]
284    fn move_shape_translates_points_with_rect() {
285        // A Line's `points` must move with `rect` (else the line stays put
286        // while its bbox moves -> arrow renders at the wrong place).
287        let mut p = AnnotationPayload::Shape {
288            kind: rofd_dom::ShapeKind::Line,
289            rect: Rect {
290                x: 10.0,
291                y: 10.0,
292                w: 40.0,
293                h: 50.0,
294            },
295            stroke: Color::Rgb(0, 0, 0),
296            fill: None,
297            width: 2.0,
298            points: vec![
299                rofd_dom::Point { x: 10.0, y: 10.0 },
300                rofd_dom::Point { x: 50.0, y: 60.0 },
301            ],
302        };
303        move_payload(&mut p, 3.0, 4.0);
304        match p {
305            AnnotationPayload::Shape { rect, points, .. } => {
306                assert_eq!(rect.x, 13.0);
307                assert_eq!(rect.y, 14.0);
308                assert_eq!(
309                    points,
310                    vec![
311                        rofd_dom::Point { x: 13.0, y: 14.0 },
312                        rofd_dom::Point { x: 53.0, y: 64.0 },
313                    ],
314                    "points must translate with rect"
315                );
316            }
317            _ => panic!("expected Shape"),
318        }
319    }
320
321    #[test]
322    fn move_polygon_translates_points() {
323        // Polygon `points` must move with `rect` (latent bug: previously only
324        // rect moved, leaving the polygon's vertices behind).
325        let mut p = AnnotationPayload::Shape {
326            kind: rofd_dom::ShapeKind::Polygon,
327            rect: Rect {
328                x: 0.0,
329                y: 0.0,
330                w: 10.0,
331                h: 10.0,
332            },
333            stroke: Color::Rgb(255, 0, 0),
334            fill: None,
335            width: 1.0,
336            points: vec![
337                rofd_dom::Point { x: 0.0, y: 0.0 },
338                rofd_dom::Point { x: 5.0, y: 10.0 },
339                rofd_dom::Point { x: 10.0, y: 0.0 },
340            ],
341        };
342        move_payload(&mut p, 1.0, 2.0);
343        if let AnnotationPayload::Shape { points, rect, .. } = &p {
344            assert_eq!(rect.x, 1.0);
345            assert_eq!(rect.y, 2.0);
346            assert_eq!(
347                points,
348                &vec![
349                    rofd_dom::Point { x: 1.0, y: 2.0 },
350                    rofd_dom::Point { x: 6.0, y: 12.0 },
351                    rofd_dom::Point { x: 11.0, y: 2.0 },
352                ]
353            );
354        }
355    }
356
357    #[test]
358    fn resize_shape_scales_points_proportionally() {
359        // Resizing the bbox must rescale the endpoints proportionally so the
360        // line keeps its relative position/direction within the bbox. A Line
361        // from rect TL->BR (0,0,100,50) resized to (10,20,200,100) maps the
362        // endpoints (0,0)->(10,20) and (100,50)->(210,120).
363        let mut p = AnnotationPayload::Shape {
364            kind: rofd_dom::ShapeKind::Line,
365            rect: Rect {
366                x: 0.0,
367                y: 0.0,
368                w: 100.0,
369                h: 50.0,
370            },
371            stroke: Color::Rgb(0, 0, 0),
372            fill: None,
373            width: 2.0,
374            points: vec![
375                rofd_dom::Point { x: 0.0, y: 0.0 },
376                rofd_dom::Point { x: 100.0, y: 50.0 },
377            ],
378        };
379        resize_payload(
380            &mut p,
381            Rect {
382                x: 10.0,
383                y: 20.0,
384                w: 200.0,
385                h: 100.0,
386            },
387        );
388        if let AnnotationPayload::Shape { rect, points, .. } = &p {
389            assert_eq!(
390                *rect,
391                Rect {
392                    x: 10.0,
393                    y: 20.0,
394                    w: 200.0,
395                    h: 100.0
396                }
397            );
398            assert_eq!(
399                points,
400                &vec![
401                    rofd_dom::Point { x: 10.0, y: 20.0 },
402                    rofd_dom::Point { x: 210.0, y: 120.0 },
403                ],
404                "points must rescale from old rect to new rect"
405            );
406        }
407    }
408
409    #[test]
410    fn resize_shape_preserves_reverse_direction() {
411        // A reverse Line (BR->TL) must keep its direction after resize: the
412        // endpoint that was at BR maps to the new BR, the TL endpoint to new TL.
413        let mut p = AnnotationPayload::Shape {
414            kind: rofd_dom::ShapeKind::Arrow,
415            rect: Rect {
416                x: 0.0,
417                y: 0.0,
418                w: 100.0,
419                h: 50.0,
420            },
421            stroke: Color::Rgb(0, 0, 0),
422            fill: None,
423            width: 2.0,
424            points: vec![
425                rofd_dom::Point { x: 100.0, y: 50.0 },
426                rofd_dom::Point { x: 0.0, y: 0.0 },
427            ],
428        };
429        resize_payload(
430            &mut p,
431            Rect {
432                x: 10.0,
433                y: 20.0,
434                w: 200.0,
435                h: 100.0,
436            },
437        );
438        if let AnnotationPayload::Shape { points, .. } = &p {
439            assert_eq!(
440                points,
441                &vec![
442                    rofd_dom::Point { x: 210.0, y: 120.0 },
443                    rofd_dom::Point { x: 10.0, y: 20.0 },
444                ],
445                "BR->TL direction preserved after resize"
446            );
447        }
448    }
449
450    #[test]
451    fn move_vertex_line_updates_points_and_rect() {
452        let mut p = AnnotationPayload::Shape {
453            kind: ShapeKind::Line,
454            rect: Rect {
455                x: 10.0,
456                y: 10.0,
457                w: 90.0,
458                h: 50.0,
459            },
460            stroke: Color::Rgb(255, 0, 0),
461            fill: None,
462            width: 2.0,
463            points: vec![Point { x: 10.0, y: 10.0 }, Point { x: 100.0, y: 60.0 }],
464        };
465        assert!(move_vertex_payload(&mut p, 1, (30.0, 20.0)));
466        match &p {
467            AnnotationPayload::Shape { rect, points, .. } => {
468                assert_eq!(points[1], Point { x: 30.0, y: 20.0 });
469                // rect 重算为 points 的 bbox:(10,10)-(30,20)
470                assert_eq!(
471                    *rect,
472                    Rect {
473                        x: 10.0,
474                        y: 10.0,
475                        w: 20.0,
476                        h: 10.0
477                    }
478                );
479            }
480            _ => panic!("expected Shape"),
481        }
482    }
483
484    #[test]
485    fn move_vertex_polygon_updates_only_that_vertex() {
486        let mut p = AnnotationPayload::Shape {
487            kind: ShapeKind::Polygon,
488            rect: Rect {
489                x: 0.0,
490                y: 0.0,
491                w: 10.0,
492                h: 10.0,
493            },
494            stroke: Color::Rgb(0, 0, 255),
495            fill: None,
496            width: 1.0,
497            points: vec![
498                Point { x: 0.0, y: 0.0 },
499                Point { x: 5.0, y: 10.0 },
500                Point { x: 10.0, y: 0.0 },
501            ],
502        };
503        assert!(move_vertex_payload(&mut p, 1, (5.0, 4.0)));
504        match &p {
505            AnnotationPayload::Shape { rect, points, .. } => {
506                assert_eq!(points[0], Point { x: 0.0, y: 0.0 });
507                assert_eq!(points[2], Point { x: 10.0, y: 0.0 });
508                assert_eq!(
509                    *rect,
510                    Rect {
511                        x: 0.0,
512                        y: 0.0,
513                        w: 10.0,
514                        h: 4.0
515                    }
516                );
517            }
518            _ => panic!("expected Shape"),
519        }
520    }
521
522    #[test]
523    fn move_vertex_line_with_empty_points_seeds_diagonal() {
524        // 外部 OFD 只带边界无顶点:先播种 rect 对角线(镜像渲染的
525        // line_endpoints 回退),再把 Vertex(1) 挪到新位置。
526        let mut p = AnnotationPayload::Shape {
527            kind: ShapeKind::Arrow,
528            rect: Rect {
529                x: 0.0,
530                y: 0.0,
531                w: 40.0,
532                h: 30.0,
533            },
534            stroke: Color::Rgb(0, 0, 0),
535            fill: None,
536            width: 2.0,
537            points: vec![],
538        };
539        assert!(move_vertex_payload(&mut p, 1, (50.0, 10.0)));
540        match &p {
541            AnnotationPayload::Shape { points, .. } => {
542                assert_eq!(points[0], Point { x: 0.0, y: 0.0 }, "seeded from rect TL");
543                assert_eq!(points[1], Point { x: 50.0, y: 10.0 });
544            }
545            _ => panic!("expected Shape"),
546        }
547    }
548
549    #[test]
550    fn move_vertex_rect_kind_is_noop() {
551        let mut p = AnnotationPayload::Shape {
552            kind: ShapeKind::Rect,
553            rect: Rect {
554                x: 0.0,
555                y: 0.0,
556                w: 10.0,
557                h: 10.0,
558            },
559            stroke: Color::Rgb(0, 0, 0),
560            fill: None,
561            width: 1.0,
562            points: vec![],
563        };
564        assert!(
565            !move_vertex_payload(&mut p, 0, (5.0, 5.0)),
566            "Rect has no vertices"
567        );
568    }
569
570    #[test]
571    fn move_vertex_out_of_range_is_noop() {
572        let mut p = AnnotationPayload::Shape {
573            kind: ShapeKind::PolyLine,
574            rect: Rect {
575                x: 0.0,
576                y: 0.0,
577                w: 10.0,
578                h: 10.0,
579            },
580            stroke: Color::Rgb(0, 0, 0),
581            fill: None,
582            width: 1.0,
583            points: vec![Point { x: 0.0, y: 0.0 }, Point { x: 10.0, y: 10.0 }],
584        };
585        let before = p.clone();
586        assert!(!move_vertex_payload(&mut p, 2, (5.0, 5.0)));
587        assert_eq!(p, before, "payload untouched on bad index");
588    }
589
590    #[test]
591    fn move_vertex_freehand_is_noop() {
592        let mut p = AnnotationPayload::Freehand {
593            path: PathData {
594                commands: vec![PathCommand::M(0.0, 0.0), PathCommand::L(5.0, 5.0)],
595            },
596            color: Color::Rgb(0, 0, 255),
597            width: 1.5,
598        };
599        assert!(!move_vertex_payload(&mut p, 0, (1.0, 1.0)));
600    }
601
602    #[test]
603    fn move_vertex_one_point_line_is_noop() {
604        // A 1-point Line is degenerate: Vertex(0)/Vertex(1) drags must return
605        // false AND leave the payload untouched. (Previously the <2 seeding
606        // guard pushed TL+BR onto the single point, yielding 3 points while
607        // rendering reads points[0..2] -> dragging Vertex(0) visibly moved the
608        // wrong endpoint.)
609        for index in [0usize, 1] {
610            let mut p = AnnotationPayload::Shape {
611                kind: ShapeKind::Line,
612                rect: Rect {
613                    x: 0.0,
614                    y: 0.0,
615                    w: 40.0,
616                    h: 30.0,
617                },
618                stroke: Color::Rgb(0, 0, 0),
619                fill: None,
620                width: 2.0,
621                points: vec![Point { x: 5.0, y: 5.0 }],
622            };
623            let before = p.clone();
624            assert!(
625                !move_vertex_payload(&mut p, index, (50.0, 10.0)),
626                "Vertex({index}) on a 1-point Line must be a clean no-op"
627            );
628            assert_eq!(p, before, "payload untouched for Vertex({index})");
629        }
630    }
631
632    #[test]
633    fn move_vertex_line_unreachable_index_does_not_seed() {
634        // Line with empty points + index >= 2: seeding must NOT run (the
635        // diagonal seed only applies when the index is reachable), so a
636        // false return leaves the payload completely untouched.
637        let mut p = AnnotationPayload::Shape {
638            kind: ShapeKind::Line,
639            rect: Rect {
640                x: 0.0,
641                y: 0.0,
642                w: 40.0,
643                h: 30.0,
644            },
645            stroke: Color::Rgb(0, 0, 0),
646            fill: None,
647            width: 2.0,
648            points: vec![],
649        };
650        let before = p.clone();
651        assert!(!move_vertex_payload(&mut p, 2, (50.0, 10.0)));
652        assert_eq!(p, before, "unreachable index must not seed the diagonal");
653        if let AnnotationPayload::Shape { points, .. } = &p {
654            assert!(points.is_empty(), "points still empty after no-op");
655        }
656    }
657}