gpui-base 0.6.4

Behavior, interaction, and infrastructure foundations 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
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
//! Fades streamed text in: the rendered characters an update adds start
//! transparent and reach full color over [`TextViewMotion::stream_fade`],
//! as one chunk, or word by word (character by character for CJK) when
//! [`TextViewMotion::stream_fade_stagger`] separates them.
//!
//! The tracker compares rendered text, not source, so `**bo` completing into
//! bold `bold` fades the changed glyphs rather than mapping source bytes.

#[cfg(not(target_family = "wasm"))]
use std::time::Instant;
use std::{ops::Range, sync::Arc, time::Duration};
#[cfg(target_family = "wasm")]
use web_time::Instant;

use gpui::{ElementId, SharedString};

use super::{
    document::ParsedDocument,
    node::{BlockNode, InlineNode, Paragraph},
};
use crate::motion::{Easing, Timing};

/// Motion policy of a text view. Base plays it; every duration defaults to
/// zero, so an unstyled view adopts new content at once.
#[derive(Clone, Debug)]
pub struct TextViewMotion {
    stream_fade: Duration,
    stream_fade_stagger: Duration,
    stream_fade_easing: Easing,
}

impl Default for TextViewMotion {
    fn default() -> Self {
        Self {
            stream_fade: Duration::ZERO,
            stream_fade_stagger: Duration::ZERO,
            stream_fade_easing: Easing::default(),
        }
    }
}

impl TextViewMotion {
    /// How long the text an update appends takes to reach full color.
    pub fn with_stream_fade(mut self, duration: Duration) -> Self {
        self.stream_fade = duration;
        self
    }

    /// How much later each further word of one update starts fading than
    /// the word before it; zero fades the update as one chunk. A long update
    /// is compressed so its last word starts within one [`Self::stream_fade`].
    pub fn with_stream_fade_stagger(mut self, stagger: Duration) -> Self {
        self.stream_fade_stagger = stagger;
        self
    }

    /// The curve the appended text fades in along.
    pub fn with_stream_fade_easing(mut self, easing: Easing) -> Self {
        self.stream_fade_easing = easing;
        self
    }

    pub fn stream_fade(&self) -> Duration {
        self.stream_fade
    }

    pub fn stream_fade_stagger(&self) -> Duration {
        self.stream_fade_stagger
    }

    pub fn stream_fade_easing(&self) -> &Easing {
        &self.stream_fade_easing
    }

    /// The start offset between consecutive words of an update `words` long.
    fn stagger_step(&self, words: usize) -> Duration {
        if words < 2 {
            return Duration::ZERO;
        }
        self.stream_fade_stagger
            .min(self.stream_fade / words as u32)
    }
}

/// Identifies one run of rendered text across re-parses: the source start of
/// the block that owns it, plus the cell ordinal inside a table.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct TextLeafKey {
    block_start: usize,
    ordinal: usize,
}

/// The key as an element id, for a leaf that needs element state or an
/// accessibility identity: unique per leaf, and allocation-free, as it is
/// built every frame.
impl From<TextLeafKey> for ElementId {
    fn from(key: TextLeafKey) -> Self {
        let mut bytes = [0; 20];
        bytes[..8].copy_from_slice(&(key.block_start as u64).to_le_bytes());
        bytes[8..16].copy_from_slice(&(key.ordinal as u64).to_le_bytes());
        ElementId::OpaqueId(bytes)
    }
}

impl TextLeafKey {
    pub(crate) fn block(start: usize) -> Self {
        Self {
            block_start: start,
            ordinal: 0,
        }
    }

    pub(crate) fn table_cell(table_start: usize, ordinal: usize) -> Self {
        Self {
            block_start: table_start,
            ordinal: ordinal + 1,
        }
    }
}

/// Rendered byte ranges with the [`gpui::HighlightStyle::fade_out`] factor
/// each one paints with this frame: `1.0` transparent, `0.0` opaque.
pub(crate) type FadeRanges = Vec<(Range<usize>, f32)>;

/// One frame's fade factors, resolved once per render so node rendering only
/// looks up its leaf.
#[derive(Debug, Default)]
pub(crate) struct StreamFadeFrame {
    leaves: Vec<(TextLeafKey, FadeRanges)>,
}

impl StreamFadeFrame {
    pub(crate) fn fades(&self, key: TextLeafKey) -> Option<&[(Range<usize>, f32)]> {
        self.leaves
            .iter()
            .find(|(leaf, _)| *leaf == key)
            .map(|(_, fades)| fades.as_slice())
    }
}

