neovide 0.17.6

Neovide: No Nonsense Neovim Gui
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
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;

use log::warn;

use crate::bridge::GridLineCell;
use crate::editor::AnchorInfo;
use crate::editor::DrawCommand;
use crate::editor::DrawCommandBatcher;
use crate::editor::grid::CharacterGrid;
use crate::editor::style::Style;
use crate::renderer::WindowDrawCommand;
use crate::renderer::box_drawing;
#[cfg(target_os = "macos")]
use crate::renderer::rendered_window::BASE_GRID_ID;
use crate::units::GridRect;
use crate::units::GridSize;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WindowType {
    Editor,
    Message { scrolled: bool },
}

/// The window identity and outer rectangle supplied by win_pos.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TiledWindowLayout {
    pub window: u64,
    pub rect: GridRect<u64>,
}

/// Buffer positions reported by win_viewport, independent of grid placement.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WindowViewport {
    pub window: u64,
    pub top_line: f64,
    pub bottom_line: f64,
    pub current_line: f64,
    pub line_count: Option<f64>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Line {
    pub text: String,
    fragments: Vec<LineFragmentData>,
    cells: Option<Vec<String>>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct LineFragmentData {
    text_range: Range<u32>,
    style: Option<Arc<Style>>,
    cells: Range<u32>,
    words: Vec<WordData>,
}

#[derive(Debug, Default, Clone, PartialEq)]
pub struct WordData {
    text_offset: u32,
    cell: u32,
    cluster_sizes: Vec<u8>,
}

pub struct LineFragment<'a> {
    pub style: &'a Option<Arc<Style>>,
    pub text: &'a str,
    pub cells: &'a Range<u32>,

    data: &'a LineFragmentData,
}

pub struct Word<'a> {
    pub text: &'a str,
    pub cell: u32,

    cluster_sizes: &'a [u8],
}

impl Line {
    pub fn fragments(&self) -> impl Iterator<Item = LineFragment<'_>> {
        self.fragments.iter().map(|fragment| {
            let range = fragment.text_range.start as usize..fragment.text_range.end as usize;
            LineFragment {
                style: &fragment.style,
                text: &self.text[range],
                cells: &fragment.cells,
                data: fragment,
            }
        })
    }

    pub fn cells(&self) -> Option<&[String]> { self.cells.as_deref() }

    #[cfg(test)]
    pub(crate) fn empty() -> Self {
        Self { text: String::new(), fragments: Vec::new(), cells: None }
    }
}

impl LineFragment<'_> {
    pub fn words(&self) -> impl Iterator<Item = Word<'_>> {
        self.data.words.iter().map(|word| {
            let size: usize = word.cluster_sizes.iter().map(|v| *v as usize).sum();
            let cluster_sizes = &word.cluster_sizes;
            let start = word.text_offset as usize;
            let end = start + size;
            let text = &self.text[start..end];
            Word { text, cell: word.cell, cluster_sizes }
        })
    }
}

impl<'a> Word<'a> {
    pub fn new(text: &'a str, cluster_sizes: &'a [u8]) -> Self {
        Self { text, cell: 0, cluster_sizes }
    }

    pub fn grapheme_clusters(&self) -> impl Iterator<Item = (usize, &'a str)> + Clone {
        self.cluster_sizes.iter().enumerate().filter(|(_, size)| **size > 0).scan(
            0,
            |current_pos, (cell_nr, size)| {
                let start = *current_pos;
                *current_pos += *size as u32;
                Some((cell_nr, &self.text[start as usize..*current_pos as usize]))
            },
        )
    }
}

pub struct Window {
    grid_id: u64,
    grid: CharacterGrid,
    pub window_type: WindowType,

    pub anchor_info: Option<AnchorInfo>,
    grid_position: (f64, f64),
    visible: bool,
    tiled_layout: Option<TiledWindowLayout>,
    viewport: Option<WindowViewport>,
    viewport_top_margin: u64,
    viewport_bottom_margin: u64,
}

