quickgui 0.1.1

A damage-driven, GPU-accelerated desktop GUI foundation
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
use super::*;

impl UiTree {
    pub fn focused_text_input(&self) -> Option<ElementId> {
        self.focused
            .filter(|focused| self.text_inputs.contains_key(focused))
    }

    pub(crate) fn focused_text_input_is_multiline(&self) -> bool {
        self.focused_text_input()
            .and_then(|id| self.text_inputs.get(&id))
            .is_some_and(TextInputState::is_multiline)
    }

    pub(crate) fn focused_text_input_is_invalid(&self) -> bool {
        self.focused_text_input()
            .is_some_and(|id| self.invalid_ids.contains(&id))
    }

    pub(crate) fn focused_text_input_value(&self) -> Option<Arc<str>> {
        self.focused_text_input()
            .and_then(|id| self.text_inputs.get(&id))
            .map(TextInputState::committed_shared_text)
    }

    /// Find the nearest semantic form containing a control.
    pub(crate) fn form_for_control(&self, mut id: ElementId) -> Option<ElementId> {
        loop {
            if self.form_ids.contains(&id) {
                return Some(id);
            }
            id = self.parents.get(&id).copied()?;
        }
    }

    /// Return the nearest form only when this element opted into submit-button behavior.
    pub(crate) fn form_for_submitter(&self, id: ElementId) -> Option<ElementId> {
        self.form_submitter_ids
            .contains(&id)
            .then(|| self.form_for_control(id))
            .flatten()
    }

    pub(crate) fn activation_target(&self, id: ElementId) -> Option<ElementId> {
        self.activation_targets.get(&id).copied()
    }

    /// Validate one mounted form, retaining only bounded shared values and issue metadata.
    ///
    /// Invalid attempts synchronously focus the first focusable invalid control in document order
    /// and replace the one retained AccessKit live announcement. No timer or idle frame is added.
    pub(crate) fn attempt_form_submission(
        &mut self,
        form: ElementId,
        trigger: Option<ElementId>,
    ) -> Option<FormAttempt> {
        if !self.form_ids.contains(&form) {
            return None;
        }
        let root = self.root.as_ref()?;
        let form_element = find_element(root, form)?;
        let mut collection = FormCollection::default();
        for child in &form_element.children {
            collect_form_controls(
                child,
                &self.text_inputs,
                &self.focusable_ids,
                &mut collection,
            );
        }

        if collection.issues.is_empty() {
            self.validation_announcement = None;
            return Some(FormAttempt::Valid(FormSubmitEvent::new(
                form,
                trigger,
                collection.fields,
                collection.fields_truncated,
            )));
        }

        if let Some(first_focusable) = collection.first_focusable_invalid {
            self.focus(first_focusable);
        }
        let report = ValidationReport::new(
            form,
            trigger,
            collection.issues,
            collection.issues_truncated,
        );
        self.set_validation_announcement(&report);
        Some(FormAttempt::Invalid(report))
    }

    pub(super) fn set_validation_announcement(&mut self, report: &ValidationReport) {
        let message = validation_announcement_message(report);
        let node = self.next_auxiliary_accessibility_id();
        self.validation_announcement = Some(ValidationAnnouncement {
            form: report.form(),
            node,
            message,
        });
    }

    pub(super) fn next_auxiliary_accessibility_id(&mut self) -> AccessibilityNodeId {
        loop {
            let candidate = AccessibilityNodeId(self.next_accessibility_text_id);
            self.next_accessibility_text_id = self.next_accessibility_text_id.wrapping_sub(1);
            if candidate != ACCESSIBILITY_ROOT_ID
                && !self.seen_ids.contains(&ElementId::new(candidate.0))
                && !self
                    .accessibility_text_ids
                    .values()
                    .any(|existing| *existing == candidate)
                && self
                    .validation_announcement
                    .as_ref()
                    .is_none_or(|announcement| announcement.node != candidate)
            {
                return candidate;
            }
        }
    }

    pub(crate) fn selected_input_text(&self) -> Option<Arc<str>> {
        let id = self.focused_text_input()?;
        if self
            .root
            .as_ref()
            .and_then(|root| find_element(root, id))
            .is_some_and(|element| {
                matches!(
                    &element.kind,
                    ElementKind::TextInput(input) if input.password
                )
            })
        {
            return None;
        }
        self.text_inputs
            .get(&id)
            .and_then(TextInputState::selected_text)
            .map(Arc::from)
    }

    pub fn selected_text(&self) -> Option<Arc<str>> {
        self.selected_input_text()
            .or_else(|| self.selected_static_text())
    }

    pub(crate) fn has_selectable_text(&self) -> bool {
        !self.selectable_texts.is_empty()
    }

