twrite-gpui 0.15.0

GPUI rendering, canvas text-shaping, and editor component for twrite
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
//! GPUI rendering, canvas text-shaping, and interactive editor component for twrite.

/// Canvas element handling prepaint, layout, and GPU quad rendering.
pub mod canvas;
/// Configuration settings for font size, line height, wrapping, and gutters.
pub mod config;
/// Main editor entity, keybindings, selections, and hook executions.
pub mod editor;
/// Frame-rate HUD for interactive performance testing.
pub mod fps;
/// Translation helpers from GPUI key events to normalized twrite key events.
pub mod input;
/// Per-version viewport cache for highlight/conceal/link inputs.
pub mod layout_cache;
/// Dumb renderer for the shared headless prompt (bottom bar, palette).
pub mod prompt_bar;
/// Color palettes, Catppuccin themes, and syntax token style resolution.
pub mod theme;

pub use canvas::{EditorCanvas, LineMetrics, RunFonts, build_line_text_runs};
pub use config::EditorConfig;
pub use editor::{Editor, FaceAvailability, SelectionGranularity, VisibleLineLayout, VisibleLink};
pub use fps::{FrameStats, fps_badge};
pub use layout_cache::{CachedInput, LayoutCache};
pub use prompt_bar::PromptBar;
pub use theme::{EditorTheme, ResolvedTokenStyle, SyntaxTheme};

#[cfg(test)]
mod tests {
    use super::*;
    use gpui::{Font, FontStyle, FontWeight, px};
    use twrite_core::{HighlightTag, StyleSpan};

    #[test]
    fn test_line_metrics_quote_detection_when_concealed() {
        let spans = vec![StyleSpan::tag(0..2, HighlightTag::Blockquote)];
        let metrics = LineMetrics::for_line("> Quote", "Quote", &spans, px(16.0), px(22.0));
        assert!(metrics.is_quote);
        assert!(!metrics.is_code_block);
        assert_eq!(metrics.line_height, px(22.0));

        // No tag -> no quote, proving detection is tag-driven not string-driven.
        let plain = LineMetrics::for_line("> Quote", "> Quote", &[], px(16.0), px(22.0));
        assert!(!plain.is_quote);
    }

    #[test]
    fn test_line_metrics_code_fence() {
        let active_spans = vec![StyleSpan::tag(0..7, HighlightTag::Code)];
        let metrics =
            LineMetrics::for_line("```rust", "```rust", &active_spans, px(16.0), px(22.0));
        assert_eq!(metrics.line_height, px(22.0));
        assert!(metrics.is_code_block);
    }

    #[test]
    fn test_line_metrics_code_empty_line_inside_block() {
        let spans = vec![StyleSpan::tag(0..0, HighlightTag::Code)];
        let metrics = LineMetrics::for_line("", "", &spans, px(16.0), px(22.0));
        assert!(metrics.is_code_block);
        assert_eq!(metrics.line_height, px(22.0));
    }

    #[test]
    fn test_build_line_text_runs_code_block_disables_text_bg() {
        let theme = EditorTheme::default();
        let font: Font = gpui::font(".SystemUIFont");
        let spans = vec![StyleSpan::tag(0..4, HighlightTag::Code)];

        let runs_block = build_line_text_runs(
            "test",
            &spans,
            None,
            &RunFonts {
                base: &font,
                code: &font,
            },
            &theme,
            true,
            false,
        );
        assert_eq!(runs_block.len(), 1);
        assert!(runs_block[0].background_color.is_none());

        let runs_inline = build_line_text_runs(
            "test",
            &spans,
            None,
            &RunFonts {
                base: &font,
                code: &font,
            },
            &theme,
            false,
            false,
        );
        assert_eq!(runs_inline.len(), 1);
        assert_eq!(runs_inline[0].background_color, Some(theme.syntax.code_bg));

        let runs_task_checked = build_line_text_runs(
            "test",
            &spans,
            None,
            &RunFonts {
                base: &font,
                code: &font,
            },
            &theme,
            false,
            true,
        );
        assert_eq!(runs_task_checked.len(), 1);
        assert!(runs_task_checked[0].strikethrough.is_some());
    }

    #[test]
    fn test_line_metrics_task_state_detection() {
        let unchecked_spans = vec![StyleSpan::tag(0..6, HighlightTag::TaskUnchecked)];
        let unchecked =
            LineMetrics::for_line("- [ ] Todo", "Todo", &unchecked_spans, px(16.0), px(22.0));
        assert_eq!(unchecked.task_state, Some(false));

        let checked_spans = vec![StyleSpan::tag(0..6, HighlightTag::TaskChecked)];
        let checked =
            LineMetrics::for_line("- [x] Done", "Done", &checked_spans, px(16.0), px(22.0));
        assert_eq!(checked.task_state, Some(true));

        let plain = LineMetrics::for_line("Plain text", "Plain text", &[], px(16.0), px(22.0));
        assert_eq!(plain.task_state, None);

        // Raw task syntax without tags must NOT be detected (custom-language proof).
        let raw_only = LineMetrics::for_line("- [ ] Todo", "- [ ] Todo", &[], px(16.0), px(22.0));
        assert_eq!(raw_only.task_state, None);
    }

