gpuikit 0.8.0

A UI toolkit for GPUI applications
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
//! A text run that participates in document-wide selection.
//!
//! Wraps [`StyledText`], modeled on gpui's `InteractiveText`, and adds the
//! two behaviours markdown needs from every run:
//!
//! - **Selection**: mouse down anchors a drag; while dragging, the anchor
//!   run's element registers window-wide move/up handlers and hit-tests the
//!   pointer against the *whole document's* registered runs (via the shared
//!   [`MarkdownSelection`]), so a drag flows across paragraphs, headings and
//!   code blocks. Double-click selects a word, triple-click the run.
//! - **Link clicks**: clickable ranges still open on click — but only when
//!   the mouse didn't move between down and up. A drag that starts on a link
//!   selects; a click on one follows it.
//!
//! Rendering the selection is not this element's job: the renderer injects
//! the selected range as one more background highlight before construction,
//! so painting stays plain `StyledText`.
//!
//! Every run also carries a [`RunRole`], which is how it announces itself to
//! assistive technology. A run is only reported at all when its whole
//! [`GlobalElementId`] is unique in the frame — see [`crate::markdown`] for
//! how the document scopes its runs' ids.

use std::mem;
use std::ops::Range;
use std::rc::Rc;

use gpui::{
    accesskit, App, Bounds, CursorStyle, DispatchPhase, Element, ElementId, GlobalElementId,
    Hitbox, HitboxBehavior, IntoElement, LayoutId, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
    Pixels, Role, SharedString, StyledText, TextLayout, Window,
};

use super::selection::{word_range_at, MarkdownSelection, SelectionPosition};

/// One run's layout and text, registered into the document's selection state
/// for the current frame.
pub(crate) struct RegisteredRun {
    pub layout: TextLayout,
    pub text: SharedString,
}

impl RegisteredRun {
    /// A registry entry with no layout behind it — selection-state tests
    /// exercise text assembly, which never touches the layout.
    #[cfg(test)]
    pub(crate) fn for_test(text: &str) -> Self {
        Self {
            layout: TextLayout::default(),
            text: SharedString::from(text.to_string()),
        }
    }
}

type ClickListener = Rc<dyn Fn(usize, &mut Window, &mut App)>;

/// What kind of block a run is, and therefore how a screen reader announces
/// it. Every run has one: a run that has not decided how it is announced
/// cannot be built.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RunRole {
    /// Body text.
    Paragraph,
    /// A heading at the given level, 1 through 6.
    Heading(u8),
    /// A block quote.
    Quote,
    /// One item of an ordered or unordered list.
    ListItem,
    /// A fenced or indented code block.
    Code,
}

impl RunRole {
    /// The accesskit role this run is reported under.
    pub fn a11y_role(self) -> Role {
        match self {
            RunRole::Paragraph => Role::Paragraph,
            RunRole::Heading(_) => Role::Heading,
            RunRole::Quote => Role::Blockquote,
            RunRole::ListItem => Role::ListItem,
            RunRole::Code => Role::Code,
        }
    }
}

/// A selectable (and optionally link-bearing) text run.
pub struct SelectableText {
    element_id: ElementId,
    text: StyledText,
    /// The run's text without any styling. [`StyledText`] does not hand its
    /// text back, and the a11y node is built during prepaint — before any
    /// layout exists to read it off.
    plain_text: SharedString,
    role: RunRole,
    /// This run's index in document order — its identity in the selection.
    run: usize,
    selection: MarkdownSelection,
    clickable_ranges: Vec<Range<usize>>,
    click_listener: Option<ClickListener>,
}

impl SelectableText {
    /// Build a run. `plain_text` is the same text `text` renders, unstyled —
    /// it is what assistive technology is told the run says.
    ///
    /// `id` must be unique within the frame *including its ancestors*: two
    /// runs whose full [`GlobalElementId`] collides produce one accessibility
    /// node id, which gpui refuses (panicking in debug builds).
    pub fn new(
        id: impl Into<ElementId>,
        text: StyledText,
        plain_text: impl Into<SharedString>,
        role: RunRole,
        run: usize,
        selection: MarkdownSelection,
    ) -> Self {
        Self {
            element_id: id.into(),
            text,
            plain_text: plain_text.into(),
            role,
            run,
            selection,
            clickable_ranges: Vec::new(),
            click_listener: None,
        }
    }