impl Window {
    pub fn new(
        grid_id: u64,
        window_type: WindowType,
        anchor_info: Option<AnchorInfo>,
        grid_position: (f64, f64),
        grid_size: (u64, u64),
        draw_command_batcher: &mut DrawCommandBatcher,
    ) -> Window {
        let window = Window {
            grid_id,
            grid: CharacterGrid::new((grid_size.0 as usize, grid_size.1 as usize)),
            window_type,
            anchor_info,
            grid_position,
            visible: true,
            tiled_layout: None,
            viewport: None,
            viewport_top_margin: 0,
            viewport_bottom_margin: 0,
        };
        window.send_updated_position(draw_command_batcher);
        window
    }

    pub fn new_tiled(
        grid_id: u64,
        layout: TiledWindowLayout,
        batcher: &mut DrawCommandBatcher,
    ) -> Self {
        let mut window = Self::new(
            grid_id,
            WindowType::Editor,
            None,
            (layout.rect.min.x as f64, layout.rect.min.y as f64),
            (layout.rect.size().width, layout.rect.size().height),
            batcher,
        );

        window.set_tiled_layout(layout);

        window
    }

    /// Returns a tiled layout only while the grid is displayed as an editor window.
    #[cfg(target_os = "macos")]
    pub fn visible_tiled_layout(&self) -> Option<TiledWindowLayout> {
        if !self.visible
            || self.grid_id == BASE_GRID_ID
            || self.window_type != WindowType::Editor
            || self.anchor_info.is_some()
        {
            return None;
        }

        self.tiled_layout.filter(|layout| !layout.rect.is_empty())
    }

    #[cfg(target_os = "macos")]
    pub fn viewport(&self) -> Option<WindowViewport> { self.viewport }

    pub fn set_viewport(&mut self, viewport: WindowViewport) { self.viewport = Some(viewport); }

    #[cfg(target_os = "macos")]
    pub fn clear_viewport_for_window(&mut self, window: u64) {
        if self.viewport.is_some_and(|viewport| viewport.window == window) {
            self.viewport = None;
        }
    }

    fn set_tiled_layout(&mut self, layout: TiledWindowLayout) {
        let previous_window = self
            .tiled_layout
            .map(|layout| layout.window)
            .or_else(|| self.viewport.map(|viewport| viewport.window));

        if previous_window.is_some_and(|window| window != layout.window) {
            self.viewport = None;
            self.viewport_top_margin = 0;
            self.viewport_bottom_margin = 0;
        }

        self.tiled_layout = Some(layout);
        self.window_type = WindowType::Editor;
    }

    pub fn position_tiled(&mut self, batcher: &mut DrawCommandBatcher, layout: TiledWindowLayout) {
        self.set_tiled_layout(layout);
        // The grid's contents and size are owned by grid_resize. Neovim can emit win_pos with a
        // window size that the grid has not been reallocated to yet, e.g. a temporary `:split`
        // followed by a UI flush from `:write` and then `:close`. Resizing to that size would drop
        // rows that Neovim considers drawn and will not resend.
        self.position(
            batcher,
            None,
            (self.get_width(), self.get_height()),
            (layout.rect.min.x as f64, layout.rect.min.y as f64),
        );

        self.show(batcher);
    }

    fn send_command(&self, batcher: &mut DrawCommandBatcher, command: WindowDrawCommand) {
        batcher.queue(DrawCommand::Window { grid_id: self.grid_id, command });
    }

    fn send_updated_position(&self, batcher: &mut DrawCommandBatcher) {
        self.send_command(
            batcher,
            WindowDrawCommand::Position {
                grid_position: self.grid_position,
                grid_size: (self.grid.width as u64, self.grid.height as u64),
                anchor_info: self.anchor_info.clone(),
                window_type: self.window_type,
            },
        );
    }

    pub fn get_cursor_grid_cell(
        &self,
        window_left: u64,
        window_top: u64,
    ) -> (String, Option<Arc<Style>>, bool) {
        let grid_cell = self
            .grid
            .get_cell(window_left as usize, window_top as usize)
            .map_or((" ".to_string(), None), |(character, style)| {
                (character.clone(), style.clone())
            });

        let double_width = self
            .grid
            .get_cell(window_left as usize + 1, window_top as usize)
            .map(|(character, _)| character.is_empty())
            .unwrap_or_default();

        (grid_cell.0, grid_cell.1, double_width)
    }

    pub fn get_width(&self) -> u64 { self.grid.width as u64 }

    pub fn get_height(&self) -> u64 { self.grid.height as u64 }

