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
415
//! Select tool (`V` / `SelectTool`) interaction handlers for `GrafiaCanvasState` (`SPEC-002 ยง3`).

pub use crate::adapters::select_drag_ops::duplicate_selected_contours_for_alt_drag;
use crate::adapters::state::GrafiaCanvasState;
use crate::core::{
    convert_line_segment_to_cubic_with_grid, hit_test_segments, ContourSegment, FontPoint, NodeId,
    NodeType, ScreenPoint,
};
use crate::interaction::{Modifiers, SelectToolState};
use crate::render::ProjectedNode;
use crate::tokens::DOUBLE_CLICK_MAX_DIST_DP;
use kurbo::Point;

pub fn handle_select_press(
    state: &mut GrafiaCanvasState,
    scr_pt: ScreenPoint,
    font_pt: FontPoint,
    mods: Modifiers,
    is_double: bool,
    is_triple: bool,
) -> bool {
    if state.try_begin_alt_select_node_press(scr_pt, font_pt, mods) {
        return true;
    }
    let (is_shift, is_alt) = (mods.shift, mods.option);
    let before = state.snapshot();
    state.drag_transients.active_drag_before_snapshot = Some(before.clone());
    state.drag_transients.pending_segment_click = None;
    state.drag_transients.alt_marquee_pending_start = None;
    state.drag_transients.alt_duplicate_pending = false;

    if is_triple {
        state.selected_nodes = state.contours.iter().flatten().map(|n| n.id).collect();
        state.select_state = SelectToolState::Idle;
        state.drag_transients.active_drag_before_snapshot = None;
        return true;
    }

    if is_double && handle_select_double_click(state, scr_pt, font_pt, is_shift) {
        return true;
    }

    if let Some(node_id) = state.hit_test_node(scr_pt) {
        if is_shift {
            if state.selected_nodes.contains(&node_id) {
                state.selected_nodes.retain(|&id| id != node_id);
            } else {
                state.selected_nodes.push(node_id);
            }
        } else if !state.selected_nodes.contains(&node_id) {
            state.selected_nodes = vec![node_id];
        }
        state.record_drag_start();
        state.drag_transients.alt_duplicate_pending =
            is_alt && !mods.control && state.selected_nodes.len() >= 2;
        state.select_state = SelectToolState::DraggingNodes {
            selected: state.selected_nodes.clone(),
            start_pt: font_pt,
            current_pt: font_pt,
            modifiers: mods,
        };
        return true;
    }

    if handle_select_segment_hit(state, scr_pt, font_pt, mods, before) {
        return true;
    }

    if state.try_select_anchor_or_component_on_press(font_pt, is_shift) {
        return true;
    }

    if state.try_click_select_postscript_hint(scr_pt)
        || state.try_click_select_truetype_instruction(scr_pt)
    {
        state.select_state = SelectToolState::Idle;
        state.drag_transients.active_drag_before_snapshot = None;
        return true;
    }

    state.drag_transients.marquee_pre_selection = if is_shift {
        state.selected_nodes.clone()
    } else {
        Vec::new()
    };
    state.drag_transients.marquee_modifiers = mods;
    if !is_shift {
        state.selected_nodes.clear();
        state.clear_anchor_and_component_selections();
    }
    state.drag_transients.active_drag_before_snapshot = None;
    if is_alt {
        state.drag_transients.alt_marquee_pending_start = Some(scr_pt);
        state.select_state = SelectToolState::Idle;
    } else {
        state.select_state = SelectToolState::MarqueeSelecting {
            start_screen: scr_pt,
            current_screen: scr_pt,
        };
    }
    true
}

fn handle_select_double_click(
    state: &mut GrafiaCanvasState,
    scr_pt: ScreenPoint,
    font_pt: FontPoint,
    is_shift: bool,
) -> bool {
    let hit_node = state.hit_test_node(scr_pt);
    if let Some(node_id) = hit_node {
        if state
            .find_node(node_id)
            .is_some_and(|n| n.node_type != NodeType::OffCurve)
        {
            state.toggle_node_smooth_corner(node_id);
            state.drag_transients.active_drag_before_snapshot = None;
            return true;
        }
    }
    let tol_font = (DOUBLE_CLICK_MAX_DIST_DP as f64) / (state.viewport.zoom as f64);
    let closed_flags = state.closed_flags();
    let target_contour = hit_node
        .and_then(|nid| {
            state
                .contours
                .iter()
                .position(|c| c.iter().any(|n| n.id == nid))
        })
        .or_else(|| {
            hit_test_segments(&state.contours, &closed_flags, font_pt, tol_font)
                .map(|h| h.contour_idx)
        });
    if let Some(c_idx) = target_contour {
        let contour_ids: Vec<NodeId> = state.contours[c_idx].iter().map(|n| n.id).collect();
        if is_shift {
            if contour_ids
                .iter()
                .all(|id| state.selected_nodes.contains(id))
            {
                state.selected_nodes.retain(|id| !contour_ids.contains(id));
            } else {
                for id in contour_ids {
                    if !state.selected_nodes.contains(&id) {
                        state.selected_nodes.push(id);
                    }
                }
            }
        } else {
            state.selected_nodes = contour_ids;
        }
        state.select_state = SelectToolState::Idle;
        state.drag_transients.active_drag_before_snapshot = None;
        return true;
    }
    if state.double_click_component_at_upm(font_pt) {
        (
            state.select_state,
            state.drag_transients.active_drag_before_snapshot,
        ) = (SelectToolState::Idle, None);
        return true;
    }
    false
}

