grafia 0.9.0

Interactive 2D cubic Bezier, spline, glyph, and vector canvas widget for egui with boolean path ops, text stream kerning, and auto-trace.
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
//! `SPEC-007` (`grafia v0.6.0`) pure 2D VC-Contract (`SelectionInfoAction`),
//! HUD 3x3 Transform-Grid hit-testing, and foreground-to-background selection projection (`align_selection_to_background`).

use crate::adapters::state::GrafiaCanvasState;
use crate::core::{
    align_oncurve_nodes_to_background, toggle_selected_on_curve_smooth, FontPoint, GuideAlignment,
    NodeId, NodeType, ScreenPoint, SelectionInfo, SelectionInfoAction, TransformGridAnchor,
};
use crate::render::selection_info_hud::{
    compute_hud_proportional_icon_rect, compute_hud_rect, compute_hud_transform_grid_dot_positions,
    should_render_selection_info_hud,
};
use crate::snapping::{Guide, GuideId, SelectedGuideRef};
use crate::tokens::HUD_GRID_DOT_HIT_RADIUS_DP;

impl GrafiaCanvasState {
    /// Applies a unified pure 2D `SelectionInfoAction` from the host UI / HUD controller (`SPEC-007 ยง2.2`).
    pub fn apply_selection_info_action(&mut self, action: SelectionInfoAction) -> bool {
        match action {
            SelectionInfoAction::SetLsb(v) => {
                v.is_finite() && {
                    self.set_lsb(v);
                    true
                }
            }
            SelectionInfoAction::SetRsb(v) => {
                v.is_finite() && {
                    self.set_rsb(v);
                    true
                }
            }
            SelectionInfoAction::SetAdvanceWidth(v) => {
                v.is_finite() && {
                    self.set_advance_width(v);
                    true
                }
            }
            SelectionInfoAction::CenterInWidth => {
                self.center_glyph_in_width();
                true
            }
            SelectionInfoAction::SetOnCurvePosition(_)
            | SelectionInfoAction::ToggleOnCurveSmooth
            | SelectionInfoAction::SetOffCurvePosition(_)
            | SelectionInfoAction::SetOffCurveDelta { .. }
            | SelectionInfoAction::SetHandleLength(_) => {
                self.apply_single_node_selection_info_action(action)
            }
            SelectionInfoAction::SetMultiAnchor(_)
            | SelectionInfoAction::SetMultiProportional(_)
            | SelectionInfoAction::SetMultiOrigin(_)
            | SelectionInfoAction::SetMultiSize { .. } => {
                self.apply_multi_node_selection_info_action(action)
            }
            SelectionInfoAction::SetGuideOrigin(_)
            | SelectionInfoAction::SetGuideAngle(_)
            | SelectionInfoAction::SetGuideAlignment(_)
            | SelectionInfoAction::SetGuideLockAngle(_)
            | SelectionInfoAction::SetGuideMeasurement(_) => {
                self.apply_guide_selection_info_action(action)
            }
            other => self.apply_component_and_layer_selection_info_action(other),
        }
    }

    fn apply_single_node_selection_info_action(&mut self, action: SelectionInfoAction) -> bool {
        match action {
            SelectionInfoAction::SetOnCurvePosition(pt) => {
                if self.selected_nodes.len() != 1
                    || !pt.x.0.is_finite()
                    || !pt.y.0.is_finite()
                    || !self
                        .find_node(self.selected_nodes[0])
                        .is_some_and(|n| n.node_type != NodeType::OffCurve)
                {
                    return false;
                }
                self.set_selected_oncurve_position(pt);
                true
            }
            SelectionInfoAction::ToggleOnCurveSmooth => {
                if self.selected_nodes.is_empty() {
                    return false;
                }
                let before = self.snapshot();
                let closed_flags = self.closed_flags();
                let changed = toggle_selected_on_curve_smooth(
                    &mut self.contours,
                    &closed_flags,
                    &self.selected_nodes,
                );
                if changed {
                    self.sync_paths_from_contours();
                    self.record_mutation("Toggle Smooth", before);
                    self.assert_invariants();
                }
                changed
            }
            SelectionInfoAction::SetOffCurvePosition(pt) => {
                if self.selected_nodes.len() != 1
                    || !pt.x.0.is_finite()
                    || !pt.y.0.is_finite()
                    || !self
                        .find_node(self.selected_nodes[0])
                        .is_some_and(|n| n.node_type == NodeType::OffCurve)
                {
                    return false;
                }
                self.set_selected_offcurve_position(pt);
                true
            }
            SelectionInfoAction::SetOffCurveDelta { dx, dy } => {
                if self.selected_nodes.len() != 1
                    || !dx.is_finite()
                    || !dy.is_finite()
                    || !self
                        .find_node(self.selected_nodes[0])
                        .is_some_and(|n| n.node_type == NodeType::OffCurve)
                {
                    return false;
                }
                self.set_selected_offcurve_delta(dx, dy);
                true
            }
            SelectionInfoAction::SetHandleLength(len) => {
                if self.selected_nodes.len() != 1
                    || !len.is_finite()
                    || !self
                        .find_node(self.selected_nodes[0])
                        .is_some_and(|n| n.node_type == NodeType::OffCurve)
                {
                    return false;
                }
                self.set_selected_handle_length(len);
                true
            }
            _ => false,
        }
    }

