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
//! `SPEC-007` (`grafia v0.6.0`) 5-Mode Contextual `SelectionInfo` HUD inspection and mutators
//! (`GlyphBase`, `SingleOnCurve`, `SingleOffCurve`, `MultiNode`, `Guide`).

use crate::adapters::state::GrafiaCanvasState;
use crate::core::{
    collect_adjacent_offcurve_positions, compute_glyph_lsb_and_rsb,
    compute_radially_scaled_handle_pos, compute_selection_bounds, find_first_offcurve_node_id,
    find_first_oncurve_with_adjacent_offcurve, resolve_tethered_oncurve_for_offcurve,
    translate_oncurve_with_adjacent_handles, update_offcurve_with_smooth_constraint, FontPoint,
    GlyphBaseInfo, GuideInfo, MultiNodeInfo, NodeId, NodeType, SelectionInfo, SingleOffCurveInfo,
    SingleOnCurveInfo, SpacingDelta,
};

impl GrafiaCanvasState {
    /// Computes the current 5-mode contextual `SelectionInfo` (`SPEC-007 ยง2.2`).
    #[must_use]
    pub fn selection_info(&self) -> SelectionInfo {
        if let Some(hh_info) = self.resolve_hinting_and_hoi_selection_info() {
            return hh_info;
        }
        if self.selected_nodes.is_empty() {
            return self.empty_node_selection_info();
        }

        if self.selected_nodes.len() == 1 {
            if let Some(info) = self.single_selected_node_info(self.selected_nodes[0]) {
                return info;
            }
        }

        let total_layer_node_count = self.contours.iter().map(Vec::len).sum();
        if let Some(bounds) = compute_selection_bounds(
            &self.contours,
            &self.selected_nodes,
            0.0,
            self.metrics.x_height * 0.5,
        ) {
            let origin = bounds.aligned_point(self.transform_grid_anchor.index());
            return SelectionInfo::MultiNode(MultiNodeInfo {
                origin_anchor: self.transform_grid_anchor,
                origin_x: origin.x.0,
                origin_y: origin.y.0,
                width: bounds.width(),
                height: bounds.height(),
                proportional_scale: self.multi_selection_proportional,
                selected_node_count: self.selected_nodes.len(),
                total_layer_node_count,
            });
        }

        SelectionInfo::GlyphBase(self.build_glyph_base_info())
    }

    fn empty_node_selection_info(&self) -> SelectionInfo {
        if let Some(grad_info) = self.resolve_gradient_stop_selection_info() {
            return grad_info;
        }
        if let Some(bg) = self.background_image.as_ref().filter(|img| img.selected) {
            return SelectionInfo::BackgroundImage(crate::tokens::BackgroundImageInfo {
                x: bg.position.x.0,
                y: bg.position.y.0,
                scale_x_pct: bg.scale_x * crate::tokens::PERCENT_SCALE_FACTOR,
                scale_y_pct: bg.scale_y * crate::tokens::PERCENT_SCALE_FACTOR,
                rotation_deg: bg.rotation_deg,
                alpha: bg.alpha,
                locked: bg.locked,
                crop_rect_px: bg.crop_rect_px,
            });
        }
        if let Some(gref) = self.selected_guide {
            let g_opt = if gref.is_global {
                self.global_guides.iter().find(|g| g.id == gref.id)
            } else {
                self.guides.iter().find(|g| g.id == gref.id)
            };
            if let Some(g) = g_opt {
                return SelectionInfo::Guide(GuideInfo {
                    guide_ref: gref,
                    x: g.position.x.0,
                    y: g.position.y.0,
                    angle_deg: g.angle_deg,
                    alignment: g.alignment,
                    lock_angle: g.lock_angle,
                    show_measurement: g.show_measurement,
                });
            }
        }
        SelectionInfo::GlyphBase(self.build_glyph_base_info())
    }