struct FadeSegment {
    range: Range<usize>,
    started_at: Instant,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum PendingUpdate {
    #[default]
    None,
    /// Every update since the last parse extended the text, which was
    /// `origin` bytes long before the first of them.
    Extend {
        origin: usize,
    },
    Replace,
}

/// Tracks which rendered text arrived recently and samples its fade.
#[derive(Default)]
pub(super) struct StreamFadeTracker {
    motion: TextViewMotion,
    pending: PendingUpdate,
    segments: Vec<(TextLeafKey, Vec<FadeSegment>)>,
}

impl StreamFadeTracker {
    pub(super) fn set_motion(&mut self, motion: TextViewMotion) {
        if motion.stream_fade.is_zero() {
            self.segments.clear();
            self.pending = PendingUpdate::None;
        }
        self.motion = motion;
    }

    pub(super) fn is_enabled(&self) -> bool {
        !self.motion.stream_fade.is_zero()
    }

    /// The next update extends the current text, which is `len` bytes long.
    pub(super) fn note_extend(&mut self, len: usize) {
        if !self.is_enabled() {
            return;
        }
        self.pending = match self.pending {
            PendingUpdate::None => PendingUpdate::Extend { origin: len },
            PendingUpdate::Extend { origin } => PendingUpdate::Extend {
                origin: origin.min(len),
            },
            PendingUpdate::Replace => PendingUpdate::Replace,
        };
    }

    /// The next update replaces the current text.
    pub(super) fn note_replace(&mut self) {
        if self.is_enabled() {
            self.pending = PendingUpdate::Replace;
        }
    }

    /// Forgets the noted update after its parse failed.
    pub(super) fn discard_pending(&mut self) {
        self.pending = PendingUpdate::None;
    }

    /// Records what `new` renders that `old` did not, for the updates noted
    /// since the last call, as segments that start fading at `now`.
    ///
    /// Only blocks the extension reaches are compared, walking both documents
    /// from the tail, so a chunk landing at the end of a long document costs
    /// one paragraph, not the document.
    pub(super) fn record(&mut self, old: &ParsedDocument, new: &ParsedDocument, now: Instant) {
        let pending = std::mem::take(&mut self.pending);
        if !self.is_enabled() {
            self.segments.clear();
            return;
        }
        let origin = match pending {
            PendingUpdate::None => return,
            PendingUpdate::Replace => {
                self.segments.clear();
                return;
            }
            PendingUpdate::Extend { origin } => origin,
        };

        let mut affected = Vec::new();
        for block in new.blocks.iter().rev() {
            if block.span().is_some_and(|span| span.end <= origin) {
                break;
            }
            text_leaves(block, &mut affected);
        }
        let Some(first_start) = affected.iter().map(|(key, _)| key.block_start).min() else {
            return;
        };

        let mut previous = Vec::new();
        for block in old.blocks.iter().rev() {
            if block.span().is_some_and(|span| span.end < first_start) {
                break;
            }
            text_leaves(block, &mut previous);
        }

        for (key, leaf) in affected {
            let len = leaf.len();
            let prefix = previous
                .iter()
                .find(|(previous_key, _)| *previous_key == key)
                .map_or(0, |(_, old_leaf)| leaf.common_prefix_len(old_leaf));
            let segments = match self.segments.iter().position(|(k, _)| *k == key) {
                Some(ix) => &mut self.segments[ix].1,
                None => {
                    self.segments.push((key, Vec::new()));
                    &mut self.segments.last_mut().expect("just pushed").1
                }
            };
            // Text past the divergence is repainted, so its earlier fade no
            // longer describes what is on screen.
            segments.retain_mut(|segment| {
                segment.range.end = segment.range.end.min(prefix);
                segment.range.start < segment.range.end
            });
            if prefix >= len {
                continue;
            }
            if self.motion.stream_fade_stagger.is_zero() {
                segments.push(FadeSegment {
                    range: prefix..len,
                    started_at: now,
                });
                continue;
            }
            let words = fade_units(leaf.chunks(), prefix, len);
            let step = self.motion.stagger_step(words.len());
            for (ix, range) in words.into_iter().enumerate() {
                segments.push(FadeSegment {
                    range,
                    started_at: now + step * ix as u32,
                });
            }
        }
        self.segments.retain(|(_, segments)| !segments.is_empty());
    }