fn handle_select_segment_hit(
    state: &mut GrafiaCanvasState,
    scr_pt: ScreenPoint,
    font_pt: FontPoint,
    mods: Modifiers,
    before: crate::interaction::GlyphSnapshot,
) -> bool {
    let (is_shift, is_alt) = (mods.shift, mods.option);
    let tol_font =
        f64::from(state.effective_segment_hit_tolerance_dp()) / f64::from(state.viewport.zoom);
    let closed_flags = state.closed_flags();
    let grid_step = state.effective_grid_step();
    let Some(hit) = hit_test_segments(&state.contours, &closed_flags, font_pt, tol_font) else {
        return false;
    };
    if is_alt
        && convert_line_segment_to_cubic_with_grid(
            &mut state.contours[hit.contour_idx],
            &hit.segment,
            &mut state.next_node_id,
            grid_step,
        )
        .is_some()
    {
        state.sync_paths_from_contours();
        state.record_mutation("Convert Line to Cubic", before);
        state.drag_transients.active_drag_before_snapshot = None;
        state.assert_invariants();
        return true;
    }

    let (start_idx, end_idx) = match hit.segment {
        ContourSegment::Line {
            start_idx, end_idx, ..
        }
        | ContourSegment::Cubic {
            start_idx, end_idx, ..
        } => (start_idx, end_idx),
    };
    let c_nodes = &state.contours[hit.contour_idx];
    if state.selected_nodes.contains(&c_nodes[start_idx].id)
        && state.selected_nodes.contains(&c_nodes[end_idx].id)
    {
        if is_shift {
            state.drag_transients.marquee_pre_selection = state.selected_nodes.clone();
            state.drag_transients.pending_segment_click =
                Some((hit.contour_idx, hit.segment, mods));
        }
        state.record_drag_start();
        state.drag_transients.alt_duplicate_pending =
            is_alt && !mods.control && state.selected_nodes.len() >= 2;
        state.select_state = SelectToolState::DraggingNodes {
            selected: state.selected_nodes.clone(),
            start_pt: font_pt,
            current_pt: font_pt,
            modifiers: mods,
        };
        return true;
    }
    state.drag_transients.marquee_pre_selection = state.selected_nodes.clone();
    state.drag_transients.marquee_modifiers = mods;
    if !is_shift {
        state.selected_nodes.clear();
    }
    state.drag_transients.pending_segment_click = Some((hit.contour_idx, hit.segment, mods));
    start_segment_or_line_marquee_drag(state, hit, scr_pt, font_pt);
    true
}

fn start_segment_or_line_marquee_drag(
    state: &mut GrafiaCanvasState,
    hit: crate::core::SegmentHit,
    scr_pt: ScreenPoint,
    font_pt: FontPoint,
) {
    match hit.segment {
        ContourSegment::Line { .. } => {
            state.drag_transients.active_drag_before_snapshot = None;
            state.select_state = SelectToolState::MarqueeSelecting {
                start_screen: scr_pt,
                current_screen: scr_pt,
            };
        }
        ContourSegment::Cubic { h1_idx, h2_idx, .. } => {
            let initial_h1 = state.contours[hit.contour_idx][h1_idx].point;
            let initial_h2 = state.contours[hit.contour_idx][h2_idx].point;
            state.record_drag_start();
            state.select_state = SelectToolState::DraggingSegment {
                contour_idx: hit.contour_idx,
                segment: hit.segment,
                t: hit.t,
                start_pt: font_pt,
                initial_h1,
                initial_h2,
            };
        }
    }
}