    fn single_selected_node_info(&self, sel_id: NodeId) -> Option<SelectionInfo> {
        let closed_flags = self.closed_flags();
        let node = self.find_node(sel_id)?;
        if let NodeType::HobbyStar {
            tension_in,
            tension_out,
            dir_constraint,
        } = node.node_type
        {
            return Some(SelectionInfo::HobbyNode(crate::tokens::HobbyNodeInfo {
                node_id: node.id,
                x: node.point.x.0,
                y: node.point.y.0,
                tension_in,
                tension_out,
                dir_constraint,
            }));
        }
        if node.node_type != NodeType::OffCurve {
            return Some(SelectionInfo::SingleOnCurve(SingleOnCurveInfo {
                node_id: node.id,
                x: node.point.x.0,
                y: node.point.y.0,
                node_type: node.node_type,
            }));
        }
        let (off_n, on_n) =
            resolve_tethered_oncurve_for_offcurve(&self.contours, &closed_flags, sel_id)?;
        let dx = off_n.point.x.0 - on_n.point.x.0;
        let dy = off_n.point.y.0 - on_n.point.y.0;
        Some(SelectionInfo::SingleOffCurve(SingleOffCurveInfo {
            node_id: off_n.id,
            anchor_node_id: on_n.id,
            tethered_oncurve_id: on_n.id,
            x: off_n.point.x.0,
            y: off_n.point.y.0,
            delta_x: dx,
            delta_y: dy,
            length: dx.hypot(dy),
        }))
    }

    fn build_glyph_base_info(&self) -> GlyphBaseInfo {
        let (lsb, rsb) = compute_glyph_lsb_and_rsb(&self.contours, self.glyph.width);
        let mut min_x = f64::INFINITY;
        let mut min_y = f64::INFINITY;
        let mut max_x = f64::NEG_INFINITY;
        let mut max_y = f64::NEG_INFINITY;
        for c in &self.contours {
            for n in c {
                min_x = min_x.min(n.point.x.0);
                min_y = min_y.min(n.point.y.0);
                max_x = max_x.max(n.point.x.0);
                max_y = max_y.max(n.point.y.0);
            }
        }
        let (bbox_x, bbox_y, bbox_w, bbox_h) = if min_x.is_finite() && min_y.is_finite() {
            (
                min_x,
                min_y,
                (max_x - min_x).max(0.0),
                (max_y - min_y).max(0.0),
            )
        } else {
            (0.0, 0.0, 0.0, 0.0)
        };
        let i = self.text_stream.active_slot_index;
        let has_slots = !self.text_stream.slots.is_empty();
        let kern_with_prev = if has_slots && i > 0 {
            self.text_stream.slots.get(i).map(|s| s.kern_with_prev)
        } else {
            None
        };
        let kern_with_next = if has_slots {
            self.text_stream.slots.get(i + 1).map(|s| s.kern_with_prev)
        } else {
            None
        };
        GlyphBaseInfo {
            glyph_name: self.glyph.name.clone(),
            bbox_x,
            bbox_y,
            bbox_w,
            bbox_h,
            lsb,
            rsb,
            advance_width: self.glyph.width,
            active_slot_kerning_left: kern_with_prev,
            kern_with_prev,
            kern_with_next,
            transform_anchor: self.transform_grid_anchor,
            proportional_scale: self.multi_selection_proportional,
            contour_count: self.contours.len(),
            total_node_count: self.contours.iter().map(Vec::len).sum(),
        }
    }

    pub(crate) fn shift_all_glyph_elements_x(&mut self, dx: f64) {
        for contour in &mut self.contours {
            for node in contour {
                node.point.x.0 += dx;
            }
        }
        for guide in &mut self.guides {
            guide.position.x.0 += dx;
        }
        for ann in &mut self.glyph.annotations {
            ann.position.x.0 += dx;
        }
        for anchor in &mut self.anchors {
            anchor.position.x.0 += dx;
        }
    }