    /// Samples every unfinished segment at `now`, dropping the finished ones.
    /// `None` means nothing is fading, so no frame needs to follow.
    pub(super) fn frame(
        &mut self,
        now: Instant,
        reduce_motion: bool,
    ) -> Option<Arc<StreamFadeFrame>> {
        if self.segments.is_empty() {
            return None;
        }
        if reduce_motion || !self.is_enabled() {
            self.segments.clear();
            return None;
        }
        let timing =
            Timing::new(self.motion.stream_fade).ease(self.motion.stream_fade_easing.clone());
        let mut leaves = Vec::with_capacity(self.segments.len());
        self.segments.retain_mut(|(key, segments)| {
            let mut fades = Vec::with_capacity(segments.len());
            segments.retain(|segment| {
                let sample = timing.sample(now.saturating_duration_since(segment.started_at));
                if sample.finished {
                    return false;
                }
                let fade_out = (1.0 - sample.directed_progress).clamp(0.0, 1.0);
                fades.push((segment.range.clone(), fade_out));
                true
            });
            if fades.is_empty() {
                return false;
            }
            leaves.push((*key, fades));
            true
        });
        (!leaves.is_empty()).then(|| Arc::new(StreamFadeFrame { leaves }))
    }
}

/// A block's rendered text, in the byte space its highlights use.
enum TextLeaf<'a> {
    Paragraph(&'a Paragraph),
    Code(SharedString),
}

enum Chunks<'a> {
    Paragraph(std::slice::Iter<'a, InlineNode>),
    Code(Option<&'a str>),
}

impl<'a> Iterator for Chunks<'a> {
    type Item = &'a str;

    fn next(&mut self) -> Option<&'a str> {
        match self {
            Self::Paragraph(nodes) => nodes.next().map(|node| node.text.as_ref()),
            Self::Code(code) => code.take(),
        }
    }
}

impl TextLeaf<'_> {
    fn chunks(&self) -> Chunks<'_> {
        match self {
            Self::Paragraph(paragraph) => Chunks::Paragraph(paragraph.children.iter()),
            Self::Code(code) => Chunks::Code(Some(code.as_ref())),
        }
    }

    fn len(&self) -> usize {
        self.chunks().map(str::len).sum()
    }

    /// The length of the rendered text `self` shares with `old`, on a char
    /// boundary of `self`.
    fn common_prefix_len(&self, old: &Self) -> usize {
        let prefix = common_prefix_len(self.chunks(), old.chunks());
        floor_char_boundary(self.chunks(), prefix)
    }
}

fn text_leaves<'a>(block: &'a BlockNode, out: &mut Vec<(TextLeafKey, TextLeaf<'a>)>) {
    match block {
        BlockNode::Paragraph(paragraph) => {
            if let Some(span) = paragraph.span {
                out.push((
                    TextLeafKey::block(span.start),
                    TextLeaf::Paragraph(paragraph),
                ));
            }
        }
        BlockNode::Heading {
            children,
            span: Some(span),
            ..
        } => out.push((
            TextLeafKey::block(span.start),
            TextLeaf::Paragraph(children),
        )),
        BlockNode::CodeBlock(code_block) => {
            if let Some(span) = code_block.span {
                out.push((
                    TextLeafKey::block(span.start),
                    TextLeaf::Code(code_block.code()),
                ));
            }
        }
        BlockNode::Table(table) => {
            if let Some(span) = table.span {
                let cells = table.children.iter().flat_map(|row| row.children.iter());
                for (ordinal, cell) in cells.enumerate() {
                    out.push((
                        TextLeafKey::table_cell(span.start, ordinal),
                        TextLeaf::Paragraph(&cell.children),
                    ));
                }
            }
        }
        BlockNode::Root { children, .. }
        | BlockNode::Blockquote { children, .. }
        | BlockNode::List { children, .. }
        | BlockNode::ListItem { children, .. } => {
            for child in children {
                text_leaves(child, out);
            }
        }
        _ => {}
    }
}

/// Compares chunk by chunk with slice equality, descending to bytes only at
/// the first chunk pair that differs.
fn common_prefix_len<'a>(
    mut a: impl Iterator<Item = &'a str>,
    mut b: impl Iterator<Item = &'a str>,
) -> usize {
    let (mut a_rest, mut b_rest): (&[u8], &[u8]) = (&[], &[]);
    let mut len = 0;
    loop {
        if a_rest.is_empty() {
            match a.next() {
                Some(chunk) => a_rest = chunk.as_bytes(),
                None => return len,
            }
            continue;
        }
        if b_rest.is_empty() {
            match b.next() {
                Some(chunk) => b_rest = chunk.as_bytes(),
                None => return len,
            }
            continue;
        }
        let step = a_rest.len().min(b_rest.len());
        if a_rest[..step] != b_rest[..step] {
            return len
                + a_rest
                    .iter()
                    .zip(b_rest)
                    .take_while(|(x, y)| x == y)
                    .count();
        }
        len += step;
        a_rest = &a_rest[step..];
        b_rest = &b_rest[step..];
    }
}