pub fn apply_marquee_selection(state: &mut GrafiaCanvasState, is_alt_now: bool) {
    let only_on_curve = state.drag_transients.marquee_modifiers.option || is_alt_now;
    let xor_toggle = state.drag_transients.marquee_modifiers.shift;
    let ctrl_slant = state.drag_transients.marquee_modifiers.control
        && !state.drag_transients.marquee_modifiers.command;
    if update_slanted_marquee_selection(state, ctrl_slant, only_on_curve, xor_toggle) {
        return;
    }
    let Some(rect) = state.select_state.marquee_rect() else {
        return;
    };
    let mut hits: Vec<NodeId> = Vec::new();
    for contour in &state.contours {
        for node in contour {
            if only_on_curve && node.node_type == NodeType::OffCurve {
                continue;
            }
            let proj = ProjectedNode::new(
                node.point,
                node.node_type,
                false,
                &state.viewport,
                &state.theme.edit_canvas,
            );
            let center = Point::new(proj.screen_pos.x.0 as f64, proj.screen_pos.y.0 as f64);
            let inter = rect.intersect(proj.bounds);
            if (rect.contains(center) || (inter.width() > 0.0 && inter.height() > 0.0))
                && !hits.contains(&node.id)
            {
                hits.push(node.id);
            }
        }
    }
    if xor_toggle {
        let mut next_sel: Vec<NodeId> = state
            .drag_transients
            .marquee_pre_selection
            .iter()
            .copied()
            .filter(|id| !hits.contains(id))
            .collect();
        for id in hits {
            if !state.drag_transients.marquee_pre_selection.contains(&id) {
                next_sel.push(id);
            }
        }
        state.selected_nodes = next_sel;
    } else {
        state.selected_nodes = hits;
    }
    state.sync_companion_marquee_selection(rect);
}

fn update_slanted_marquee_selection(
    state: &mut GrafiaCanvasState,
    ctrl_slant: bool,
    only_on_curve: bool,
    xor_toggle: bool,
) -> bool {
    let SelectToolState::MarqueeSelecting {
        start_screen,
        current_screen,
    } = state.select_state
    else {
        return false;
    };
    if ctrl_slant {
        state.show_bounding_box_slanted = true;
        let (p0, p1) = (
            state.viewport.to_font(start_screen),
            state.viewport.to_font(current_screen),
        );
        let mut deg = (p1.x.0 - p0.x.0)
            .atan2((p1.y.0 - p0.y.0).abs().max(1.0))
            .to_degrees()
            .clamp(
                -crate::tokens::MARQUEE_MAX_SLANT_DEG,
                crate::tokens::MARQUEE_MAX_SLANT_DEG,
            );
        if (deg - state.italic_angle_deg).abs() < crate::tokens::MARQUEE_ITALIC_SNAP_TOL_DEG {
            deg = state.italic_angle_deg;
        } else if state.drag_transients.marquee_modifiers.shift {
            deg = deg.round();
        }
        state.selection_angle_deg = deg;
    } else if only_on_curve && state.italic_angle_deg.abs() > 0.0 {
        state.selection_angle_deg = state.italic_angle_deg;
        state.show_bounding_box_slanted = true;
    } else {
        state.selection_angle_deg = 0.0;
        state.show_bounding_box_slanted = false;
    }
    if (ctrl_slant || only_on_curve) && state.selection_angle_deg.abs() > 0.0 {
        state.selected_nodes = crate::core::select_nodes_in_slanted_marquee(
            &state.contours,
            &state.viewport,
            start_screen,
            current_screen,
            state.selection_angle_deg,
            &state.drag_transients.marquee_pre_selection,
            (xor_toggle, only_on_curve),
        );
        return true;
    }
    false
}

pub fn apply_segment_click_selection(
    state: &mut GrafiaCanvasState,
    c_idx: usize,
    seg: ContourSegment,
    mods: Modifiers,
) {
    let Some(contour) = state.contours.get(c_idx) else {
        return;
    };
    let target_ids: Vec<NodeId> = match seg {
        ContourSegment::Line {
            start_idx, end_idx, ..
        } => vec![contour[start_idx].id, contour[end_idx].id],
        ContourSegment::Cubic {
            start_idx,
            h1_idx,
            h2_idx,
            end_idx,
            ..
        } => {
            vec![
                contour[start_idx].id,
                contour[h1_idx].id,
                contour[h2_idx].id,
                contour[end_idx].id,
            ]
        }
    };
    if mods.shift {
        let mut sel = state.drag_transients.marquee_pre_selection.clone();
        if target_ids.iter().all(|id| sel.contains(id)) {
            sel.retain(|id| !target_ids.contains(id));
        } else {
            for id in target_ids {
                if !sel.contains(&id) {
                    sel.push(id);
                }
            }
        }
        state.selected_nodes = sel;
    } else {
        state.selected_nodes = target_ids;
    }
}