    #[test]
    fn test_line_metrics_thematic_break_detection() {
        let spans = vec![StyleSpan::tag(0..3, HighlightTag::HorizontalRule)];
        let metrics = LineMetrics::for_line("---", "---", &spans, px(16.0), px(22.0));
        assert!(metrics.is_thematic_break);

        let plain = LineMetrics::for_line("---", "---", &[], px(16.0), px(22.0));
        assert!(!plain.is_thematic_break);
    }

    #[test]
    fn test_visible_link_layout() {
        let link = VisibleLink {
            bounds: gpui::Bounds::new(
                gpui::point(px(50.0), px(20.0)),
                gpui::size(px(60.0), px(20.0)),
            ),
            url: "https://example.com".to_string(),
        };
        assert!(link.bounds.contains(&gpui::point(px(60.0), px(25.0))));
        assert!(!link.bounds.contains(&gpui::point(px(120.0), px(25.0))));
        assert_eq!(link.url, "https://example.com");
    }

    /// Returns the font of the run covering byte `idx` in `text`.
    fn run_font_at(runs: &[gpui::TextRun], text: &str, idx: usize) -> gpui::Font {
        let mut offset = 0;
        for run in runs {
            if idx < offset + run.len {
                return run.font.clone();
            }
            offset += run.len;
        }
        panic!("idx {idx} out of runs for {text:?}");
    }

    #[test]
    fn test_build_line_text_runs_bold_italic_fonts() {
        // Proves the span -> run pipeline requests real faces: if bold/italic
        // don't *paint* differently, the cause is missing OS font faces
        // (silent font-kit fallback), not this pipeline.
        let theme = EditorTheme::default();
        let font: Font = gpui::font(".SystemUIFont");
        let text = "Hi bold and ital!";
        let spans = vec![
            StyleSpan::tag(3..7, HighlightTag::Bold),
            StyleSpan::tag(12..16, HighlightTag::Italic),
        ];
        let runs = build_line_text_runs(
            text,
            &spans,
            None,
            &RunFonts {
                base: &font,
                code: &font,
            },
            &theme,
            false,
            false,
        );

        let plain = run_font_at(&runs, text, 0);
        assert_eq!(plain.weight, FontWeight::NORMAL);
        assert_eq!(plain.style, FontStyle::Normal);

        let bold = run_font_at(&runs, text, 4);
        assert_eq!(bold.weight, FontWeight::BOLD);
        assert_eq!(bold.style, FontStyle::Normal);

        let italic = run_font_at(&runs, text, 13);
        assert_eq!(italic.weight, FontWeight::NORMAL);
        assert_eq!(italic.style, FontStyle::Italic);
    }

    #[test]
    fn test_build_line_text_runs_code_spans_use_code_font() {
        let theme = EditorTheme::default();
        let font: Font = gpui::font(".SystemUIFont");
        let code_font = Font {
            family: "CodeFam".into(),
            ..gpui::font(".SystemUIFont")
        };
        let text = "a `b` c";
        let spans = vec![StyleSpan::tag(2..5, HighlightTag::Code)];
        let runs = build_line_text_runs(
            text,
            &spans,
            None,
            &RunFonts {
                base: &font,
                code: &code_font,
            },
            &theme,
            false,
            false,
        );

        assert_eq!(
            run_font_at(&runs, text, 0).family.as_ref(),
            font.family.as_ref()
        );
        assert_eq!(run_font_at(&runs, text, 3).family.as_ref(), "CodeFam");
        assert_eq!(
            run_font_at(&runs, text, 6).family.as_ref(),
            font.family.as_ref()
        );
    }

    #[test]
    fn test_line_metrics_heading_levels() {
        let h1 = LineMetrics::for_line(
            "# A",
            "# A",
            &[StyleSpan::tag(0..3, HighlightTag::Heading(1))],
            px(16.0),
            px(22.0),
        );
        assert_eq!(h1.font_size, px(16.0) * 2.0);

        let h4 = LineMetrics::for_line(
            "#### D",
            "#### D",
            &[StyleSpan::tag(0..6, HighlightTag::Heading(4))],
            px(16.0),
            px(22.0),
        );
        assert_eq!(h4.font_size, px(16.0) * 1.125);

        // Lowest level wins when several heading tags share a line.
        let mixed = LineMetrics::for_line(
            "mix",
            "mix",
            &[
                StyleSpan::tag(0..3, HighlightTag::Heading(3)),
                StyleSpan::tag(0..3, HighlightTag::Heading(1)),
            ],
            px(16.0),
            px(22.0),
        );
        assert_eq!(mixed.font_size, px(16.0) * 2.0);

        // Out-of-range levels render bold at the base size.
        let odd = LineMetrics::for_line(
            "odd",
            "odd",
            &[StyleSpan::tag(0..3, HighlightTag::Heading(9))],
            px(16.0),
            px(22.0),
        );
        assert_eq!(odd.font_size, px(16.0));
        assert_eq!(odd.line_height, px(22.0));
    }