/// Splits `start..end` of the rendered text into the units that fade one
/// after another: a word together with the whitespace after it, or one CJK
/// character, since CJK text has no spaces to reveal it by.
fn fade_units<'a>(
    chunks: impl Iterator<Item = &'a str>,
    start: usize,
    end: usize,
) -> Vec<Range<usize>> {
    let mut units = Vec::new();
    let mut unit_start = start;
    let mut unit_has_glyph = false;
    let mut previous: Option<char> = None;
    let mut offset = 0;
    for chunk in chunks {
        if offset + chunk.len() <= start {
            offset += chunk.len();
            previous = chunk.chars().next_back();
            continue;
        }
        for (ix, c) in chunk.char_indices() {
            let position = offset + ix;
            if position >= end {
                break;
            }
            if position >= start {
                let starts_unit = unit_has_glyph
                    && !c.is_whitespace()
                    && (is_cjk(c) || previous.is_some_and(|p| p.is_whitespace() || is_cjk(p)));
                if starts_unit && position > unit_start {
                    units.push(unit_start..position);
                    unit_start = position;
                    unit_has_glyph = false;
                }
                unit_has_glyph |= !c.is_whitespace();
            }
            previous = Some(c);
        }
        offset += chunk.len();
        if offset >= end {
            break;
        }
    }
    if unit_start < end {
        units.push(unit_start..end);
    }
    units
}

fn is_cjk(c: char) -> bool {
    matches!(
        u32::from(c),
        0x3040..=0x30FF // Hiragana, Katakana
            | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A
            | 0x4E00..=0x9FFF // CJK Unified Ideographs
            | 0xAC00..=0xD7AF // Hangul syllables
            | 0xF900..=0xFAFF // CJK Compatibility Ideographs
            | 0x20000..=0x2FA1F // CJK Unified Ideographs Extensions B and later
    )
}

fn floor_char_boundary<'a>(chunks: impl Iterator<Item = &'a str>, offset: usize) -> usize {
    let mut start = 0;
    for chunk in chunks {
        let end = start + chunk.len();
        if offset < end {
            let mut local = offset - start;
            while !chunk.is_char_boundary(local) {
                local -= 1;
            }
            return start + local;
        }
        start = end;
    }
    offset
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn common_prefix_spans_chunk_boundaries() {
        assert_eq!(
            common_prefix_len(["ab", "cd"].into_iter(), ["abc", "d"].into_iter()),
            4
        );
        assert_eq!(
            common_prefix_len(["ab", "cd"].into_iter(), ["abc", "x"].into_iter()),
            3
        );
        assert_eq!(
            common_prefix_len(["", "ab"].into_iter(), ["a", "", "b", "c"].into_iter()),
            2
        );
        assert_eq!(common_prefix_len(["ab"].into_iter(), [].into_iter()), 0);
    }

    #[test]
    fn fade_units_are_words_with_their_trailing_space() {
        let text = ["hello", " one two", "  three"];
        assert_eq!(
            fade_units(text.into_iter(), 5, 20),
            vec![5..10, 10..15, 15..20]
        );
        // A unit that is only whitespace joins the word after it.
        assert_eq!(fade_units(["a  b"].into_iter(), 1, 4), vec![1..4]);
        assert_eq!(
            fade_units(["abc"].into_iter(), 3, 3),
            Vec::<Range<usize>>::new()
        );
    }

    #[test]
    fn fade_units_split_cjk_by_character() {
        assert_eq!(
            fade_units(["你好,世界 ok"].into_iter(), 0, 18),
            vec![0..3, 3..6, 6..9, 9..12, 12..16, 16..18]
        );
        // Latin before CJK starts a unit at the script change.
        assert_eq!(fade_units(["ab中"].into_iter(), 0, 5), vec![0..2, 2..5]);
    }

    #[test]
    fn stagger_is_compressed_into_one_fade() {
        let motion = TextViewMotion::default()
            .with_stream_fade(Duration::from_millis(600))
            .with_stream_fade_stagger(Duration::from_millis(100));
        assert_eq!(motion.stagger_step(1), Duration::ZERO);
        assert_eq!(motion.stagger_step(3), Duration::from_millis(100));
        assert_eq!(motion.stagger_step(30), Duration::from_millis(20));
    }

    #[test]
    fn prefix_never_splits_a_character() {
        // "中" and "串" share their first UTF-8 byte.
        let new = "a中";
        let old = "a串";
        let prefix = common_prefix_len([new].into_iter(), [old].into_iter());
        assert!(prefix > 1 && !new.is_char_boundary(prefix));
        assert_eq!(floor_char_boundary([new].into_iter(), prefix), 1);
        assert_eq!(floor_char_boundary(["a", ""].into_iter(), 4), 4);
    }
}