    pub fn get_grid_position(&self) -> (f64, f64) { self.grid_position }

    #[cfg(target_os = "macos")]
    pub fn viewport_margins(&self) -> (u64, u64) {
        (self.viewport_top_margin, self.viewport_bottom_margin)
    }

    pub fn set_viewport_margins(&mut self, top: u64, bottom: u64) {
        self.viewport_top_margin = top;
        self.viewport_bottom_margin = bottom;
    }

    pub fn position(
        &mut self,
        batcher: &mut DrawCommandBatcher,
        anchor_info: Option<AnchorInfo>,
        grid_size: (u64, u64),
        grid_position: (f64, f64),
    ) {
        self.grid.resize((grid_size.0 as usize, grid_size.1 as usize));
        self.anchor_info = anchor_info;
        if self.anchor_info.is_some() || self.window_type != WindowType::Editor {
            self.tiled_layout = None;
        }
        self.grid_position = grid_position;
        self.send_updated_position(batcher);
    }

    pub fn resize(&mut self, batcher: &mut DrawCommandBatcher, new_size: (u64, u64)) {
        self.grid.resize((new_size.0 as usize, new_size.1 as usize));
        self.send_updated_position(batcher);
    }

    fn modify_grid(
        &mut self,
        row_index: usize,
        column_pos: &mut usize,
        cell: GridLineCell,
        defined_styles: &HashMap<u64, Arc<Style>>,
        previous_style: &mut Option<Arc<Style>>,
    ) {
        // Get the defined style from the style list.
        let style = match cell.highlight_id {
            Some(0) => None,
            Some(style_id) => defined_styles.get(&style_id).cloned(),
            None => previous_style.clone(),
        };

        let text = cell.text;
        if let Some(times) = cell.repeat {
            // Repeats of zero times should be ignored, they are mostly useful for terminal Neovim
            // to distinguish between empty lines and lines ending with spaces.
            if times == 0 {
                return;
            }

            for _ in 0..times.saturating_sub(1) {
                if let Some(cell) = self.grid.get_cell_mut(*column_pos, row_index) {
                    *cell = (text.clone(), style.clone());
                }
                *column_pos += 1;
            }
        };
        if let Some(cell) = self.grid.get_cell_mut(*column_pos, row_index) {
            *cell = (text, style.clone());
        }
        *column_pos += 1;

        *previous_style = style;
    }

    // Build a line fragment for the given row starting from current_start up until the next style
    // change or double width character.
    fn build_line_fragment(
        &self,
        row_index: usize,
        start: usize,
        text: &mut String,
    ) -> (usize, LineFragmentData) {
        let row = self.grid.row(row_index).unwrap();

        let (_, style) = &row[start];

        let mut width = 0u32;
        let mut last_box_char = None;
        let mut text_range = text.len() as u32..text.len() as u32;
        let mut words = Vec::new();
        let mut current_word = WordData::default();

        for (cluster, possible_end_style) in row.iter().take(self.grid.width).skip(start) {
            // Style doesn't match. Draw what we've got.
            if style != possible_end_style {
                break;
            }

            // Box drawing characters are rendered specially; break up the segment such that
            // repeated box drawing characters are in a segment by themselves
            if box_drawing::is_box_char(cluster) {
                if text_range.is_empty() {
                    last_box_char = Some(cluster)
                }
                if (!text_range.is_empty() && last_box_char.is_none())
                    || last_box_char != Some(cluster)
                {
                    // either we have non-box chars accumulated or this is a different box char
                    // from what we have seen before. Either way, render what we have
                    break;
                }
            } else if last_box_char.is_some() {
                // render the list of box chars we have accumulated so far
                break;
            }

            width += 1;

            // We can't deal with clusters that are longer than 255 bytes, so replace them with spaces.
            // This should only happen if Neovim sends corrupted lines, or maybe in some pathological
            // Unicode combining sequence.
            let cluster = if cluster.len() > 255 { " " } else { cluster };

            if cluster.is_empty() {
                // For double-width char, the empty cell should be part of the current word as a 0 cluster size
                // Or ignored when it's part of whitespace
                if !current_word.cluster_sizes.is_empty() {
                    current_word.cluster_sizes.push(0);
                }
                continue;
            }

            let is_whitespace = cluster.chars().next().is_some_and(|char| char.is_whitespace());
            if is_whitespace {
                if !current_word.cluster_sizes.is_empty() {
                    // Finish the current word
                    words.push(current_word);
                    current_word = WordData::default();
                }
            } else if current_word.cluster_sizes.is_empty() {
                // Properly initialize a new word
                current_word.cell = width - 1;
                current_word.cluster_sizes.push(cluster.len() as u8);
                current_word.text_offset = text.len() as u32 - text_range.start;
            } else {
                current_word.cluster_sizes.push(cluster.len() as u8);
            }

            // Add the grid cell to the cells to render.
            text.push_str(cluster);
            text_range.end += cluster.len() as u32;
        }
        if !current_word.cluster_sizes.is_empty() {
            words.push(current_word);
        }

        let line_fragment = LineFragmentData {
            text_range,
            cells: start as u32..start as u32 + width,
            style: style.clone(),
            words,
        };

        (start + width as usize, line_fragment)
    }