    /// `listener` is called with the index of the clicked range — same
    /// contract as `InteractiveText::on_click`, except a click is only a
    /// click when the pointer didn't drag between down and up.
    pub fn on_click(
        mut self,
        ranges: Vec<Range<usize>>,
        listener: impl Fn(usize, &mut Window, &mut App) + 'static,
    ) -> Self {
        self.clickable_ranges = ranges;
        self.click_listener = Some(Rc::new(listener));
        self
    }
}

impl IntoElement for SelectableText {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl Element for SelectableText {
    type RequestLayoutState = ();
    type PrepaintState = Hitbox;

    fn id(&self) -> Option<ElementId> {
        Some(self.element_id.clone())
    }

    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
        None
    }

    fn a11y_role(&self) -> Option<Role> {
        Some(self.role.a11y_role())
    }

    fn write_a11y_info(&self, node: &mut accesskit::Node) {
        // Label, not value: accesskit only names a node from its `value` for
        // `Role::Label`. Under any of our roles, `value` would leave the node
        // nameless, and setting both risks a double announcement.
        node.set_label(self.plain_text.to_string());
        if let RunRole::Heading(level) = self.role {
            node.set_level(level as usize);
        }
    }

    fn request_layout(
        &mut self,
        _id: Option<&GlobalElementId>,
        inspector_id: Option<&gpui::InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        self.text.request_layout(None, inspector_id, window, cx)
    }

    fn prepaint(
        &mut self,
        _global_id: Option<&GlobalElementId>,
        inspector_id: Option<&gpui::InspectorElementId>,
        bounds: Bounds<Pixels>,
        state: &mut Self::RequestLayoutState,
        window: &mut Window,
        cx: &mut App,
    ) -> Hitbox {
        #[cfg(test)]
        recorder::record(self, _global_id);

        self.text
            .prepaint(None, inspector_id, bounds, state, window, cx);
        window.insert_hitbox(bounds, HitboxBehavior::Normal)
    }

    fn paint(
        &mut self,
        _global_id: Option<&GlobalElementId>,
        inspector_id: Option<&gpui::InspectorElementId>,
        bounds: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        hitbox: &mut Hitbox,
        window: &mut Window,
        cx: &mut App,
    ) {
        let text_layout = self.text.layout().clone();
        let selection = self.selection.clone();
        let run = self.run;

        // This frame's registry entry — hit-testing and copy read from it.
        selection.register_run(
            run,
            RegisteredRun {
                layout: text_layout.clone(),
                text: SharedString::from(text_layout.text()),
            },
        );

        // Cursor: ibeam over text; pointing hand over a link.
        let over_link = text_layout
            .index_for_position(window.mouse_position())
            .is_ok_and(|ix| {
                self.clickable_ranges
                    .iter()
                    .any(|range| range.contains(&ix))
            });
        window.set_cursor_style(
            if over_link {
                CursorStyle::PointingHand
            } else {
                CursorStyle::IBeam
            },
            hitbox,
        );

        // Mouse down in this run: anchor a drag (single click), select a
        // word (double), or the whole run (triple). Also the place a click
        // anywhere *outside* the document clears its selection.
        {
            let selection = selection.clone();
            let text_layout = text_layout.clone();
            let hitbox = hitbox.clone();
            window.on_mouse_event(move |event: &MouseDownEvent, phase, window, _cx| {
                if phase != DispatchPhase::Bubble {
                    return;
                }
                if hitbox.is_hovered(window) {
                    let offset = match text_layout.index_for_position(event.position) {
                        Ok(offset) => offset,
                        Err(nearest) => nearest,
                    };
                    match event.click_count {
                        1 => selection.begin_drag(SelectionPosition { run, offset }),
                        2 => {
                            if let Some(text) = selection.run_text(run) {
                                selection.select_in_run(run, word_range_at(&text, offset));
                            }
                        }
                        _ => {
                            let len = selection.run_text(run).map_or(0, |text| text.len());
                            selection.select_in_run(run, 0..len);
                        }
                    }
                    window.refresh();
                } else if run == 0
                    && !selection.is_empty()
                    && !selection.point_in_any_run(event.position)
                {
                    // Run 0 speaks for the document: a press outside every
                    // run drops the selection. (Guarded to one run so the
                    // clear doesn't run once per block.)
                    selection.clear();
                    window.refresh();
                }
            });
        }

        // While a drag that started in this run is live, this element owns
        // the document-wide move/up handlers. Deliberately not hitbox-gated:
        // the pointer outruns the run immediately, and crossing into another
        // block is the point.
        if selection.drag_anchor_run() == Some(run) {
            {
                let selection = selection.clone();
                window.on_mouse_event(move |event: &MouseMoveEvent, phase, window, _cx| {
                    if phase != DispatchPhase::Bubble || !selection.is_dragging() {
                        return;
                    }
                    if let Some(position) = selection.position_for_point(event.position) {
                        selection.update_head(position);
                        window.refresh();
                    }
                });
            }
            {
                let selection = selection.clone();
                let text_layout = text_layout.clone();
                let hitbox = hitbox.clone();
                let clickable_ranges = mem::take(&mut self.clickable_ranges);
                let click_listener = self.click_listener.clone();
                window.on_mouse_event(move |event: &MouseUpEvent, phase, window, cx| {
                    if phase != DispatchPhase::Bubble || !selection.is_dragging() {
                        return;
                    }
                    let was_click = selection.range().is_none();
                    selection.end_drag();
                    // A press-and-release with no movement on a link opens
                    // it; with movement, the selection wins and the link
                    // stays put.
                    if was_click && hitbox.is_hovered(window) {
                        if let (Some(listener), Ok(ix)) = (
                            click_listener.as_ref(),
                            text_layout.index_for_position(event.position),
                        ) {
                            if let Some(range_ix) = clickable_ranges
                                .iter()
                                .position(|range| range.contains(&ix))
                            {
                                listener(range_ix, window, cx);
                            }
                        }
                    }
                    window.refresh();
                });
            }
        }

        self.text
            .paint(None, inspector_id, bounds, &mut (), &mut (), window, cx);
    }
}