    fn apply_multi_node_selection_info_action(&mut self, action: SelectionInfoAction) -> bool {
        match action {
            SelectionInfoAction::SetMultiAnchor(anchor) => {
                self.set_multi_selection_anchor(anchor);
                true
            }
            SelectionInfoAction::SetMultiProportional(prop) => {
                self.set_multi_selection_proportional(prop);
                true
            }
            SelectionInfoAction::SetMultiOrigin(origin) => {
                if self.selected_nodes.len() < 2
                    || !origin.x.0.is_finite()
                    || !origin.y.0.is_finite()
                {
                    return false;
                }
                self.set_multi_selection_origin(origin);
                true
            }
            SelectionInfoAction::SetMultiSize { width, height } => {
                if self.selected_nodes.len() < 2
                    || (width.is_none() && height.is_none())
                    || width.is_some_and(|w| !w.is_finite())
                    || height.is_some_and(|h| !h.is_finite())
                {
                    return false;
                }
                self.set_multi_selection_size(width, height);
                true
            }
            _ => false,
        }
    }

    fn apply_guide_selection_info_action(&mut self, action: SelectionInfoAction) -> bool {
        match action {
            SelectionInfoAction::SetGuideOrigin(origin) => {
                if !origin.x.0.is_finite()
                    || !origin.y.0.is_finite()
                    || !self.selected_guide_matches(|g| !g.locked)
                {
                    return false;
                }
                self.set_selected_guide_origin(origin);
                true
            }
            SelectionInfoAction::SetGuideAngle(angle) => {
                if !angle.is_finite()
                    || !self.selected_guide_matches(|g| !g.locked && !g.lock_angle)
                {
                    return false;
                }
                self.set_selected_guide_angle(angle);
                true
            }
            SelectionInfoAction::SetGuideAlignment(align) => {
                if !self.selected_guide_matches(|_| true) {
                    return false;
                }
                self.set_selected_guide_alignment(align);
                true
            }
            SelectionInfoAction::SetGuideLockAngle(lock) => {
                if !self.selected_guide_matches(|_| true) {
                    return false;
                }
                self.set_selected_guide_lock_angle(lock);
                true
            }
            SelectionInfoAction::SetGuideMeasurement(show) => {
                if !self.selected_guide_matches(|_| true) {
                    return false;
                }
                self.set_selected_guide_measurement(show);
                true
            }
            _ => false,
        }
    }

    /// Projects every selected `OnCurve` node (and translates its adjacent `OffCurve` handles)
    /// onto the nearest point on `self.background_contours` (`Line` and `Cubic` segments).
    pub fn align_selection_to_background(&mut self) -> usize {
        if self.selected_nodes.is_empty() || self.background_contours.is_empty() {
            return 0;
        }
        let selected_oncurve_ids: Vec<NodeId> = self
            .selected_nodes
            .iter()
            .copied()
            .filter(|&id| {
                self.find_node(id)
                    .is_some_and(|n| n.node_type != NodeType::OffCurve)
            })
            .collect();
        if selected_oncurve_ids.is_empty() {
            return 0;
        }

        let before = self.snapshot();
        let closed_flags = self.closed_flags();
        let aligned_count = align_oncurve_nodes_to_background(
            &mut self.contours,
            &closed_flags,
            &selected_oncurve_ids,
            &self.background_contours,
        );
        if aligned_count > 0 {
            self.sync_paths_from_contours();
            self.record_mutation("Align Selection to Background", before);
            self.assert_invariants();
        }
        aligned_count
    }

    /// Hit-tests the 9 dots of the 3x3 Transform-Grid inside the bottom Grey Info Box HUD.
    #[must_use]
    pub fn hit_test_hud_transform_grid_anchor(
        &self,
        scr_pt: ScreenPoint,
        canvas_rect: egui::Rect,
    ) -> Option<TransformGridAnchor> {
        if !should_render_selection_info_hud(self)
            || !matches!(self.selection_info(), SelectionInfo::MultiNode(_))
        {
            return None;
        }
        let hud_rect = compute_hud_rect(canvas_rect);
        let dots = compute_hud_transform_grid_dot_positions(hud_rect);
        dots.into_iter()
            .find(|(_, pt)| scr_pt.distance_to(*pt) <= HUD_GRID_DOT_HIT_RADIUS_DP)
            .map(|(anchor, _)| anchor)
    }

