gpui-pre-web 0.3.5

Zed's `gpui_web` crate (gpui-pre snapshot of zed@d89e9c2)
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
//! Eligibility only for independent, horizontal Canvas fallback of a complete
//! extended grapheme. Callers must still check whether bundled shaping supplies
//! the requested glyph and presentation; eligibility alone does not override it.
//!
//! This is intentionally not a Unicode sequence validator or an RGI emoji database.
//! Han variation selectors are checked structurally, not against the IVD registry.
//! Emoji selectors are checked against the Emoji property, not the registered
//! variation-sequence list. Eligibility does not guarantee browser coverage.
//! Flags accept two regional indicators, not only assigned country codes. ZWJ
//! support is limited to person/profession pairs and a small explicit allowlist;
//! tags are limited to the three subdivision flags. Other sequences stay on Cosmic.

use unicode_properties::{EmojiStatus, GeneralCategory, UnicodeEmoji, UnicodeGeneralCategory};
use unicode_script::{Script, UnicodeScript};
use unicode_segmentation::UnicodeSegmentation;

/// Controls browser-font fallback when loaded fonts lack a glyph or its emoji presentation.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CanvasFontFallback {
    /// Use only fonts loaded into GPUI.
    Disabled,
    /// Use Canvas only for eligible graphemes requesting emoji presentation.
    #[default]
    Emoji,
    /// Also allow approximate independent rendering of eligible horizontal CJK text.
    EmojiAndCjk,
}

impl CanvasFontFallback {
    #[cfg(any(target_family = "wasm", test))]
    pub(crate) fn allows(self, emoji_presentation: bool) -> bool {
        match self {
            Self::Disabled => false,
            Self::Emoji => emoji_presentation,
            Self::EmojiAndCjk => true,
        }
    }
}

/// A supported grapheme assumed to be independently renderable.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CanvasFallback {
    /// Whether to request emoji presentation instead of ordinary text presentation.
    pub emoji_presentation: bool,
}

/// Returns a presentation only when `grapheme` is exactly one supported extended
/// grapheme cluster. No normalization, splitting, or font-coverage decision occurs.
pub fn classify_canvas_fallback(grapheme: &str) -> Option<CanvasFallback> {
    if grapheme.is_ascii() {
        return None;
    }
    let mut graphemes = grapheme.graphemes(true);
    if graphemes.next()? != grapheme || graphemes.next().is_some() {
        return None;
    }

    if is_cjk(grapheme) {
        Some(CanvasFallback {
            emoji_presentation: false,
        })
    } else {
        classify_emoji(grapheme).map(|emoji_presentation| CanvasFallback { emoji_presentation })
    }
}

fn is_cjk(grapheme: &str) -> bool {
    let mut characters = grapheme.chars();
    let Some(base) = characters.next() else {
        return false;
    };
    let suffix = characters.as_str();

    // The script/category checks exclude unassigned holes; the ranges exclude
    // Han radicals, iteration marks, and other non-ideographic Han characters.
    if base.script() == Script::Han
        && base.general_category() == GeneralCategory::OtherLetter
        && matches!(base, '\u{3400}'..='\u{9fff}' | '\u{f900}'..='\u{faff}'
            | '\u{20000}'..='\u{323af}')
    {
        return suffix.is_empty()
            || matches!(
                (characters.next(), characters.next()),
                (Some('\u{fe00}'..='\u{fe02}' | '\u{e0100}'..='\u{e01ef}'), None)
            );
    }

    if matches!(base, '\u{3041}'..='\u{3096}' | '\u{30a1}'..='\u{30fa}') {
        return suffix.is_empty()
            || match suffix {
                "\u{3099}" => "γ†γ‹γγγ‘γ“γ•γ—γ™γ›γγŸγ‘γ€γ¦γ¨γ―γ²γ΅γΈγ»γ‚¦γ‚«γ‚­γ‚―γ‚±γ‚³γ‚΅γ‚·γ‚Ήγ‚»γ‚½γ‚Ώγƒγƒ„γƒ†γƒˆγƒγƒ’γƒ•γƒ˜γƒ›γƒ―γƒ°γƒ±γƒ²".contains(base),
                "\u{309a}" => "γ―γ²γ΅γΈγ»γƒγƒ’γƒ•γƒ˜γƒ›".contains(base),
                _ => false,
            };
    }

    if matches!(base, '\u{ac00}'..='\u{d7a3}') {
        return suffix.is_empty()
            || ((base as u32 - 0xac00).is_multiple_of(28)
                && is_single_modern_trailing_jamo(suffix));
    }
    if matches!(base, '\u{1100}'..='\u{1112}') {
        return matches!(characters.next(), Some('\u{1161}'..='\u{1175}'))
            && (characters.as_str().is_empty()
                || is_single_modern_trailing_jamo(characters.as_str()));
    }

    suffix.is_empty()
        && (matches!(base, '\u{3131}'..='\u{3163}')
            || "γ€γ€‚γ€ˆγ€‰γ€Šγ€‹γ€Œγ€γ€Žγ€γ€γ€‘γ€”γ€•οΌˆοΌ‰οΌ»οΌ½ο½›ο½οΌŒοΌŽοΌοΌŸοΌšοΌ›γƒ»γƒΌγ€…γ€†".contains(base))
}