    /// Sets the active glyph's Left Sidebearing (`LSB`) in UPM while preserving `RSB` (`SPEC-007 ยง2.2.1`).
    pub fn set_lsb(&mut self, new_lsb: f64) {
        if !new_lsb.is_finite() {
            return;
        }
        let before = self.snapshot();
        let (cur_lsb, _) = compute_glyph_lsb_and_rsb(&self.contours, self.glyph.width);
        let dx = new_lsb - cur_lsb;
        let old_w = self.glyph.width;
        self.shift_all_glyph_elements_x(dx);
        self.glyph.width = (self.glyph.width + dx).max(0.0);
        self.sync_paths_from_contours();
        let d_lsb = dx.round() as i32;
        let d_w = (self.glyph.width - old_w).round() as i32;
        self.text_stream.pending_spacing_deltas.push(SpacingDelta {
            slot_index: self.text_stream.active_slot_index,
            glyph_name: self.glyph.name.clone(),
            axis: crate::core::MetricsAxis::Horizontal,
            lsb_delta_upm: d_lsb,
            rsb_delta_upm: 0,
            width_delta_upm: d_w,
            tsb_delta_upm: 0,
            bsb_delta_upm: 0,
            advance_height_delta_upm: 0,
        });
        self.record_mutation("Set LSB", before);
        self.assert_invariants();
    }

    /// Sets the active glyph's Right Sidebearing (`RSB`) in UPM while preserving `LSB` (`SPEC-007 ยง2.2.1`).
    pub fn set_rsb(&mut self, new_rsb: f64) {
        if !new_rsb.is_finite() {
            return;
        }
        let before = self.snapshot();
        let (_, cur_rsb) = compute_glyph_lsb_and_rsb(&self.contours, self.glyph.width);
        let dx = new_rsb - cur_rsb;
        let old_w = self.glyph.width;
        self.glyph.width = (self.glyph.width + dx).max(0.0);
        self.sync_paths_from_contours();
        let d_rsb = dx.round() as i32;
        let d_w = (self.glyph.width - old_w).round() as i32;
        self.text_stream.pending_spacing_deltas.push(SpacingDelta {
            slot_index: self.text_stream.active_slot_index,
            glyph_name: self.glyph.name.clone(),
            axis: crate::core::MetricsAxis::Horizontal,
            lsb_delta_upm: 0,
            rsb_delta_upm: d_rsb,
            width_delta_upm: d_w,
            tsb_delta_upm: 0,
            bsb_delta_upm: 0,
            advance_height_delta_upm: 0,
        });
        self.record_mutation("Set RSB", before);
        self.assert_invariants();
    }

    /// Sets the active glyph's `advance_width` in UPM (`SPEC-007 ยง2.2.1`).
    pub fn set_advance_width(&mut self, new_width: f64) {
        if !new_width.is_finite() {
            return;
        }
        let before = self.snapshot();
        let old_w = self.glyph.width;
        self.glyph.width = new_width.max(0.0);
        self.sync_paths_from_contours();
        let d_w = (self.glyph.width - old_w).round() as i32;
        self.text_stream.pending_spacing_deltas.push(SpacingDelta {
            slot_index: self.text_stream.active_slot_index,
            glyph_name: self.glyph.name.clone(),
            axis: crate::core::MetricsAxis::Horizontal,
            lsb_delta_upm: 0,
            rsb_delta_upm: d_w,
            width_delta_upm: d_w,
            tsb_delta_upm: 0,
            bsb_delta_upm: 0,
            advance_height_delta_upm: 0,
        });
        self.record_mutation("Set Advance Width", before);
        self.assert_invariants();
    }

    /// Centers all contours horizontally within the current `advance_width` so `LSB == RSB` (`SPEC-007 ยง2.2.1`).
    pub fn center_glyph_in_width(&mut self) {
        let before = self.snapshot();
        let (lsb, rsb) = compute_glyph_lsb_and_rsb(&self.contours, self.glyph.width);
        let dx = (rsb - lsb) * 0.5;
        self.shift_all_glyph_elements_x(dx);
        self.sync_paths_from_contours();
        let d_lsb = dx.round() as i32;
        self.text_stream.pending_spacing_deltas.push(SpacingDelta {
            slot_index: self.text_stream.active_slot_index,
            glyph_name: self.glyph.name.clone(),
            axis: crate::core::MetricsAxis::Horizontal,
            lsb_delta_upm: d_lsb,
            rsb_delta_upm: -d_lsb,
            width_delta_upm: 0,
            tsb_delta_upm: 0,
            bsb_delta_upm: 0,
            advance_height_delta_upm: 0,
        });
        self.record_mutation("Center in Width", before);
        self.assert_invariants();
    }