    // Redraw line by calling build_line_fragment starting at 0
    // until current_start is greater than the grid width and sending the resulting
    // fragments as a batch.
    fn redraw_line(&self, batcher: &mut DrawCommandBatcher, row: usize) {
        let mut current_start = 0;
        let mut line_fragments = Vec::new();
        let mut text = String::new();
        while current_start < self.grid.width {
            let (next_start, line_fragment) =
                self.build_line_fragment(row, current_start, &mut text);
            current_start = next_start;
            line_fragments.push(line_fragment);
        }

        let cells = matches!(self.window_type, WindowType::Message { .. })
            .then(|| self.row_cells(row))
            .flatten();

        let line = Line { text, fragments: line_fragments, cells };

        self.send_command(batcher, WindowDrawCommand::DrawLine { row, line });
    }

    fn row_cells(&self, row: usize) -> Option<Vec<String>> {
        self.grid.row(row).map(|line| line.iter().map(|(character, _)| character.clone()).collect())
    }

    pub fn draw_grid_line(
        &mut self,
        batcher: &mut DrawCommandBatcher,
        row: u64,
        column_start: u64,
        cells: Vec<GridLineCell>,
        defined_styles: &HashMap<u64, Arc<Style>>,
    ) {
        let mut previous_style = None;
        let row = row as usize;
        if row < self.grid.height {
            let mut column_pos = column_start as usize;
            for cell in cells {
                self.modify_grid(row, &mut column_pos, cell, defined_styles, &mut previous_style);
            }

            self.redraw_line(batcher, row);
        } else {
            warn!("Draw command out of bounds");
        }
    }

    pub fn draw_centered_text_line(
        &mut self,
        batcher: &mut DrawCommandBatcher,
        row: usize,
        text: &str,
    ) {
        if row >= self.grid.height {
            return;
        }

        for column in 0..self.grid.width {
            if let Some(cell) = self.grid.get_cell_mut(column, row) {
                *cell = (" ".to_string(), None);
            }
        }

        if text.is_empty() {
            self.redraw_line(batcher, row);
            return;
        }

        let text_width = text.chars().count();
        let start_column =
            if text_width >= self.grid.width { 0 } else { (self.grid.width - text_width) / 2 };

        for (offset, ch) in text.chars().enumerate() {
            let column = start_column + offset;
            if column >= self.grid.width {
                break;
            }

            if let Some(cell) = self.grid.get_cell_mut(column, row) {
                *cell = (ch.to_string(), None);
            }
        }

        self.redraw_line(batcher, row);
    }

    pub fn scroll_region(
        &mut self,
        batcher: &mut DrawCommandBatcher,
        region: GridRect<u64>,
        size: GridSize<i64>,
    ) {
        let top = region.min.y;
        let bottom = region.max.y;
        let left = region.min.x;
        let right = region.max.x;
        let rows = size.height;
        let cols = size.width;
        // Scrolls must move the data and send a WindowDrawCommand to move the rendered texture so
        // that future renders draw correctly
        let is_pure_updown = self.grid.scroll_region(
            top as usize,
            bottom as usize,
            left as usize,
            right as usize,
            rows as isize,
            cols as isize,
        );

        self.send_command(
            batcher,
            WindowDrawCommand::Scroll { top, bottom, left, right, rows, cols },
        );

        // There's no need to send any updates for pure up/down scrolling, the actual new lines
        // will be sent later
        if !is_pure_updown {
            let mut top = top as isize;
            let mut bottom = bottom as isize;
            // Send only the scrolled lines
            // neovim will send the rest later
            if rows > 0 {
                bottom -= rows as isize;
            } else {
                top -= rows as isize;
            }

            for row in top..bottom {
                self.redraw_line(batcher, row as usize);
            }
        }
    }