fn is_single_modern_trailing_jamo(text: &str) -> bool {
    let mut characters = text.chars();
    matches!(characters.next(), Some('\u{11a8}'..='\u{11c2}')) && characters.next().is_none()
}

fn classify_emoji(grapheme: &str) -> Option<bool> {
    let mut characters = grapheme.chars();
    let base = characters.next()?;
    let suffix = characters.as_str();

    if matches!(base, '0'..='9' | '#' | '*') {
        return match suffix {
            "\u{20e3}" | "\u{fe0f}\u{20e3}" => Some(true),
            _ => None,
        };
    }
    if unicode_properties::emoji::is_regional_indicator(base) {
        return (characters
            .next()
            .is_some_and(unicode_properties::emoji::is_regional_indicator)
            && characters.next().is_none())
        .then_some(true);
    }
    if matches!(
        grapheme,
        "🏴\u{e0067}\u{e0062}\u{e0065}\u{e006e}\u{e0067}\u{e007f}"
            | "🏴\u{e0067}\u{e0062}\u{e0073}\u{e0063}\u{e0074}\u{e007f}"
            | "🏴\u{e0067}\u{e0062}\u{e0077}\u{e006c}\u{e0073}\u{e007f}"
    ) {
        return Some(true);
    }
    if grapheme.contains('\u{200d}') {
        return is_supported_zwj_sequence(grapheme).then_some(true);
    }
    classify_emoji_unit(grapheme)
}

fn classify_emoji_unit(text: &str) -> Option<bool> {
    let mut characters = text.chars();
    let base = characters.next()?;
    if !base.is_emoji_char() || base.is_emoji_component() {
        return None;
    }
    let status = base.emoji_status();
    let mut emoji_presentation = matches!(
        status,
        EmojiStatus::EmojiPresentation | EmojiStatus::EmojiPresentationAndModifierBase
    );
    let mut next = characters.next();
    let explicit_text = next == Some('\u{fe0e}');
    if matches!(next, Some('\u{fe0e}' | '\u{fe0f}')) {
        emoji_presentation = !explicit_text;
        next = characters.next();
    }
    if let Some(modifier) = next {
        if explicit_text
            || !matches!(
                status,
                EmojiStatus::EmojiModifierBase | EmojiStatus::EmojiPresentationAndModifierBase
            )
            || modifier.emoji_status() != EmojiStatus::EmojiPresentationAndModifierAndEmojiComponent
        {
            return None;
        }
        emoji_presentation = true;
    }
    characters.next().is_none().then_some(emoji_presentation)
}