/// Reconstructs, per prepainted run, exactly what gpui reads when it builds
/// the accessibility tree: the run's [`GlobalElementId`] — which gpui hashes
/// into an `accesskit::NodeId`, and which must therefore be unique in the
/// frame — and the node the element writes into.
///
/// This exists because accessibility cannot be switched on in a test. The
/// active flag is only ever set by a platform adapter's activation callback,
/// and the test platform has none, so no test can watch gpui's duplicate-node
/// assert fire. Taking the same inputs at the same point in the frame is the
/// next best thing.
#[cfg(test)]
pub(crate) mod recorder {
    use super::*;
    use std::cell::RefCell;

    /// One run, as the accessibility walk would have seen it.
    #[derive(Clone, Debug)]
    pub(crate) struct RecordedRun {
        /// The id path gpui hashes into a node id, printed the way
        /// [`GlobalElementId`] prints itself: segments joined by `.`.
        pub id_path: String,
        /// The same path's segments, outermost first.
        pub id_segments: Vec<String>,
        pub role: Option<Role>,
        pub label: Option<String>,
        pub level: Option<usize>,
    }

    thread_local! {
        static RECORDED: RefCell<Vec<RecordedRun>> = const { RefCell::new(Vec::new()) };
    }

    pub(crate) fn record(text: &SelectableText, global_id: Option<&GlobalElementId>) {
        // No global id means no node: gpui only reports elements it can name.
        let Some(global_id) = global_id else {
            return;
        };

        let (role, label, level) = match text.a11y_role() {
            Some(role) => {
                let mut node = accesskit::Node::new(role);
                text.write_a11y_info(&mut node);
                (Some(role), node.label().map(str::to_owned), node.level())
            }
            None => (None, None, None),
        };

        RECORDED.with(|recorded| {
            recorded.borrow_mut().push(RecordedRun {
                id_path: global_id.to_string(),
                id_segments: global_id.iter().map(|id| id.to_string()).collect(),
                role,
                label,
                level,
            })
        });
    }

    /// Drop everything recorded so far. Call before drawing the frame under
    /// test, so a previous frame's runs don't leak into the assertions.
    pub(crate) fn clear() {
        RECORDED.with(|recorded| recorded.borrow_mut().clear());
    }

    /// Everything recorded since the last [`clear`], in prepaint order.
    pub(crate) fn take() -> Vec<RecordedRun> {
        RECORDED.with(|recorded| std::mem::take(&mut *recorded.borrow_mut()))
    }
}