    #[test]
    fn test_custom_tag_colors() {
        let mut theme = EditorTheme::default();
        // Unregistered customs fall back to the foreground.
        assert_eq!(
            theme.tag_color(HighlightTag::Custom("speaker")),
            theme.foreground
        );

        theme
            .syntax
            .set_custom_tag_color("speaker", gpui::rgb(0xf9e2af).into());
        assert_eq!(
            theme.tag_color(HighlightTag::Custom("speaker")),
            gpui::rgb(0xf9e2af).into()
        );
        // Other names are unaffected.
        assert_eq!(
            theme.tag_color(HighlightTag::Custom("dialogue")),
            theme.foreground
        );
    }

    #[test]
    fn test_heading_level_colors() {
        let theme = EditorTheme::default();
        assert_eq!(
            theme.tag_color(HighlightTag::Heading(1)),
            theme.syntax.heading1
        );
        assert_eq!(
            theme.tag_color(HighlightTag::Heading(2)),
            theme.syntax.heading2
        );
        assert_eq!(
            theme.tag_color(HighlightTag::Heading(4)),
            theme.syntax.heading3
        );
    }

    #[test]
    fn test_highlight_tag_styling() {
        use twrite_core::StyleValue;
        let theme = EditorTheme::default();
        // Marked text keeps the foreground; the tint comes from the background.
        assert_eq!(theme.tag_color(HighlightTag::Highlight), theme.foreground);
        let resolved = theme.resolve_style(&StyleValue::Tag(HighlightTag::Highlight));
        assert_eq!(resolved.background, Some(theme.syntax.highlight_bg));
        assert!(!resolved.bold);
        // Inline code keeps its own pill fill.
        let code = theme.resolve_style(&StyleValue::Tag(HighlightTag::Code));
        assert_eq!(code.background, Some(theme.syntax.code_bg));
    }

    #[test]
    fn test_callout_accent_colors() {
        use twrite_core::CalloutKind;
        let theme = EditorTheme::default();
        assert_eq!(
            theme.syntax.callout_accent(CalloutKind::Note),
            theme.syntax.callout_note
        );
        assert_eq!(
            theme.syntax.callout_accent(CalloutKind::Tip),
            theme.syntax.callout_tip
        );
        assert_eq!(
            theme.syntax.callout_accent(CalloutKind::Warning),
            theme.syntax.callout_warning
        );
        assert_eq!(
            theme.syntax.callout_accent(CalloutKind::Caution),
            theme.syntax.callout_caution
        );
        assert_eq!(
            theme.syntax.callout_accent(CalloutKind::Important),
            theme.syntax.callout_important
        );
        // Unknown kinds fall back to the note accent.
        assert_eq!(
            theme.syntax.callout_accent(CalloutKind::Other),
            theme.syntax.callout_note
        );
        // The structural tag itself stays neutral; accents apply to quads.
        assert_eq!(
            theme.tag_color(HighlightTag::Callout(CalloutKind::Warning)),
            theme.foreground
        );
    }

    #[test]
    fn test_line_metrics_callout_detection() {
        use twrite_core::CalloutKind;
        let callout = LineMetrics::for_line(
            "> [!TIP] T",
            "> [!TIP] T",
            &[StyleSpan::tag(
                0..10,
                HighlightTag::Callout(CalloutKind::Tip),
            )],
            px(16.0),
            px(22.0),
        );
        assert_eq!(callout.callout, Some(CalloutKind::Tip));

        let plain = LineMetrics::for_line(
            "> quote",
            "> quote",
            &[StyleSpan::tag(0..2, HighlightTag::Blockquote)],
            px(16.0),
            px(22.0),
        );
        assert_eq!(plain.callout, None);
    }

    #[test]
    fn test_visible_line_layout_fold_indicator() {
        let layout = VisibleLineLayout {
            row: 0,
            top: px(0.0),
            bottom: px(24.0),
            line_start_byte: 0,
            line_len_bytes: 7,
            text_origin_x: px(50.0),
            line_height: px(24.0),
            is_task_checkbox: false,
            checkbox_box_x: px(0.0),
            task_state: None,
            links: Vec::new(),
            fold_indicator_bounds: Some(gpui::Bounds::new(
                gpui::point(px(120.0), px(4.0)),
                gpui::size(px(30.0), px(16.0)),
            )),
        };
        let bounds = layout.fold_indicator_bounds.unwrap();
        assert!(bounds.contains(&gpui::point(px(130.0), px(10.0))));
        assert!(!bounds.contains(&gpui::point(px(60.0), px(10.0))));
    }
}