    /// Returns the first `OnCurve` node that has at least one adjacent `OffCurve` handle.
    #[must_use]
    pub fn first_oncurve_with_adjacent_offcurve(&self) -> Option<NodeId> {
        find_first_oncurve_with_adjacent_offcurve(&self.contours, &self.closed_flags())
    }

    /// Returns the positions of all `OffCurve` handles directly adjacent to `oncurve_id`.
    #[must_use]
    pub fn adjacent_offcurve_positions(&self, oncurve_id: NodeId) -> Vec<FontPoint> {
        collect_adjacent_offcurve_positions(&self.contours, &self.closed_flags(), oncurve_id)
    }

    /// Selects exclusively `node_id` (clearing any guide selection).
    pub fn select_only_node(&mut self, node_id: NodeId) {
        self.selected_guide = None;
        if self.find_node(node_id).is_some() {
            self.selected_nodes = vec![node_id];
        } else {
            self.selected_nodes.clear();
        }
        self.assert_invariants();
    }

    /// Moves the single selected `OnCurve` node to `new_pos`, translating its adjacent `OffCurve` handles by the same delta.
    pub fn set_selected_oncurve_position(&mut self, new_pos: FontPoint) {
        if self.selected_nodes.len() != 1 || !new_pos.x.0.is_finite() || !new_pos.y.0.is_finite() {
            return;
        }
        let sel_id = self.selected_nodes[0];
        let before = self.snapshot();
        let closed_flags = self.closed_flags();
        if translate_oncurve_with_adjacent_handles(
            &mut self.contours,
            &closed_flags,
            sel_id,
            new_pos,
        ) {
            self.sync_paths_from_contours();
            self.record_mutation("Move On-Curve Node", before);
            self.assert_invariants();
        }
    }

    /// Returns the first `OffCurve` handle `NodeId` in the active layer.
    #[must_use]
    pub fn first_offcurve_node_id(&self) -> Option<NodeId> {
        find_first_offcurve_node_id(&self.contours)
    }

    /// Moves the single selected `OffCurve` handle to absolute `new_pos`, preserving smooth collinearity.
    pub fn set_selected_offcurve_position(&mut self, new_pos: FontPoint) {
        if self.selected_nodes.len() != 1 || !new_pos.x.0.is_finite() || !new_pos.y.0.is_finite() {
            return;
        }
        let sel_id = self.selected_nodes[0];
        let before = self.snapshot();
        let closed_flags = self.closed_flags();
        if update_offcurve_with_smooth_constraint(
            &mut self.contours,
            &closed_flags,
            sel_id,
            new_pos,
        ) {
            self.sync_paths_from_contours();
            self.record_mutation("Move Off-Curve Handle", before);
            self.assert_invariants();
        }
    }

    /// Sets the relative `(dx, dy)` offset of the selected `OffCurve` handle from its tethered `OnCurve` anchor.
    pub fn set_selected_offcurve_delta(&mut self, dx: f64, dy: f64) {
        if self.selected_nodes.len() != 1 || !dx.is_finite() || !dy.is_finite() {
            return;
        }
        let sel_id = self.selected_nodes[0];
        let closed_flags = self.closed_flags();
        let Some((_, on_n)) =
            resolve_tethered_oncurve_for_offcurve(&self.contours, &closed_flags, sel_id)
        else {
            return;
        };
        self.set_selected_offcurve_position(FontPoint::new(
            on_n.point.x.0 + dx,
            on_n.point.y.0 + dy,
        ));
    }

    /// Radially scales the selected `OffCurve` handle to `new_length` along its current angle from its tethered `OnCurve` anchor.
    pub fn set_selected_handle_length(&mut self, new_length: f64) {
        if self.selected_nodes.len() != 1 || !new_length.is_finite() {
            return;
        }
        let sel_id = self.selected_nodes[0];
        let closed_flags = self.closed_flags();
        let Some((off_n, on_n)) =
            resolve_tethered_oncurve_for_offcurve(&self.contours, &closed_flags, sel_id)
        else {
            return;
        };
        let new_pos = compute_radially_scaled_handle_pos(on_n.point, off_n.point, new_length);
        self.set_selected_offcurve_position(new_pos);
    }
}