    pub(crate) fn select_all_static_text(&mut self) -> bool {
        let (Some(first), Some(last)) =
            (self.selectable_texts.first(), self.selectable_texts.last())
        else {
            return false;
        };
        let next = StaticTextSelection {
            anchor: StaticTextPosition {
                id: first.id,
                offset: 0,
            },
            focus: StaticTextPosition {
                id: last.id,
                offset: last.content.len(),
            },
        };
        let changed = self.static_text_selection != Some(next);
        self.static_text_selection = Some(next);
        self.static_text_gesture = None;
        changed
    }

    pub(crate) fn clear_static_text_selection(&mut self) -> bool {
        self.static_text_gesture = None;
        self.static_text_selection.take().is_some()
    }

    pub(super) fn selected_static_text(&self) -> Option<Arc<str>> {
        let selection = self.static_text_selection?;
        let (start, end) = normalized_static_selection(selection, &self.selectable_text_indices)?;
        if start == end {
            return None;
        }
        let mut output = String::new();
        for document_index in start.0..=end.0 {
            let entry = self.selectable_texts.get(document_index)?;
            let range = if start.0 == end.0 {
                start.1.min(entry.content.len())..end.1.min(entry.content.len())
            } else if document_index == start.0 {
                start.1.min(entry.content.len())..entry.content.len()
            } else if document_index == end.0 {
                0..end.1.min(entry.content.len())
            } else {
                0..entry.content.len()
            };
            if document_index > start.0 {
                let previous = &self.selectable_texts[document_index - 1];
                let separator = selection_separator(
                    self.element_bounds.get(&previous.id).copied(),
                    self.element_bounds.get(&entry.id).copied(),
                );
                push_bounded_text(&mut output, separator, MAX_STATIC_TEXT_COPY_BYTES);
            }
            push_bounded_text(
                &mut output,
                &entry.content[range],
                MAX_STATIC_TEXT_COPY_BYTES,
            );
            if output.len() == MAX_STATIC_TEXT_COPY_BYTES {
                break;
            }
        }
        (!output.is_empty()).then(|| Arc::from(output))
    }

    pub fn input_move_left(&mut self, extend: bool) -> InputResult {
        self.edit_focused_input(|state| state.move_left(extend))
    }

    pub fn input_move_right(&mut self, extend: bool) -> InputResult {
        self.edit_focused_input(|state| state.move_right(extend))
    }

    pub fn input_move_word_left(&mut self, extend: bool) -> InputResult {
        self.edit_focused_input(|state| state.move_word_left(extend))
    }

    pub fn input_move_word_right(&mut self, extend: bool) -> InputResult {
        self.edit_focused_input(|state| state.move_word_right(extend))
    }

    pub fn input_move_home(&mut self, extend: bool) -> InputResult {
        self.edit_focused_input(|state| state.move_home(extend))
    }

    pub fn input_move_end(&mut self, extend: bool) -> InputResult {
        self.edit_focused_input(|state| state.move_end(extend))
    }

    pub fn input_move_line_start(&mut self, extend: bool) -> InputResult {
        self.edit_focused_input(|state| state.move_line_start(extend))
    }

    pub fn input_move_line_end(&mut self, extend: bool) -> InputResult {
        self.edit_focused_input(|state| state.move_line_end(extend))
    }

    pub fn input_move_vertical(
        &mut self,
        lines: isize,
        extend: bool,
        renderer: &mut impl TextLayoutEngine,
    ) -> InputResult {
        if lines == 0 {
            return InputResult::default();
        }
        let Some(id) = self.focused_text_input() else {
            return InputResult::default();
        };
        let Some(region) = self
            .text_input_regions
            .iter()
            .rev()
            .find(|region| region.id == id)
            .cloned()
        else {
            return InputResult::default();
        };
        let Some(state) = self.text_inputs.get_mut(&id) else {
            return InputResult::default();
        };
        if !state.is_multiline() {
            return InputResult::default();
        }

        let mut repaint = false;
        let selection = state.selection();
        if !extend && !selection.is_empty() {
            let collapse = if lines < 0 {
                selection.start
            } else {
                selection.end
            };
            repaint |= state.move_to(collapse, false);
        }

        let content = state.shared_text();
        let text_id = TextId::new(id.value());
        let caret = renderer.text_caret_position_with_highlights(
            text_id,
            &content,
            &region.style,
            region.highlights.as_ref(),
            region.bounds.width,
            self.scale_factor,
            state.caret(),
        );
        let preferred_x = state.preferred_x().unwrap_or(caret.x);
        let target = Point::new(
            preferred_x,
            caret.y + lines as f32 * region.style.line_height + region.style.line_height * 0.5,
        );
        let index = renderer.text_index_for_point_with_highlights(
            text_id,
            &content,
            &region.style,
            region.highlights.as_ref(),
            region.bounds.width,
            self.scale_factor,
            target,
        );
        repaint |= state.move_to_with_preferred_x(index, extend, preferred_x);
        InputResult {
            repaint,
            change: None,
        }
    }