    pub fn clear(&mut self, batcher: &mut DrawCommandBatcher) {
        self.grid.clear();
        self.send_command(batcher, WindowDrawCommand::Clear);
    }

    pub fn redraw(&self, batcher: &mut DrawCommandBatcher) {
        self.send_command(batcher, WindowDrawCommand::Clear);
        // Draw the lines from the bottom up so that underlines don't get overwritten by the line
        // below.
        for row in (0..self.grid.height).rev() {
            self.redraw_line(batcher, row);
        }
    }

    pub fn hide(&mut self, batcher: &mut DrawCommandBatcher) {
        self.visible = false;
        self.send_command(batcher, WindowDrawCommand::Hide);
    }

    pub fn show(&mut self, batcher: &mut DrawCommandBatcher) {
        self.visible = true;
        self.send_command(batcher, WindowDrawCommand::Show);
    }

    pub fn close(&self, batcher: &mut DrawCommandBatcher) {
        self.send_command(batcher, WindowDrawCommand::Close);
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use skia_safe::Color4f;
    use skia_safe::colors;

    use super::*;
    use crate::editor::style::Colors;
    use crate::editor::style::Style;

    fn make_style(color: Color4f) -> Arc<Style> {
        Arc::new(Style::new(Colors {
            foreground: Some(color),
            background: Some(Color4f::new(0.0, 0.0, 0.0, 1.0)),
            special: Some(Color4f::new(0.0, 0.0, 0.0, 1.0)),
        }))
    }

    fn make_window<const WIDTH: usize, const HEIGHT: usize>(
        rows: [[(&str, Option<Color4f>); WIDTH]; HEIGHT],
    ) -> Window {
        let mut grid = CharacterGrid::new((WIDTH, HEIGHT));
        for (y, row) in rows.iter().enumerate() {
            for (x, (ch, color)) in row.iter().enumerate() {
                *grid.get_cell_mut(x, y).unwrap() = (ch.to_string(), color.map(make_style));
            }
        }
        Window {
            grid_id: 1,
            grid,
            window_type: WindowType::Editor,
            anchor_info: None,
            grid_position: (0.0, 0.0),
            visible: true,
            tiled_layout: None,
            viewport: None,
            viewport_top_margin: 0,
            viewport_bottom_margin: 0,
        }
    }

    #[test]
    fn test_build_line_fragment_macro_basic() {
        let window = make_window([[
            ("a", Some(colors::RED)),
            ("b", Some(colors::RED)),
            ("c", Some(colors::RED)),
        ]]);

        let mut text = String::new();
        let (next_start, fragment) = window.build_line_fragment(0, 0, &mut text);

        assert_eq!(next_start, 3);
        assert_eq!(fragment.cells, 0..3);
        assert_eq!(fragment.text_range, 0..3);
        assert_eq!(fragment.style, Some(make_style(colors::RED)));
        assert_eq!(fragment.words.len(), 1);

        // There should be no more fragments
        assert_eq!(next_start, window.grid.width);
    }

    #[test]
    fn test_build_line_fragment_macro_style_change() {
        let window = make_window([[
            ("x", Some(colors::RED)),
            ("y", Some(colors::GREEN)),
            ("z", Some(colors::GREEN)),
        ]]);

        let mut text = String::new();
        let (next_start, fragment) = window.build_line_fragment(0, 0, &mut text);

        assert_eq!(next_start, 1);
        assert_eq!(fragment.cells, 0..1);
        assert_eq!(fragment.text_range, 0..1);
        assert_eq!(fragment.style, Some(make_style(colors::RED)));
        assert_eq!(fragment.words.len(), 1);

        let (next_start, fragment) = window.build_line_fragment(0, next_start, &mut text);
        assert_eq!(next_start, 3);
        assert_eq!(fragment.cells, 1..3);
        assert_eq!(fragment.text_range, 1..3);
        assert_eq!(fragment.style, Some(make_style(colors::GREEN)));
        assert_eq!(fragment.words.len(), 1);

        // All fragments should be covered
        assert_eq!(next_start, window.grid.width);
    }

    #[test]
    fn test_build_line_fragment_box_chars() {
        // Use Unicode box drawing char ─ (U+2500)
        let window = make_window([[
            ("─", Some(colors::BLUE)),
            ("─", Some(colors::BLUE)),
            ("│", Some(colors::BLUE)),
        ]]);

        let mut text = String::new();
        let (next_start, fragment) = window.build_line_fragment(0, 0, &mut text);

        // Should group the two ─ chars together, then break for │
        assert_eq!(next_start, 2);
        assert_eq!(fragment.cells, 0..2);
        assert_eq!(fragment.text_range, 0..6);
        assert_eq!(fragment.style, Some(make_style(colors::BLUE)));
        assert_eq!(fragment.words.len(), 1);

        let (next_start, fragment) = window.build_line_fragment(0, next_start, &mut text);
        assert_eq!(next_start, 3);
        assert_eq!(fragment.cells, 2..3);
        assert_eq!(fragment.text_range, 6..9);
        assert_eq!(fragment.style, Some(make_style(colors::BLUE)));
        assert_eq!(fragment.words.len(), 1);

        assert_eq!(next_start, window.grid.width);
    }

    #[test]
    fn win_pos_with_stale_size_keeps_grid_rows() {
        let mut window = make_window([[("a", None)], [("b", None)], [("c", None)], [("d", None)]]);
        let mut batcher = DrawCommandBatcher::new();
        let layout = |row, height| TiledWindowLayout {
            window: 1000,
            rect: GridRect::from_origin_and_size((0, row).into(), (1, height).into()),
        };

        // Temporary split: win_pos reports half the height, without a grid_resize.
        window.position_tiled(&mut batcher, layout(2, 2));
        assert_eq!(window.get_grid_position(), (0.0, 2.0));
        // The split is closed again before Neovim redraws the window.
        window.position_tiled(&mut batcher, layout(0, 4));

        assert_eq!(window.get_height(), 4);
        let rows: Vec<_> = (0..4).map(|row| window.row_cells(row).unwrap().concat()).collect();
        assert_eq!(rows, ["a", "b", "c", "d"]);
    }

    #[test]
    fn test_build_line_fragment_multiple_words_with_spaces() {
        // "  foo bar  baz"
        let window = make_window([[
            (" ", Some(colors::GREEN)),
            (" ", Some(colors::GREEN)),
            ("f", Some(colors::GREEN)),
            ("o", Some(colors::GREEN)),
            ("o", Some(colors::GREEN)),
            (" ", Some(colors::GREEN)),
            ("b", Some(colors::GREEN)),
            ("a", Some(colors::GREEN)),
            ("r", Some(colors::GREEN)),
            (" ", Some(colors::GREEN)),
            (" ", Some(colors::GREEN)),
            ("b", Some(colors::GREEN)),
            ("a", Some(colors::GREEN)),
            ("z", Some(colors::GREEN)),
        ]]);

        let mut text = String::new();
        let (next_start, fragment) = window.build_line_fragment(0, 0, &mut text);

        assert_eq!(next_start, 14);
        assert_eq!(fragment.cells, 0..14);
        assert_eq!(fragment.text_range, 0..14);
        assert_eq!(fragment.style, Some(make_style(colors::GREEN)));
        assert_eq!(text, "  foo bar  baz");

        // There should be three words: "foo", "bar", "baz"
        assert_eq!(fragment.words.len(), 3);

        // "foo"
        assert_eq!(fragment.words[0].cell, 2);
        assert_eq!(fragment.words[0].text_offset, 2);
        assert_eq!(fragment.words[0].cluster_sizes, vec![1, 1, 1]);

        // "bar"
        assert_eq!(fragment.words[1].cell, 6);
        assert_eq!(fragment.words[1].text_offset, 6);
        assert_eq!(fragment.words[1].cluster_sizes, vec![1, 1, 1]);

        // "baz"
        assert_eq!(fragment.words[2].cell, 11);
        assert_eq!(fragment.words[2].text_offset, 11);
        assert_eq!(fragment.words[2].cluster_sizes, vec![1, 1, 1]);

        assert_eq!(next_start, window.grid.width);
    }

    #[test]
    fn test_build_line_fragment_double_width() {
        // U+4E00 is a common double-width CJK char (一)
        // Double width: char, then empty string, both with same style
        let window = make_window([[
            ("一", Some(colors::RED)),
            ("", Some(colors::RED)),
            ("c", Some(colors::RED)),
        ]]);

        let mut text = String::new();
        let (next_start, fragment) = window.build_line_fragment(0, 0, &mut text);

        // The fragment should include all three cells (0..3), text range 0..4 ("一" is 3 bytes, "c" is 1)
        assert_eq!(next_start, 3);
        assert_eq!(fragment.cells, 0..3);
        assert_eq!(fragment.text_range, 0..4);
        assert_eq!(fragment.style, Some(make_style(colors::RED)));
        assert_eq!(fragment.words.len(), 1); // "一c" is a single word
        assert_eq!(text, "一c");

        assert_eq!(next_start, window.grid.width);
    }

    #[test]
    fn test_build_line_fragment_double_width_space_between_words() {
        // "a", double-width space (U+3000), "", "b"
        let window = make_window([[
            ("a", Some(colors::RED)),
            (" ", Some(colors::RED)), // U+3000 IDEOGRAPHIC SPACE
            ("", Some(colors::RED)),
            ("b", Some(colors::RED)),
        ]]);

        let mut text = String::new();
        let (next_start, fragment) = window.build_line_fragment(0, 0, &mut text);

        // The fragment should include all four cells (0..4), text range 0..5 ("a" 1, " " 3, "b" 1)
        assert_eq!(next_start, 4);
        assert_eq!(fragment.cells, 0..4);
        assert_eq!(fragment.text_range, 0..5);
        assert_eq!(fragment.style, Some(make_style(colors::RED)));
        assert_eq!(text, "a b");

        // The words should be ["a"] and ["b"], the double-width space and its empty cell are not part of any word
        assert_eq!(fragment.words.len(), 2);
        // First word: "a"
        assert_eq!(fragment.words[0].cell, 0);
        assert_eq!(fragment.words[0].text_offset, 0);
        assert_eq!(fragment.words[0].cluster_sizes, vec![1]);
        // Second word: "b"
        assert_eq!(fragment.words[1].cell, 3);
        assert_eq!(fragment.words[1].text_offset, 4);
        assert_eq!(fragment.words[1].cluster_sizes, vec![1]);

        assert_eq!(next_start, window.grid.width);
    }

    #[test]
    fn test_build_line_fragment_double_width_in_middle_of_word() {
        // "a", "一" (double-width), "", "b"
        let window = make_window([[
            ("a", Some(colors::RED)),
            ("一", Some(colors::RED)),
            ("", Some(colors::RED)),
            ("b", Some(colors::RED)),
        ]]);

        let mut text = String::new();
        let (next_start, fragment) = window.build_line_fragment(0, 0, &mut text);

        // The fragment should include all four cells (0..4), text range 0..5 ("a" 1, "一" 3, "b" 1)
        assert_eq!(next_start, 4);
        assert_eq!(fragment.cells, 0..4);
        assert_eq!(fragment.text_range, 0..5);
        assert_eq!(fragment.style, Some(make_style(colors::RED)));
        assert_eq!(text, "a一b");

        // The word should be ["a一b"], with cluster_sizes [1, 3, 0, 1]
        assert_eq!(fragment.words.len(), 1);
        assert_eq!(fragment.words[0].cell, 0);
        assert_eq!(fragment.words[0].text_offset, 0);
        assert_eq!(fragment.words[0].cluster_sizes, vec![1, 3, 0, 1]);

        assert_eq!(next_start, window.grid.width);
    }

    #[test]
    fn get_cursor_grid_cell_returns_default_for_zero_height_window() {
        let window = Window {
            grid_id: 1,
            grid: CharacterGrid::new((4, 0)),
            window_type: WindowType::Editor,
            anchor_info: None,
            grid_position: (0.0, 0.0),
            visible: true,
            tiled_layout: None,
            viewport: None,
            viewport_top_margin: 0,
            viewport_bottom_margin: 0,
        };

        assert_eq!(window.get_cursor_grid_cell(0, 0), (" ".to_string(), None, false));
    }
}