fn is_supported_zwj_sequence(grapheme: &str) -> bool {
    if matches!(
        grapheme,
        "πŸ‘¨β€πŸ‘©β€πŸ‘§" | "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦"
            | "πŸ‘©β€πŸ‘©β€πŸ‘§β€πŸ‘¦"
            | "πŸ‘¨β€πŸ‘¨β€πŸ‘§β€πŸ‘¦"
            | "πŸ³οΈβ€πŸŒˆ"
            | "πŸ³οΈβ€βš§οΈ"
            | "πŸ΄β€β˜ οΈ"
            | "❀️‍πŸ”₯"
            | "β€οΈβ€πŸ©Ή"
            | "πŸ‘οΈβ€πŸ—¨οΈ"
            | "πŸ»β€β„οΈ"
    ) {
        return true;
    }
    let Some((person, profession)) = grapheme.split_once('\u{200d}') else {
        return false;
    };
    matches!(person.chars().next(), Some('πŸ‘¨' | 'πŸ‘©' | 'πŸ§‘'))
        && classify_emoji_unit(person) == Some(true)
        && matches!(
            profession,
            "βš•οΈ" | "βš–οΈ"
                | "✈️"
                | "🌾"
                | "🍳"
                | "πŸŽ“"
                | "🎀"
                | "🎨"
                | "🏫"
                | "🏭"
                | "πŸ’»"
                | "πŸ’Ό"
                | "πŸ”§"
                | "πŸ”¬"
                | "πŸš€"
                | "πŸš’"
        )
}

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

    #[test]
    fn canvas_font_fallback_policy() {
        assert_eq!(CanvasFontFallback::default(), CanvasFontFallback::Emoji);
        for grapheme in ["πŸ˜€", "❀️", "1️⃣", "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦", "δΈ­", "か\u{3099}", "ᄀᅑᆨ", "Β©", "❀︎"]
        {
            let fallback = classify_canvas_fallback(grapheme).expect("eligible grapheme");
            assert!(!CanvasFontFallback::Disabled.allows(fallback.emoji_presentation));
            assert_eq!(
                CanvasFontFallback::Emoji.allows(fallback.emoji_presentation),
                ["πŸ˜€", "❀️", "1️⃣", "πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦"].contains(&grapheme),
            );
            assert!(CanvasFontFallback::EmojiAndCjk.allows(fallback.emoji_presentation));
        }
    }

    #[test]
    fn ascii_is_ineligible_but_keycaps_are_preserved() {
        for byte in 0..=0x7f_u8 {
            assert_eq!(classify_canvas_fallback(&(byte as char).to_string()), None);
        }
        for text in ["", "Hello", "0123456789#*", "\r\n"] {
            assert_eq!(classify_canvas_fallback(text), None);
        }
        for base in "0123456789#*".chars() {
            for text in [format!("{base}\u{20e3}"), format!("{base}\u{fe0f}\u{20e3}")] {
                assert_eq!(
                    classify_canvas_fallback(&text),
                    Some(CanvasFallback {
                        emoji_presentation: true,
                    }),
                    "{text:?}"
                );
            }
        }
    }

    #[test]
    fn ordinary_cjk_clusters() {
        for text in [
            "ζΌ’",
            "π €€",
            "﨑",
            "ζΌ’\u{fe00}",
            "θ‘›\u{e0100}",
            "θ‘›\u{e01ef}",
            "あ",
            "ガ",
            "か\u{3099}",
            "ハ\u{309a}",
            "κ°€",
            "각",
            "α„€α…‘",
            "ᄀᅑᆨ",
            "각",
            "γ„±",
            "、",
            "。",
            "γ€Œ",
            "」",
            "(",
            "!",
            "γƒΌ",
            "γ€…",
        ] {
            assert_eq!(
                classify_canvas_fallback(text),
                Some(CanvasFallback {
                    emoji_presentation: false,
                }),
                "{text:?}"
            );
        }
    }

    #[test]
    fn emoji_presentation_is_preserved() {
        for (text, emoji_presentation) in [
            ("πŸ˜€", true),
            ("Β©", false),
            ("Β©\u{fe0e}", false),
            ("Β©\u{fe0f}", true),
            ("❀", false),
            ("❀\u{fe0e}", false),
            ("❀\u{fe0f}", true),
            ("πŸ˜€\u{fe0e}", false),
            ("πŸ‘πŸ½", true),
            ("☝🏽", true),
            ("πŸ‘\u{fe0f}🏽", true),
            ("πŸ‡―πŸ‡΅", true),
            ("1\u{20e3}", true),
            ("#\u{fe0f}\u{20e3}", true),
            ("*\u{fe0f}\u{20e3}", true),
            ("πŸ‘©πŸ½β€πŸ’»", true),
            ("πŸ§‘β€βš•οΈ", true),
            ("πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦", true),
            ("πŸ³οΈβ€πŸŒˆ", true),
            (
                "🏴\u{e0067}\u{e0062}\u{e0065}\u{e006e}\u{e0067}\u{e007f}",
                true,
            ),
            (
                "🏴\u{e0067}\u{e0062}\u{e0073}\u{e0063}\u{e0074}\u{e007f}",
                true,
            ),
            (
                "🏴\u{e0067}\u{e0062}\u{e0077}\u{e006c}\u{e0073}\u{e007f}",
                true,
            ),
        ] {
            assert_eq!(
                classify_canvas_fallback(text),
                Some(CanvasFallback { emoji_presentation }),
                "{text:?}"
            );
        }
    }

    #[test]
    fn unsupported_scripts_and_cjk_forms_stay_on_cosmic() {
        for text in [
            "a",
            "Γ©",
            "Ξ±",
            "Π–",
            "Ψ΄",
            "Χ©",
            "ΰ€•",
            "ΰ€•ΰ₯ΰ€·",
            "ก",
            "αž€",
            "α  ",
            "ΰ½€",
            "\0",
            "\n",
            "\r\n",
            "\u{202e}",
            "\u{200d}",
            "\u{fdd0}",
            "\u{10ffff}",
            "\u{2a6e0}",
            "\u{e000}",
            "\u{3099}",
            "\u{fe0f}",
            "\u{e0100}",
            "ζΌ’\u{301}",
            "ζΌ’\u{fe03}",
            "ζΌ’\u{fe0f}",
            "ζΌ’\u{e0100}\u{e0101}",
            "あ\u{3099}",
            "か\u{309a}",
            "か\u{3099}\u{3099}",
            "α„€",
            "α…‘",
            "ᆨ",
            "α„“α…‘",
            "α„€α…Ά",
            "ᄀᅑᇃ",
            "각ᆨ",
            "α„€α„€α…‘",
            "\u{3164}",
            "\u{3165}",
            "βΊ€",
            "βΌ€",
            "㇀",
            "㆐",
            "γ„…",
            "㐀\u{200d}",
            "\u{1b000}",
            "ο½Ά",
            "!\u{301}",
        ] {
            assert_eq!(classify_canvas_fallback(text), None, "{text:?}");
        }
    }

    #[test]
    fn malformed_or_out_of_policy_emoji_stay_on_cosmic() {
        for text in [
            "0",
            "#",
            "*",
            "1\u{fe0f}",
            "#\u{fe0e}",
            "1\u{fe0e}\u{20e3}",
            "a\u{20e3}",
            "🏽",
            "πŸ‡―",
            "πŸ˜€πŸ½",
            "πŸ‘πŸ½πŸ½",
            "πŸ‘\u{fe0e}🏽",
            "πŸ‘πŸ½\u{fe0f}",
            "❀\u{fe0f}\u{fe0f}",
            "πŸ˜€\u{301}",
            "🦰",
            "πŸ˜€β€πŸ˜€",
            "πŸ‘©β€",
            "πŸ‘©β€πŸ’»β€πŸš€",
            "πŸ‘©\u{fe0e}β€πŸ’»",
            "🏴\u{e0067}",
            "🏴\u{e0061}\u{e0062}\u{e007f}",
            "πŸ˜€\u{e0067}\u{e007f}",
        ] {
            assert_eq!(classify_canvas_fallback(text), None, "{text:?}");
        }
    }

    #[test]
    fn accepts_only_one_whole_extended_grapheme() {
        for text in [
            "",
            "ζΌ’ε­—",
            "あい",
            "κ°€λ‚˜",
            "πŸ˜€πŸ˜€",
            "πŸ‡―πŸ‡΅πŸ‡Ί",
            "πŸ‡―πŸ‡΅πŸ‡ΊπŸ‡Έ",
            " ζΌ’",
            "ζΌ’\n",
        ] {
            assert_eq!(classify_canvas_fallback(text), None, "{text:?}");
        }
        let text = "aか\u{3099}πŸ‘©πŸ½β€πŸ’»ζΌ’\u{e0100}";
        let eligible: Vec<_> = text
            .grapheme_indices(true)
            .filter_map(|(start, grapheme)| {
                classify_canvas_fallback(grapheme).map(|_| start..start + grapheme.len())
            })
            .collect();
        assert_eq!(
            eligible
                .iter()
                .map(|range| &text[range.clone()])
                .collect::<Vec<_>>(),
            ["か\u{3099}", "πŸ‘©πŸ½β€πŸ’»", "ζΌ’\u{e0100}"]
        );
    }
}