    pub fn input_move_page(
        &mut self,
        direction: isize,
        extend: bool,
        renderer: &mut impl TextLayoutEngine,
    ) -> InputResult {
        let Some(id) = self.focused_text_input() else {
            return InputResult::default();
        };
        let Some(region) = self
            .text_input_regions
            .iter()
            .rev()
            .find(|region| region.id == id)
        else {
            return InputResult::default();
        };
        let lines = (region.bounds.height / region.style.line_height)
            .floor()
            .max(1.0) as isize;
        self.input_move_vertical(direction.signum() * lines, extend, renderer)
    }

    pub fn input_select_all(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::select_all)
    }

    pub fn input_backspace(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::backspace)
    }

    pub fn input_delete(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::delete)
    }

    pub fn input_delete_word_backward(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::delete_word_backward)
    }

    pub fn input_delete_word_forward(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::delete_word_forward)
    }

    pub fn input_delete_to_line_start(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::delete_to_line_start)
    }

    pub fn input_delete_to_line_end(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::delete_to_line_end)
    }

    pub fn input_replace(&mut self, value: &str) -> InputResult {
        self.edit_focused_input(|state| state.replace_selection(value))
    }

    pub fn input_insert_newline(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::insert_newline)
    }

    pub fn input_can_undo(&self) -> bool {
        self.focused_text_input()
            .and_then(|id| self.text_inputs.get(&id))
            .is_some_and(TextInputState::can_undo)
    }

    pub fn input_can_redo(&self) -> bool {
        self.focused_text_input()
            .and_then(|id| self.text_inputs.get(&id))
            .is_some_and(TextInputState::can_redo)
    }

    pub fn input_undo(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::undo)
    }

    pub fn input_redo(&mut self) -> InputResult {
        self.edit_focused_input(TextInputState::redo)
    }

    pub fn input_preedit(&mut self, value: &str, cursor: Option<(usize, usize)>) -> InputResult {
        self.edit_focused_input(|state| state.set_preedit(value, cursor))
    }

    pub fn input_cancel_preedit(&mut self, id: ElementId) -> InputResult {
        self.edit_input(id, |state| state.set_preedit("", None))
    }

    pub fn input_set_value(&mut self, id: ElementId, value: &str) -> InputResult {
        self.edit_input(id, |state| state.set_value(value))
    }

    pub fn set_accessibility_text_selection(
        &mut self,
        id: ElementId,
        selection: &TextSelection,
    ) -> InputResult {
        let Some(text_id) = self.accessibility_text_ids.get(&id).copied() else {
            return InputResult::default();
        };
        if selection.anchor.node != text_id || selection.focus.node != text_id {
            return InputResult::default();
        }
        if self.text_inputs.contains_key(&id) {
            return self.edit_input(id, |state| {
                let anchor = state.accessibility_byte_index(selection.anchor.character_index);
                let caret = state.accessibility_byte_index(selection.focus.character_index);
                state.set_selection(anchor, caret)
            });
        }
        let Some(document_index) = self.selectable_text_indices.get(&id).copied() else {
            return InputResult::default();
        };
        let content = &self.selectable_texts[document_index].content;
        let next = StaticTextSelection {
            anchor: StaticTextPosition {
                id,
                offset: accessibility_byte_index(content, selection.anchor.character_index),
            },
            focus: StaticTextPosition {
                id,
                offset: accessibility_byte_index(content, selection.focus.character_index),
            },
        };
        let repaint = self.static_text_selection != Some(next);
        self.static_text_selection = Some(next);
        self.static_text_gesture = None;
        InputResult {
            repaint,
            change: None,
        }
    }

    pub fn ime_cursor_area(&self) -> Option<Rect> {
        let focused = self.focused_text_input()?;
        self.text_input_regions
            .iter()
            .rev()
            .find(|region| region.id == focused)
            .and_then(|region| region.caret_bounds.intersection(region.clip))
    }

    pub(super) fn edit_focused_input(
        &mut self,
        edit: impl FnOnce(&mut TextInputState) -> bool,
    ) -> InputResult {
        let Some(id) = self.focused_text_input() else {
            return InputResult::default();
        };
        self.edit_input(id, edit)
    }

    pub(super) fn edit_input(
        &mut self,
        id: ElementId,
        edit: impl FnOnce(&mut TextInputState) -> bool,
    ) -> InputResult {
        let Some(state) = self.text_inputs.get_mut(&id) else {
            return InputResult::default();
        };
        let previous = state.committed_shared_text();
        let repaint = edit(state);
        let committed = state.committed_shared_text();
        let change = (previous != committed).then_some(InputChange {
            id,
            value: committed,
        });
        InputResult { repaint, change }
    }
}