Skip to main content

escriba_render/
gpu.rs

1//! GPU renderer — implements [`madori::RenderCallback`] backed by garasu's
2//! glyphon-wrapped text renderer. Each frame:
3//!
4//!   1. Locks the shared `EditorState`.
5//!   2. Collects visible buffer lines into a single string.
6//!   3. Builds a glyphon `Buffer` (re-created each frame — phase 1.B; phase 2
7//!      will diff + reuse).
8//!   4. Prepares + renders through `madori::RenderContext::text`.
9//!
10//! Colors are the **Vellum** fleet theme (warm aged-paper Nord-matte),
11//! sourced from `escriba_ui::chrome::ChromePalette` so the GPU chrome matches
12//! the rest of the fleet (mado, tear, frostmourne, …) and escriba's TUI
13//! backend. Text is rendered in `snow1` (#E2DBC8, warm cream foreground)
14//! over a `night0` (#16140E, parchment ground) background. The status
15//! line is rendered in `ice_cyan` (#94BBB8, the matte accent).
16
17use std::sync::{Arc, Mutex};
18
19use escriba_core::{EditGen, Mode};
20use escriba_runtime::EditorState;
21use glyphon::{Attrs, Buffer, Color as GlyphColor, Family, Metrics, Shaping, TextArea, TextBounds};
22use escriba_ui::chrome::ChromePalette;
23use ishou_tokens::{EscribaSignals, Rgb, SignalMode, Srgb};
24use madori::{RenderCallback, RenderContext};
25// hikari (光) — the fleet syntax-highlighting spine. path→Box<dyn Highlighter>,
26// coverage-complete HlClass span partition, HlClass→Rgb via NordTheme.
27use hikari_core::{Ecosystem, Language, NordTheme, Rgb as HlRgb, Theme};
28
29/// Shared handle to the editor state — both the GPU renderer (reads) and
30/// the madori `on_event` callback (writes) hold one.
31pub type SharedState = Arc<Mutex<EditorState>>;
32
33/// The GPU render callback.
34///
35/// Holds a shared reference to the editor state. `render()` reads it under
36/// lock, computes a frame, releases the lock before touching the GPU to
37/// minimise contention with the event loop.
38pub struct GpuRenderer {
39    state: SharedState,
40    font_size: f32,
41    line_height: f32,
42    /// Cached font metrics — rebuilt if font_size changes.
43    metrics: Metrics,
44    /// hikari highlight registry (built once — resolves path→Highlighter).
45    eco: Ecosystem,
46    /// Nord syntax theme (HlClass→Rgb).
47    theme: NordTheme,
48    /// The resolved CHROME palette this renderer paints with.
49    ///
50    /// Held as state rather than re-derived per paint site, so a theme is
51    /// a VALUE the renderer owns and `set_theme` can change at runtime.
52    /// Every site previously called `ChromePalette::prescribed()` directly,
53    /// which hardwired the paint path to the FLEET default and made
54    /// `(deftheme :preset …)` inert no matter what the operator authored.
55    chrome: ChromePalette,
56    /// The refresh generation of the currently-cached text buffer — the seal
57    /// (`theory/ESCRIBA.md` §Refresh-Seal). When `EditorState::edit_gen()`
58    /// still equals this, the cached shaped buffer is reused verbatim: no
59    /// re-highlight, no re-shape. Init `u64::MAX` so the first frame always
60    /// paints.
61    last_gen: EditGen,
62    /// The shaped main-text glyphon buffer, cached across frames while the
63    /// generation is unchanged. `None` before the first paint.
64    cached_text: Option<Buffer>,
65    /// The incremental highlighter for the active buffer's language (M2). Held
66    /// across frames so a re-highlight re-lexes only the lines that changed
67    /// (hikari's `LineState` fixpoint, `theory/ESCRIBA.md` §X) instead of the
68    /// whole visible window. Keyed by path so a language switch rebuilds it;
69    /// `None` before the first paint.
70    highlighter: Option<(String, Box<dyn hikari_core::IncrementalHighlighter>)>,
71}
72
73impl GpuRenderer {
74    #[must_use]
75    pub fn new(state: SharedState) -> Self {
76        let font_size = 14.0;
77        let line_height = 20.0;
78        Self {
79            state,
80            font_size,
81            line_height,
82            metrics: Metrics::new(font_size, line_height),
83            eco: build_ecosystem(),
84            theme: NordTheme,
85            // Nord (the fleet prescribed default) until a config resolves
86            // otherwise — never a hand-written constant, so a fleet
87            // re-point lands here for free.
88            chrome: ChromePalette::prescribed(),
89            last_gen: EditGen(u64::MAX),
90            cached_text: None,
91            highlighter: None,
92        }
93    }
94
95    /// Point the renderer at a theme — the wiring that makes
96    /// `(deftheme :preset …)` real.
97    ///
98    /// `ChromePalette::for_theme` is total over `FleetTheme` (no wildcard
99    /// arm), so a theme added upstream fails this to compile rather than
100    /// silently painting the wrong thing.
101    pub fn set_theme(&mut self, theme: ishou_tokens::FleetTheme) {
102        self.chrome = ChromePalette::for_theme(theme);
103    }
104
105    /// The palette currently painted with.
106    #[must_use]
107    pub fn chrome(&self) -> ChromePalette {
108        self.chrome
109    }
110
111    /// Builder form of [`Self::set_theme`].
112    #[must_use]
113    pub fn with_theme(mut self, theme: ishou_tokens::FleetTheme) -> Self {
114        self.set_theme(theme);
115        self
116    }
117
118    #[must_use]
119    pub fn with_font_size(mut self, font_size: f32, line_height: f32) -> Self {
120        self.font_size = font_size;
121        self.line_height = line_height;
122        self.metrics = Metrics::new(font_size, line_height);
123        self
124    }
125}
126
127impl RenderCallback for GpuRenderer {
128    fn render(&mut self, ctx: &mut RenderContext<'_>) {
129        // ── 1. Read state under lock. The visible text is built ONLY when a
130        //    rebuild is due (the refresh-generation gate): an idle frame reads
131        //    just mode/cursor for the status line and reuses the cached shaped
132        //    buffer below — zero re-highlight, zero re-shape. `rebuild_input`
133        //    is Some((text, path)) exactly when the generation moved.
134        let (rebuild_input, mode, cursor_line, cursor_col, cur_gen) = {
135            let s = self
136                .state
137                .lock()
138                .unwrap_or_else(std::sync::PoisonError::into_inner);
139            let Some(buf) = s.buffers.get(s.active) else {
140                return clear_frame(ctx);
141            };
142            let cur_gen = s.edit_gen();
143            let rebuild = cur_gen != self.last_gen || self.cached_text.is_none();
144            // (rendered text, path, search-match byte ranges INTO that text).
145            // The match ranges ride along with the text they index so the two
146            // cannot be computed against different frames.
147            let rebuild_input: Option<(String, String, Vec<(usize, usize)>)> = if rebuild {
148                // The open file's path drives hikari language resolution.
149                let path = buf
150                    .path
151                    .as_ref()
152                    .map(|p| p.to_string_lossy().into_owned())
153                    .unwrap_or_default();
154                let win = s.layout.active_window().cloned();
155                let top_line = win.as_ref().map_or(0, |w| w.viewport.top_line);
156                let left_column = win.as_ref().map_or(0, |w| w.viewport.left_column) as usize;
157                let visible_lines = win
158                    .as_ref()
159                    .map_or(40, |w| w.viewport.visible_lines.max(20));
160                let visible_columns = win
161                    .as_ref()
162                    .map_or(usize::MAX, |w| w.viewport.visible_columns as usize);
163                let mut out = String::new();
164                // Search matches are DOCUMENT char offsets; `out` is a
165                // RECONSTRUCTED string (each row trimmed of \r\n, char-sliced
166                // to the horizontal window, then \n-joined). There is
167                // therefore NO single base offset relating the two — the map
168                // has to be built per row, while we still know what each row
169                // corresponds to. Converting here, at the one place both
170                // coordinate systems are in scope, is what keeps byte/char
171                // confusion out of the painting code below.
172                let mut match_bytes: Vec<(usize, usize)> = Vec::new();
173                let hl = s.search.highlights();
174                for row in 0..visible_lines {
175                    let ln = top_line + row;
176                    if ln >= buf.line_count() {
177                        break;
178                    }
179                    if let Some(line) = buf.line(ln) {
180                        let trimmed = line.trim_end_matches('\n').trim_end_matches('\r');
181                        // Slice to the visible horizontal window
182                        // `[left_column, left_column + visible_columns)`.
183                        // Char-based so multibyte text stays aligned; long
184                        // lines clip to the window, no glyphon wrap.
185                        let sliced: String = trimmed
186                            .chars()
187                            .skip(left_column)
188                            .take(visible_columns)
189                            .collect();
190                        if !hl.is_empty() {
191                            let seg_byte0 = out.len();
192                            // Document char span this rendered segment covers.
193                            let doc0 = buf
194                                .position_to_char(escriba_core::Position::new(ln, 0))
195                                .unwrap_or(0)
196                                + left_column;
197                            let seg_chars = sliced.chars().count();
198                            // char index -> byte index within this segment.
199                            let bytes: Vec<usize> = sliced
200                                .char_indices()
201                                .map(|(b, _)| b)
202                                .chain(std::iter::once(sliced.len()))
203                                .collect();
204                            for m in hl {
205                                let a = m.start.max(doc0);
206                                let b = m.end.min(doc0 + seg_chars);
207                                if a < b {
208                                    match_bytes.push((
209                                        seg_byte0 + bytes[a - doc0],
210                                        seg_byte0 + bytes[b - doc0],
211                                    ));
212                                }
213                            }
214                        }
215                        out.push_str(&sliced);
216                        out.push('\n');
217                    }
218                }
219                Some((out, path, match_bytes))
220            } else {
221                None
222            };
223            (rebuild_input, s.modal.mode(), s.cursor().line, s.cursor().column, cur_gen)
224        };
225
226        // ── 2. Rebuild the shaped main-text buffer ONLY on a generation
227        //    change; otherwise reuse the cached one. This is the seal
228        //    (theory/ESCRIBA.md §Refresh-Seal): highlight + set_rich_text +
229        //    shape — the frame's dominant cost — run once per edit, never
230        //    per vsync.
231        let palette = self.chrome;
232        let fg = chrome_glyph(palette.text);
233        let width = ctx.width as f32;
234        let height = ctx.height as f32 - self.line_height; // reserve bottom row for status
235        if let Some((text, path, match_bytes)) = rebuild_input {
236            let mut buffer = Buffer::new(&mut ctx.text.font_system, self.metrics);
237            buffer.set_size(&mut ctx.text.font_system, Some(width), Some(height));
238            // hikari: resolve the language, highlight the visible text, paint
239            // each span its Nord color. The span vec is a coverage-complete,
240            // non-overlapping, sorted partition of `text` (the SpanSink
241            // invariant), so each (slice, color) run is a valid set_rich_text
242            // item. Offsets are self-consistent (highlight == render string).
243            let base = Attrs::new().family(Family::Monospace);
244            // hikari incremental (M2): reuse the per-path LineCache and re-lex
245            // only the lines that changed since the last frame (the LineState
246            // fixpoint). A language switch (path change) rebuilds the cache; a
247            // scroll re-lexes the newly-visible window (graceful degrade). This
248            // is byte-identical to the one-shot highlighter it replaces.
249            if self.highlighter.as_ref().is_none_or(|(p, _)| p != &path) {
250                self.highlighter =
251                    Some((path.clone(), self.eco.incremental_highlighter_for_path(&path)));
252            }
253            let hl = &mut self
254                .highlighter
255                .as_mut()
256                .expect("highlighter set immediately above")
257                .1;
258            let spans = hl.highlight(&text);
259            // Overlay search matches on the syntax partition. Each syntax
260            // span is cut at any match boundary crossing it and the matched
261            // piece is recoloured; the result is still coverage-complete,
262            // non-overlapping and sorted, which is what set_rich_text
263            // requires — splitting a partition preserves that, replacing it
264            // would not.
265            let search_color = chrome_glyph(self.chrome.warning);
266            let runs: Vec<(&str, Attrs)> = spans
267                .iter()
268                .flat_map(|sp| {
269                    let syntax = base.clone().color(hl_to_glyph(self.theme.color(sp.class)));
270                    split_on_matches(sp.span.range(), &match_bytes)
271                        .into_iter()
272                        .filter_map(|(r, is_match)| {
273                            text.get(r).map(|slice| {
274                                (
275                                    slice,
276                                    if is_match {
277                                        base.clone().color(search_color)
278                                    } else {
279                                        syntax.clone()
280                                    },
281                                )
282                            })
283                        })
284                        .collect::<Vec<_>>()
285                })
286                .collect();
287            buffer.set_rich_text(&mut ctx.text.font_system, runs, &base, Shaping::Advanced, None);
288            buffer.shape_until_scroll(&mut ctx.text.font_system, false);
289            self.cached_text = Some(buffer);
290            self.last_gen = cur_gen;
291        }
292        let buffer = self
293            .cached_text
294            .as_ref()
295            .expect("cached_text is built on the first frame (last_gen inits to u64::MAX)");
296
297        // Status line — rendered as its own glyphon buffer. The mode is the
298        // BORN fleet mode glyph (`ishou_tokens::EscribaSignals`) + escriba's
299        // canonical uppercase mode label.
300        let signals = EscribaSignals::prescribed();
301        let status = format!(
302            " {} {}  {}:{}  escriba v{} ",
303            mode_glyph(&signals, mode).render(SignalMode::Glyph),
304            mode.as_str(),
305            cursor_line + 1,
306            cursor_col + 1,
307            env!("CARGO_PKG_VERSION")
308        );
309        let mut status_buf = Buffer::new(&mut ctx.text.font_system, self.metrics);
310        status_buf.set_size(
311            &mut ctx.text.font_system,
312            Some(width),
313            Some(self.line_height * 2.0),
314        );
315        status_buf.set_text(
316            &mut ctx.text.font_system,
317            &status,
318            &Attrs::new().family(Family::Monospace),
319            Shaping::Advanced,
320        );
321        status_buf.shape_until_scroll(&mut ctx.text.font_system, false);
322
323        let status_color = chrome_glyph(palette.info);
324
325        let text_areas = [
326            TextArea {
327                buffer,
328                left: 8.0,
329                top: 8.0,
330                scale: 1.0,
331                bounds: TextBounds {
332                    left: 0,
333                    top: 0,
334                    right: ctx.width as i32,
335                    bottom: (height as i32).max(0),
336                },
337                default_color: fg,
338                custom_glyphs: &[],
339            },
340            TextArea {
341                buffer: &status_buf,
342                left: 8.0,
343                top: (ctx.height as f32 - self.line_height - 4.0).max(0.0),
344                scale: 1.0,
345                bounds: TextBounds {
346                    left: 0,
347                    top: (ctx.height as i32 - self.line_height as i32 - 4).max(0),
348                    right: ctx.width as i32,
349                    bottom: ctx.height as i32,
350                },
351                default_color: status_color,
352                custom_glyphs: &[],
353            },
354        ];
355
356        if let Err(e) = ctx.text.prepare(
357            &ctx.gpu.device,
358            &ctx.gpu.queue,
359            ctx.width,
360            ctx.height,
361            text_areas,
362        ) {
363            tracing::warn!(error = %e, "glyphon prepare failed");
364            return clear_frame(ctx);
365        }
366
367        // ── 3. Encode frame. ───────────────────────────────────────────
368        let mut encoder = ctx
369            .gpu
370            .device
371            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
372                label: Some("escriba frame"),
373            });
374        {
375            let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
376                label: Some("escriba main pass"),
377                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
378                    view: ctx.surface_view,
379                    resolve_target: None,
380                    ops: wgpu::Operations {
381                        load: wgpu::LoadOp::Clear(ground_bg()),
382                        store: wgpu::StoreOp::Store,
383                    },
384                })],
385                depth_stencil_attachment: None,
386                timestamp_writes: None,
387                occlusion_query_set: None,
388            });
389            if let Err(e) = ctx.text.render(&mut pass) {
390                tracing::warn!(error = %e, "glyphon render failed");
391            }
392        }
393        ctx.gpu.queue.submit(std::iter::once(encoder.finish()));
394    }
395
396    fn resize(&mut self, width: u32, height: u32) {
397        if let Ok(mut s) = self.state.lock() {
398            // Monospace cell width estimate — glyphon advance for the
399            // Family::Monospace face is ≈ 0.6 × font_size. Used to derive a
400            // visible-column count so the horizontal-scroll window tracks the
401            // real window width (mirrors the visible-line derivation below).
402            let cell_w = (self.font_size * 0.6).max(1.0);
403            for w in &mut s.layout.windows {
404                w.rect.width = width;
405                w.rect.height = height;
406                // Rough visible-line count from height / line_height.
407                let lh = self.line_height.max(1.0);
408                w.viewport.visible_lines = ((height as f32 / lh).max(1.0) as u32).saturating_sub(1);
409                // Rough visible-column count from width / cell_width.
410                w.viewport.visible_columns = (width as f32 / cell_w).max(1.0) as u32;
411            }
412        }
413    }
414}
415
416/// The highlight registry escriba renders through: **tree-sitter grammars
417/// (hikari-ts) take precedence** for the languages they cover, and the zero-dep
418/// table backend fills every other language. So `.rs` gets real tree-sitter
419/// highlighting while `.py` / `.lisp` / `.json` / … get the batteries-included
420/// table lexer — and both flow through the same coverage-complete `HlClass`
421/// partition. Registration order is load-bearing: `Ecosystem::resolve` returns
422/// the first matching plugin, so tree-sitter (registered first) wins for its
423/// languages; the table backend is skipped for any language tree-sitter already
424/// covers (no duplicate). If the tree-sitter host fails to build, the table
425/// backend covers everything — never a panic, never an empty registry.
426///
427/// A third tier registers last: [`crate::langs::escriba_local`], the languages
428/// escriba serves that the fleet spine does not ship yet (today: blue). Last
429/// means an upstream hikari backend for the same language always wins, so a
430/// local table retires itself the day hikari grows one — no edit here, and no
431/// window where the two disagree.
432///
433/// Public because the registry IS escriba's language surface: a test that asks
434/// "does the editor know this language?" must be able to ask the same object
435/// the renderer holds, not a reconstruction of it.
436#[must_use]
437pub fn build_ecosystem() -> Ecosystem {
438    let mut eco = Ecosystem::new();
439    let mut covered: Vec<Language> = Vec::new();
440    if let Ok(host) = hikari_ts::TreeSitterHost::builtin() {
441        for p in host.plugins() {
442            covered.push(p.language());
443            eco.register(p);
444        }
445    }
446    for p in hikari_core::langs::builtins() {
447        if !covered.contains(&p.language()) {
448            covered.push(p.language());
449            eco.register(p);
450        }
451    }
452    for p in crate::langs::escriba_local() {
453        if !covered.contains(&p.language()) {
454            eco.register(p);
455        }
456    }
457    eco
458}
459
460/// Utility — clear the frame to Nord background. Used on error paths.
461fn clear_frame(ctx: &mut RenderContext<'_>) {
462    let mut encoder = ctx
463        .gpu
464        .device
465        .create_command_encoder(&wgpu::CommandEncoderDescriptor {
466            label: Some("escriba clear"),
467        });
468    {
469        let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
470            label: Some("escriba clear pass"),
471            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
472                view: ctx.surface_view,
473                resolve_target: None,
474                ops: wgpu::Operations {
475                    load: wgpu::LoadOp::Clear(ground_bg()),
476                    store: wgpu::StoreOp::Store,
477                },
478            })],
479            depth_stencil_attachment: None,
480            timestamp_writes: None,
481            occlusion_query_set: None,
482        });
483    }
484    ctx.gpu.queue.submit(std::iter::once(encoder.finish()));
485}
486
487/// The editor ground as `wgpu::Color`, resolved from the fleet-prescribed
488/// theme's `background` role. Gamma-correct: the sRGB token is promoted
489/// through `ishou_tokens`' typed sRGB→linear path so it composites
490/// correctly on the linear-storage surface.
491fn ground_bg() -> wgpu::Color {
492    let c = ChromePalette::prescribed().background;
493    Srgb::from(c).to_linear().with_alpha(1.0).into()
494}
495
496/// ishou `Rgb` → glyphon `Color` (sRGB u8 RGBA, opaque). Theme-agnostic —
497/// was `vellum_glyph`, back when the paint path was hardwired to Vellum.
498/// Cut `range` wherever a match in `matches` starts or ends inside it.
499///
500/// Returns `(sub_range, is_match)` pieces that are contiguous, in order, and
501/// exactly cover `range` — the property `set_rich_text` depends on. `matches`
502/// are byte ranges into the SAME string `range` indexes.
503///
504/// Splitting the existing syntax partition (rather than building a second one)
505/// is what keeps the two colour sources composable: a match inside a string
506/// literal recolours only the matched bytes and the literal keeps its colour
507/// either side.
508fn split_on_matches(
509    range: std::ops::Range<usize>,
510    matches: &[(usize, usize)],
511) -> Vec<(std::ops::Range<usize>, bool)> {
512    let mut cuts: Vec<usize> = vec![range.start, range.end];
513    for &(a, b) in matches {
514        if a > range.start && a < range.end {
515            cuts.push(a);
516        }
517        if b > range.start && b < range.end {
518            cuts.push(b);
519        }
520    }
521    if cuts.len() == 2 {
522        // No boundary crosses this span — the common case, so avoid the
523        // sort/dedup entirely.
524        let hit = matches.iter().any(|&(a, b)| a <= range.start && b >= range.end);
525        return vec![(range, hit)];
526    }
527    cuts.sort_unstable();
528    cuts.dedup();
529    cuts.windows(2)
530        .map(|w| {
531            let (a, b) = (w[0], w[1]);
532            let hit = matches.iter().any(|&(ms, me)| ms <= a && me >= b);
533            (a..b, hit)
534        })
535        .collect()
536}
537
538fn chrome_glyph(c: Rgb) -> GlyphColor {
539    GlyphColor::rgba(c.r, c.g, c.b, 0xFF)
540}
541
542/// hikari `Rgb` (sRGB u8) → glyphon `Color` (opaque) — the syntax-span paint.
543fn hl_to_glyph(c: HlRgb) -> GlyphColor {
544    GlyphColor::rgba(c.r, c.g, c.b, 0xFF)
545}
546
547/// Mode indicator color — used by higher-layer rendering paths that want a
548/// glance-readable color. Named by ROLE so the hue follows the active theme:
549/// Normal info, Insert success, Visual accent, Command warning.
550#[must_use]
551pub fn mode_color(mode: Mode) -> Rgb {
552    let c = ChromePalette::prescribed();
553    match mode {
554        Mode::Insert => c.success,
555        Mode::Command => c.warning,
556        Mode::Visual | Mode::VisualLine => c.accent,
557        Mode::Normal => c.info,
558    }
559}
560
561/// The [`CursorShape`](escriba_core::CursorShape) the GPU backend should
562/// draw for `mode`. Derived from the single typed `Mode::cursor_shape`
563/// mapping shared with the TUI backend — so the GPU cursor (once it gains a
564/// dedicated glyph; today the buffer text carries the caret) renders the
565/// same shape the TUI does for any given mode. Exposed now so the shape is
566/// a typed value at the GPU layer, not a renderer-local literal later.
567#[must_use]
568pub fn cursor_shape(mode: Mode) -> escriba_core::CursorShape {
569    mode.cursor_shape()
570}
571
572/// Map an editor [`Mode`] to its fleet [`Signal`](ishou_tokens::Signal)
573/// from [`EscribaSignals`].
574///
575/// `VisualLine` shares `mode_visual` with `Visual` — the fleet signal set
576/// has one visual signal, matching how [`mode_color`] groups the two.
577#[must_use]
578pub fn mode_glyph(sig: &EscribaSignals, mode: Mode) -> &ishou_tokens::Signal {
579    match mode {
580        Mode::Normal => &sig.mode_normal,
581        Mode::Insert => &sig.mode_insert,
582        Mode::Visual | Mode::VisualLine => &sig.mode_visual,
583        Mode::Command => &sig.mode_command,
584    }
585}
586
587#[cfg(test)]
588mod tests {
589
590    // ── search-highlight overlay ──────────────────────────────────────
591    //
592    // set_rich_text requires a coverage-complete, non-overlapping, sorted
593    // partition. Splitting the syntax partition preserves that; these pin it,
594    // because a violation shows up as garbled text rather than a panic.
595
596    /// The invariant, asserted directly: pieces are contiguous, ordered, and
597    /// exactly cover the input range.
598    fn assert_partition(range: std::ops::Range<usize>, out: &[(std::ops::Range<usize>, bool)]) {
599        assert!(!out.is_empty(), "a range must yield at least one piece");
600        assert_eq!(out[0].0.start, range.start, "starts at the range start");
601        assert_eq!(out[out.len() - 1].0.end, range.end, "ends at the range end");
602        for w in out.windows(2) {
603            assert_eq!(w[0].0.end, w[1].0.start, "pieces are contiguous, no gap or overlap");
604        }
605    }
606
607    #[test]
608    fn a_span_with_no_match_is_returned_whole() {
609        let out = split_on_matches(0..10, &[]);
610        assert_eq!(out.len(), 1, "no needless splitting");
611        assert!(!out[0].1);
612        assert_partition(0..10, &out);
613    }
614
615    #[test]
616    fn a_match_covering_the_whole_span_marks_it_without_splitting() {
617        let out = split_on_matches(4..8, &[(0, 20)]);
618        assert_eq!(out.len(), 1);
619        assert!(out[0].1, "fully covered span is a match");
620        assert_partition(4..8, &out);
621    }
622
623    #[test]
624    fn a_match_starting_mid_span_splits_it_in_two() {
625        // Syntax span 0..10, match 5..10 -> [0..5 plain][5..10 match]
626        let out = split_on_matches(0..10, &[(5, 10)]);
627        assert_eq!(out.len(), 2);
628        assert_eq!(out[0], (0..5, false));
629        assert_eq!(out[1], (5..10, true));
630        assert_partition(0..10, &out);
631    }
632
633    #[test]
634    fn a_match_inside_a_span_splits_it_in_three() {
635        // This is the case that matters: a match inside a string literal must
636        // recolour only the matched bytes, leaving the literal coloured
637        // either side.
638        let out = split_on_matches(0..10, &[(3, 6)]);
639        assert_eq!(out.len(), 3);
640        assert_eq!(out[0], (0..3, false));
641        assert_eq!(out[1], (3..6, true));
642        assert_eq!(out[2], (6..10, false));
643        assert_partition(0..10, &out);
644    }
645
646    #[test]
647    fn two_matches_in_one_span_both_split() {
648        let out = split_on_matches(0..20, &[(2, 4), (10, 12)]);
649        assert_partition(0..20, &out);
650        let hits: Vec<_> = out.iter().filter(|(_, m)| *m).map(|(r, _)| r.clone()).collect();
651        assert_eq!(hits, vec![2..4, 10..12]);
652    }
653
654    #[test]
655    fn a_match_entirely_outside_the_span_changes_nothing() {
656        let out = split_on_matches(10..20, &[(0, 5)]);
657        assert_eq!(out.len(), 1);
658        assert!(!out[0].1);
659        assert_partition(10..20, &out);
660    }
661
662    #[test]
663    fn a_match_touching_the_span_edge_does_not_create_an_empty_piece() {
664        // Boundary exactly at the edge must not emit a zero-width run.
665        for m in [(0usize, 10usize), (10, 20)] {
666            let out = split_on_matches(10..20, &[m]);
667            assert_partition(10..20, &out);
668            assert!(out.iter().all(|(r, _)| r.start < r.end), "no empty piece for {m:?}");
669        }
670    }
671
672    #[test]
673    fn adjacent_matches_do_not_produce_duplicate_cuts() {
674        // Two matches meeting at 5 must yield one cut there, not two.
675        let out = split_on_matches(0..10, &[(0, 5), (5, 10)]);
676        assert_partition(0..10, &out);
677        assert!(out.iter().all(|(r, _)| r.start < r.end));
678        assert!(out.iter().all(|(_, m)| *m), "both halves are matches");
679    }
680    use super::*;
681    use escriba_buffer::BufferSet;
682
683    #[test]
684    fn ground_is_the_prescribed_theme_promoted_to_linear() {
685        let bg = ground_bg();
686        // Was pinned to Vellum's warm parchment (night0 #16140E, r >= g >= b).
687        // The prescribed theme is now Nord, whose ground is COOL (b >= r), so
688        // the old warmth assertion was theme-specific and had to go. What is
689        // actually invariant — and worth asserting — is that the ground is a
690        // dark, opaque, gamma-correct promotion of the theme's own
691        // background role.
692        let want = Srgb::from(ChromePalette::prescribed().background)
693            .to_linear()
694            .with_alpha(1.0);
695        let want: wgpu::Color = want.into();
696        assert!((bg.r - want.r).abs() < 1e-6, "r {} != {}", bg.r, want.r);
697        assert!((bg.g - want.g).abs() < 1e-6, "g {} != {}", bg.g, want.g);
698        assert!((bg.b - want.b).abs() < 1e-6, "b {} != {}", bg.b, want.b);
699        assert_eq!(bg.a, 1.0);
700        // Dark ground: an editor background must stay well below mid-grey in
701        // linear space whatever the theme.
702        assert!(bg.r < 0.1 && bg.g < 0.1 && bg.b < 0.1, "ground is not dark: {bg:?}");
703    }
704
705    #[test]
706    fn renderer_construction_is_cheap() {
707        let mut bufs = BufferSet::new();
708        let id = bufs.scratch("hello\n");
709        let state = Arc::new(Mutex::new(EditorState::new_with_buffer(bufs, id)));
710        let _r = GpuRenderer::new(state);
711    }
712
713    /// Phase 4: the render Ecosystem serves `.rs` from the **tree-sitter**
714    /// backend (hikari-ts) and other languages from the table backend — both a
715    /// coverage-complete `HlClass` partition. Proves real tree-sitter
716    /// highlighting is wired into the live render path (not just the table lexer).
717    #[test]
718    fn ecosystem_uses_tree_sitter_for_rust_and_table_for_the_rest() {
719        use hikari_core::{HlClass, Language};
720        let eco = build_ecosystem();
721        // .rs resolves to a grammar and produces real (non-Plain) classification.
722        assert_eq!(eco.resolve("src/main.rs"), Language("rust"));
723        let rs = eco
724            .highlighter_for_path("src/main.rs")
725            .highlight("fn main() { let x = 42; }");
726        assert!(
727            rs.iter().any(|s| s.class != HlClass::Plain),
728            "rust must be really highlighted (tree-sitter or table)",
729        );
730        // Python is also served (tree-sitter, once hikari-ts ships that grammar;
731        // the table backend covers it otherwise) — either way it classifies.
732        assert_eq!(eco.resolve("app.py"), Language("python"));
733        // A tree-sitter-uncovered language still resolves via the table backend.
734        assert_eq!(eco.resolve("init.lisp"), Language("lisp"));
735        // An unknown extension is still total (plain text, never a panic).
736        assert_eq!(eco.resolve("notes.xyz"), hikari_core::PLAIN_TEXT);
737    }
738
739    #[test]
740    fn mode_colors_differ_by_mode() {
741        let n = mode_color(Mode::Normal);
742        let i = mode_color(Mode::Insert);
743        let v = mode_color(Mode::Visual);
744        assert_ne!((n.r, n.g, n.b), (i.r, i.g, i.b));
745        assert_ne!((n.r, n.g, n.b), (v.r, v.g, v.b));
746    }
747
748    #[test]
749    fn cursor_shape_tracks_mode() {
750        use escriba_core::CursorShape;
751        assert_eq!(cursor_shape(Mode::Normal), CursorShape::Block);
752        assert_eq!(cursor_shape(Mode::Command), CursorShape::Block);
753        assert_eq!(cursor_shape(Mode::Insert), CursorShape::Bar);
754        assert_eq!(cursor_shape(Mode::Visual), CursorShape::Underline);
755        assert_eq!(cursor_shape(Mode::VisualLine), CursorShape::Underline);
756    }
757
758    /// Mode pills map to ROLES, not to one theme's hexes. This test used to
759    /// pin the four Vellum values (`#94BBB8` …), which is precisely why it
760    /// went red the moment the fleet theme moved — a test asserting a
761    /// theme's spelling has to be rewritten on every theme change, and is
762    /// no evidence the mapping is right. Asserting role identity instead
763    /// survives the move AND still catches a mis-wired pill.
764    #[test]
765    fn mode_colors_are_role_pills() {
766        let c = ChromePalette::prescribed();
767        assert_eq!(mode_color(Mode::Normal).hex(), c.info.hex(), "Normal = info");
768        assert_eq!(mode_color(Mode::Insert).hex(), c.success.hex(), "Insert = success");
769        assert_eq!(mode_color(Mode::Visual).hex(), c.accent.hex(), "Visual = accent");
770        assert_eq!(mode_color(Mode::Command).hex(), c.warning.hex(), "Command = warning");
771
772        // The four pills must be mutually distinct, or the mode is not
773        // glance-readable regardless of which theme is active.
774        let mut seen = std::collections::BTreeSet::new();
775        for m in [Mode::Normal, Mode::Insert, Mode::Visual, Mode::Command] {
776            assert!(seen.insert(mode_color(m).hex()), "{m:?} duplicates another pill");
777        }
778    }
779
780    /// Forcing function: the status-line mode glyphs are sourced from the
781    /// fleet `EscribaSignals` vocabulary, not hand-picked literals. Pins
782    /// the geometric `Glyph`-mode marks so drift in either escriba or
783    /// ishou surfaces here.
784    #[test]
785    fn mode_glyphs_are_fleet_signals() {
786        let sig = EscribaSignals::prescribed();
787        assert_eq!(mode_glyph(&sig, Mode::Normal).render(SignalMode::Glyph), "◆");
788        assert_eq!(mode_glyph(&sig, Mode::Insert).render(SignalMode::Glyph), "▸");
789        assert_eq!(mode_glyph(&sig, Mode::Visual).render(SignalMode::Glyph), "▮");
790        assert_eq!(
791            mode_glyph(&sig, Mode::VisualLine).render(SignalMode::Glyph),
792            "▮"
793        );
794        assert_eq!(
795            mode_glyph(&sig, Mode::Command).render(SignalMode::Glyph),
796            ":"
797        );
798    }
799
800    /// Fleet convergence guard: escriba's GPU chrome paints whatever
801    /// `ChromePalette::prescribed()` resolves, which is
802    /// `FleetTheme::prescribed_default()` BY CONSTRUCTION — so this Guard
803    /// cannot be satisfied by a stale hand-written constant.
804    ///
805    /// It previously hardcoded `FleetTheme::Vellum` to match a paint path
806    /// hardwired to `VellumPalette::vellum()`. When the fleet moved its
807    /// prescribed theme to PlemeDark (Nord) this went RED — correctly, since
808    /// the GPU backend really was painting the wrong theme while the TUI
809    /// face and the rest of the fleet (mado, tear, frostmourne, …) moved on.
810    /// Smallest real editor state — a scratch buffer. The theming tests
811    /// care about the palette, not the buffer, but GpuRenderer owns state.
812    fn test_renderer() -> GpuRenderer {
813        let mut bufs = escriba_buffer::BufferSet::new();
814        let id = bufs.scratch("");
815        GpuRenderer::new(Arc::new(Mutex::new(EditorState::new_with_buffer(bufs, id))))
816    }
817
818    #[test]
819    fn default_theme_is_the_fleet_prescribed_nord() {
820        // Nord is the default because the FLEET says so — asserted against
821        // FleetTheme::prescribed_default(), never a hand-written "nord",
822        // so a fleet re-point cannot leave escriba silently behind.
823        let r = test_renderer();
824        let want = ChromePalette::for_theme(ishou_tokens::FleetTheme::prescribed_default());
825        assert_eq!(r.chrome().hex_tuple(), want.hex_tuple());
826    }
827
828    #[test]
829    fn set_theme_actually_changes_what_is_painted() {
830        // The wiring this exists to prove: before it, every paint site
831        // called ChromePalette::prescribed() directly, so (deftheme :preset)
832        // resolved to a real FleetTheme that NOTHING consumed. If set_theme
833        // ever stops reaching the paint path, this fails.
834        let mut r = test_renderer();
835        let before = r.chrome().hex_tuple();
836        r.set_theme(ishou_tokens::FleetTheme::Vellum);
837        let after = r.chrome().hex_tuple();
838        assert_ne!(
839            before, after,
840            "switching to Vellum must change the painted palette"
841        );
842        assert_eq!(
843            after,
844            ChromePalette::for_theme(ishou_tokens::FleetTheme::Vellum).hex_tuple()
845        );
846        // And it is reversible — a theme is a value, not a one-way latch.
847        r.set_theme(ishou_tokens::FleetTheme::prescribed_default());
848        assert_eq!(r.chrome().hex_tuple(), before);
849    }
850
851    #[test]
852    fn escriba_gpu_chrome_converges_with_fleet() {
853        use ishou_tokens::{FleetTheme, convergence::Guard};
854        let chrome_theme = FleetTheme::prescribed_default();
855        Guard::for_app("escriba-render").expect_theme(chrome_theme).run();
856    }
857}