    /// Hit-tests the proportional scale icon inside the bottom Grey Info Box HUD.
    #[must_use]
    pub fn hit_test_hud_proportional_toggle(
        &self,
        scr_pt: ScreenPoint,
        canvas_rect: egui::Rect,
    ) -> bool {
        if !should_render_selection_info_hud(self)
            || !matches!(self.selection_info(), SelectionInfo::MultiNode(_))
        {
            return false;
        }
        let hud_rect = compute_hud_rect(canvas_rect);
        let prop_rect = compute_hud_proportional_icon_rect(hud_rect);
        prop_rect.contains(egui::Pos2::new(scr_pt.x.0, scr_pt.y.0))
    }

    /// Handles primary pointer press on the interactive 3x3 Transform-Grid and proportional icon in the HUD.
    pub fn handle_hud_pointer_press(
        &mut self,
        scr_pt: ScreenPoint,
        canvas_rect: egui::Rect,
    ) -> bool {
        if let Some(anchor) = self.hit_test_hud_transform_grid_anchor(scr_pt, canvas_rect) {
            return self.apply_selection_info_action(SelectionInfoAction::SetMultiAnchor(anchor));
        }
        if self.hit_test_hud_proportional_toggle(scr_pt, canvas_rect) {
            let next_prop = !self.multi_selection_proportional;
            return self
                .apply_selection_info_action(SelectionInfoAction::SetMultiProportional(next_prop));
        }
        false
    }

    /// Adds a local guide at `origin` with `angle_deg`, selects it, and records an Undo snapshot.
    pub fn add_local_guide(&mut self, origin: FontPoint, angle_deg: f64) -> GuideId {
        let before = self.snapshot();
        let id = GuideId(self.drag_transients.next_guide_id);
        self.drag_transients.next_guide_id += 1;
        self.guides.push(Guide::new(id, origin, angle_deg, false));
        self.show_guides = true;
        self.selected_nodes.clear();
        self.selected_guide = Some(SelectedGuideRef {
            id,
            is_global: false,
        });
        self.record_mutation("Add Guide", before);
        self.assert_invariants();
        id
    }

    fn selected_guide_matches(&self, pred: impl Fn(&Guide) -> bool) -> bool {
        let Some(gref) = self.selected_guide else {
            return false;
        };
        let list = if gref.is_global {
            &self.global_guides
        } else {
            &self.guides
        };
        list.iter().any(|g| g.id == gref.id && pred(g))
    }

    fn mutate_selected_guide(&mut self, label: &'static str, op: impl FnOnce(&mut Guide)) {
        let Some(gref) = self.selected_guide else {
            return;
        };
        let before = self.snapshot();
        let list = if gref.is_global {
            &mut self.global_guides
        } else {
            &mut self.guides
        };
        if let Some(g) = list.iter_mut().find(|g| g.id == gref.id) {
            op(g);
        }
        self.record_mutation(label, before);
        self.assert_invariants();
    }
    /// Selects a local guide by `id` (clearing `selected_nodes` so `SelectionInfo::Guide` is active).
    pub fn select_local_guide(&mut self, id: GuideId) {
        if self.guides.iter().any(|g| g.id == id) {
            self.selected_nodes.clear();
            self.selected_guide = Some(SelectedGuideRef {
                id,
                is_global: false,
            });
        }
        self.assert_invariants();
    }

    /// Sets the `GuideAlignment` (`Lsb`, `Center`, `Rsb`) of the selected guide and aligns its X position.
    pub fn set_selected_guide_alignment(&mut self, alignment: GuideAlignment) {
        let target_x = match alignment {
            GuideAlignment::Lsb => 0.0,
            GuideAlignment::Center => self.glyph.width * 0.5,
            GuideAlignment::Rsb => self.glyph.width,
        };
        self.mutate_selected_guide("Set Guide Alignment", |g| {
            g.alignment = alignment;
            if !g.locked {
                g.position.x.0 = target_x;
            }
        });
    }

    /// Sets the origin (`FontPoint`) of the currently selected guide.
    pub fn set_selected_guide_origin(&mut self, new_origin: FontPoint) {
        if !new_origin.x.0.is_finite() || !new_origin.y.0.is_finite() {
            return;
        }
        self.mutate_selected_guide("Move Guide", |g| {
            if !g.locked {
                g.position = new_origin;
            }
        });
    }

    /// Sets the angle in degrees of the currently selected guide (if not angle-locked).
    pub fn set_selected_guide_angle(&mut self, new_angle_deg: f64) {
        self.mutate_selected_guide("Rotate Guide", |g| {
            let _ = g.set_angle(new_angle_deg);
        });
    }

    /// Sets the `lock_angle` flag on the currently selected guide.
    pub fn set_selected_guide_lock_angle(&mut self, lock: bool) {
        self.mutate_selected_guide("Lock Guide Angle", |g| {
            g.lock_angle = lock;
        });
    }

    /// Sets the `show_measurement` flag on the currently selected guide.
    pub fn set_selected_guide_measurement(&mut self, show: bool) {
        self.mutate_selected_guide("Toggle Guide Measurement", |g| {
            g.show_measurement = show;
        });
    }
}