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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
use std::cell::RefCell;
use std::ops::Range;
use std::rc::Rc;

use skia_safe::BlendMode;
use skia_safe::Canvas;
use skia_safe::Color;
use skia_safe::Color4f;
use skia_safe::Matrix;
use skia_safe::Paint;
use skia_safe::Path;
use skia_safe::PathBuilder;
use skia_safe::Picture;
use skia_safe::PictureRecorder;
use skia_safe::Rect;

use crate::bridge::WindowAnchor;
use crate::cmd_line::CmdLineSettings;
use crate::editor::AnchorInfo;
use crate::editor::Line;
use crate::editor::LineFragment;
use crate::editor::SortOrder;
use crate::editor::WindowType;
use crate::profiling::tracy_plot;
use crate::profiling::tracy_zone;
use crate::renderer::GridRenderer;
use crate::renderer::RendererSettings;
use crate::renderer::animation_utils::*;
use crate::settings::Settings;
use crate::units::GridPos;
use crate::units::GridRect;
use crate::units::GridScale;
use crate::units::GridSize;
use crate::units::PixelPos;
use crate::units::PixelRect;
use crate::units::PixelVec;
use crate::units::to_skia_rect;
use crate::utils::RingBuffer;

pub const BASE_GRID_ID: u64 = 1;
pub const NO_MULTIGRID_GRID_ID: u64 = 0;

// Window layouts can leave a tiny remainder past the last full grid cell when
// the content size is not an exact multiple of the cell size. We extend edge
// backgrounds slightly into that gap, capped to one cell so the grid never
// appears visibly stretched if it briefly lags a resize.
const MAX_EDGE_FILL_CELLS: f32 = 1.0;

#[derive(Debug)]
pub struct ViewportMargins {
    pub top: u64,
    pub bottom: u64,
}

#[derive(Debug, Clone, PartialEq)]
pub enum WindowDrawCommand {
    Position {
        grid_position: (f64, f64),
        grid_size: (u64, u64),
        anchor_info: Option<AnchorInfo>,
        window_type: WindowType,
    },
    DrawLine {
        row: usize,
        line: Line,
    },
    Scroll {
        top: u64,
        bottom: u64,
        left: u64,
        right: u64,
        rows: i64,
        cols: i64,
    },
    Clear,
    Show,
    Hide,
    Close,
    Viewport {
        scroll_delta: f64,
    },
    ViewportMargins {
        top: u64,
        bottom: u64,
        #[allow(unused)]
        left: u64,
        #[allow(unused)]
        right: u64,
    },
    SortOrder(SortOrder),
}

struct RenderedLine {
    line: Line,
    background_picture: Option<Picture>,
    background_runs: CachedBackgroundRuns,
    foreground_picture: Option<Picture>,
    boxchar_picture: Option<(Picture, PixelPos<f32>)>,
    trailing_background: Option<Color4f>,
    has_transparency: bool,
    is_valid: bool,
}

/// Background color for a half-open cell range on one rendered line.
#[derive(Clone, Copy)]
struct BackgroundRun {
    start_cell: u32,
    end_cell: u32,
    color: Color4f,
}

/// The normal background picture still draws the line itself. These runs keep enough per-column
/// color information to extend a fractional bottom edge using the bottom row's actual background
/// colors, without replaying line fragments or filling the strip with one flat color.
#[derive(Default)]
struct CachedBackgroundRuns {
    runs: Vec<BackgroundRun>,
}

impl CachedBackgroundRuns {
    fn push(&mut self, cells: Range<u32>, color: Color4f) {
        if cells.is_empty() {
            return;
        }

        if let Some(last) = self.runs.last_mut()
            && last.color == color
            && last.end_cell == cells.start
        {
            last.end_cell = cells.end;
            return;
        }

        self.runs.push(BackgroundRun { start_cell: cells.start, end_cell: cells.end, color });
    }

    fn iter(&self) -> impl Iterator<Item = &BackgroundRun> { self.runs.iter() }

    #[cfg(test)]
    fn len(&self) -> usize { self.runs.len() }
}

pub struct RenderedWindow {
    pub id: u64,
    valid: bool,
    pub hidden: bool,
    pub anchor_info: Option<AnchorInfo>,
    pub window_type: WindowType,

    pub grid_size: GridSize<u32>,

    scrollback_lines: RingBuffer<Option<Rc<RefCell<RenderedLine>>>>,
    actual_lines: RingBuffer<Option<Rc<RefCell<RenderedLine>>>>,
    scroll_delta: isize,
    pub viewport_margins: ViewportMargins,

    grid_start_position: GridPos<f32>,
    pub grid_current_position: GridPos<f32>,
    grid_destination: GridPos<f32>,
    position_t: f32,

    pub scroll_animation: CriticallyDampedSpringAnimation,
    pub scroll_animation_delta: f32,
}
#[derive(Clone, Debug)]
pub struct WindowDrawDetails {
    pub id: u64,
    pub region: PixelRect<f32>,
    pub grid_size: GridSize<u32>,
    pub window_type: WindowType,
}

impl WindowDrawDetails {
    pub fn event_grid_id(&self, settings: &Settings) -> u64 {
        if settings.get::<CmdLineSettings>().no_multi_grid { NO_MULTIGRID_GRID_ID } else { self.id }
    }
}

impl RenderedWindow {
    pub fn new(id: u64) -> RenderedWindow {
        let grid_size = GridSize::ZERO;
        let grid_position = GridPos::ZERO;
        RenderedWindow {
            id,
            valid: false,
            hidden: false,
            anchor_info: None,
            window_type: WindowType::Editor,

            grid_size,

            actual_lines: RingBuffer::new(grid_size.height as usize, None),
            scrollback_lines: RingBuffer::new(2 * grid_size.height as usize, None),
            scroll_delta: 0,
            viewport_margins: ViewportMargins { top: 0, bottom: 0 },

            grid_start_position: grid_position,
            grid_current_position: grid_position,
            grid_destination: grid_position,
            position_t: 2.0, // 2.0 is out of the 0.0 to 1.0 range and stops animation.

            scroll_animation: CriticallyDampedSpringAnimation::new(),
            scroll_animation_delta: 0.0,
        }
    }

    pub fn pixel_region(&self, grid_scale: GridScale) -> PixelRect<f32> {
        // Round to the same fraction as the desination to avoid glitches when rendering box
        // characters.
        let fract = (self.grid_destination * grid_scale).fract();
        let pos = (self.grid_current_position * grid_scale - fract).round() + fract.to_vector();
        PixelRect::<f32>::from_origin_and_size(pos.into(), self.grid_size() * grid_scale)
    }

    fn grid_size(&self) -> GridSize<u32> {
        let mut size = self.grid_size;
        if matches!(self.window_type, WindowType::Message { .. }) {
            // Neovim reports message grids with the full default-grid height even
            // when they are anchored near the bottom. Only the rows from the
            // message start row down to the bottom edge are actually visible.
            size.height = size.height.saturating_sub(self.grid_destination.y.max(0.0) as u32);
        }
        size
    }

    fn full_window_vertical_scroll_rows(
        &self,
        top: u64,
        bottom: u64,
        left: u64,
        right: u64,
        rows: i64,
        cols: i64,
    ) -> Option<i64> {
        (top == 0
            && bottom == u64::from(self.grid_size.height)
            && left == 0
            && right == u64::from(self.grid_size.width)
            && cols == 0)
            .then_some(rows)
    }

    fn get_target_position(&self, grid_rect: &GridRect<f32>) -> GridPos<f32> {
        let destination = self.grid_destination + grid_rect.min.to_vector();

        match self.anchor_info {
            None => destination,
            Some(AnchorInfo { anchor_type: WindowAnchor::Absolute, .. }) => destination,
            _ => {
                let grid_size: GridSize<f32> = self.grid_size().try_cast().unwrap();
                // If a floating window is partially outside the grid, then move it in from the right, but
                // ensure that the left edge is always visible.
                let x = destination.x.min(grid_rect.max.x - grid_size.width).max(grid_rect.min.x);

                // For messages the last line is most important, (it shows press enter), so let the position go negative
                // Otherwise ensure that the window start row is within the screen
                let mut y = destination.y.min(grid_rect.max.y - grid_size.height);
                if !matches!(self.window_type, WindowType::Message { .. }) {
                    y = y.max(grid_rect.min.y)
                }
                GridPos::<f32>::new(x, y)
            }
        }
    }

    /// Returns `true` if the window has been animated in this step.
    pub fn animate(
        &mut self,
        settings: &RendererSettings,
        grid_rect: &GridRect<f32>,
        dt: f32,
    ) -> bool {
        let mut animating = false;

        if self.position_t > 1.0 - f32::EPSILON {
            // We are at destination, move t out of 0-1 range to stop the animation.
            self.position_t = 2.0;
        } else {
            animating = true;
            self.position_t = (self.position_t + dt / settings.position_animation_length).min(1.0);
        }

        let prev_position = self.grid_current_position;
        self.grid_current_position = ease_point(
            ease_out_expo,
            self.grid_start_position,
            self.get_target_position(grid_rect),
            self.position_t,
        );
        animating |= self.grid_current_position != prev_position;

        let scroll_before = self.scroll_animation.position;
        let scrolling = self.scroll_animation.update(dt, settings.scroll_animation_length);
        self.scroll_animation_delta = self.scroll_animation.position - scroll_before;

        animating |= scrolling;

        if scrolling {
            tracy_plot!("Scroll position {}", self.scroll_animation.position.into());
        }

        animating
    }

    pub fn draw_background_surface(
        &mut self,
        canvas: &Canvas,
        pixel_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) {
        let inner_region = self.inner_region(pixel_region, grid_scale);

        canvas.save();
        canvas.clip_rect(to_skia_rect(&pixel_region), None, false);
        for (matrix, line) in self.iter_border_lines_with_transform(pixel_region, grid_scale) {
            let line = line.borrow();
            if let Some(background_picture) = &line.background_picture {
                canvas.draw_picture(background_picture, Some(&matrix), None);
            }
        }
        canvas.restore();

        canvas.save();
        canvas.clip_rect(inner_region, None, false);
        let mut pics = 0;
        for (matrix, line) in self.iter_scrollable_lines_with_transform(pixel_region, grid_scale) {
            let line = line.borrow();
            if let Some(background_picture) = &line.background_picture {
                canvas.draw_picture(background_picture, Some(&matrix), None);
                pics += 1;
            }
        }

        log::trace!("region: {pixel_region:?}, inner: {inner_region:?}, pics: {pics}");
        canvas.restore();
    }

    pub fn draw_foreground_surface(
        &mut self,
        canvas: &Canvas,
        pixel_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) {
        for (matrix, line) in self.iter_border_lines_with_transform(pixel_region, grid_scale) {
            let line = line.borrow();
            if let Some(foreground_picture) = &line.foreground_picture {
                canvas.draw_picture(foreground_picture, Some(&matrix), None);
            }
        }
        canvas.save();
        canvas.clip_rect(self.inner_region(pixel_region, grid_scale), None, false);
        for (matrix, line) in self.iter_scrollable_lines_with_transform(pixel_region, grid_scale) {
            let line = line.borrow();
            if let Some(foreground_picture) = &line.foreground_picture {
                canvas.draw_picture(foreground_picture, Some(&matrix), None);
            }
        }
        canvas.restore();

        for (mut matrix, line) in self.iter_border_lines_with_transform(pixel_region, grid_scale) {
            let line = line.borrow();
            if let Some((boxchar_picture, position)) = &line.boxchar_picture {
                let deltax = pixel_region.min.x - position.x;
                matrix.set_translate_x(deltax);
                canvas.draw_picture(boxchar_picture, Some(&matrix), None);
            }
        }
        canvas.save();
        canvas.clip_rect(self.inner_region(pixel_region, grid_scale), None, false);
        for (mut matrix, line) in
            self.iter_scrollable_lines_with_transform(pixel_region, grid_scale)
        {
            let line = line.borrow();
            if let Some((boxchar_picture, position)) = &line.boxchar_picture {
                let deltax = pixel_region.min.x - position.x;
                matrix.set_translate_x(deltax);
                canvas.draw_picture(boxchar_picture, Some(&matrix), None);
            }
        }
        canvas.restore();
    }

    pub fn has_transparency(&self) -> bool {
        let scroll_offset_lines = self.scroll_animation.position.floor() as isize;
        if self.scrollback_lines.is_empty() {
            return false;
        }
        self.scrollback_lines
            .iter_range(
                scroll_offset_lines..scroll_offset_lines + self.grid_size.height as isize + 1,
            )
            .flatten()
            .any(|line| line.borrow().has_transparency)
    }

    pub fn draw(
        &mut self,
        root_canvas: &Canvas,
        default_background: Color,
        grid_scale: GridScale,
        content_region: Option<PixelRect<f32>>,
        rightmost_window: bool,
        bottom_fill_y: Option<f32>,
    ) -> WindowDrawDetails {
        let pixel_region_box = self.pixel_region(grid_scale);
        let draw_region_box = self.expanded_pixel_region(
            pixel_region_box,
            content_region,
            grid_scale,
            rightmost_window,
        );
        let pixel_region = to_skia_rect(&draw_region_box);

        if !self.valid {
            return WindowDrawDetails {
                id: self.id,
                region: pixel_region_box,
                grid_size: self.grid_size,
                window_type: self.window_type,
            };
        }

        root_canvas.save();
        root_canvas.clip_rect(pixel_region, None, Some(false));
        root_canvas.clear(default_background);

        self.draw_background_surface(root_canvas, draw_region_box, grid_scale);
        self.draw_foreground_surface(root_canvas, draw_region_box, grid_scale);

        root_canvas.restore();

        let window_region_box = self.expanded_bottom_pixel_region(
            draw_region_box,
            content_region,
            grid_scale,
            bottom_fill_y,
        );

        self.draw_edge_background_surface(root_canvas, window_region_box, grid_scale);

        WindowDrawDetails {
            id: self.id,
            region: window_region_box,
            grid_size: self.grid_size,
            window_type: self.window_type,
        }
    }

    pub fn expanded_pixel_region(
        &self,
        pixel_region: PixelRect<f32>,
        content_region: Option<PixelRect<f32>>,
        grid_scale: GridScale,
        rightmost_window: bool,
    ) -> PixelRect<f32> {
        let Some(content_region) = content_region else {
            return pixel_region;
        };

        let mut region = pixel_region;
        if rightmost_window
            && sub_cell_edge_gap(content_region.max.x, region.max.x, grid_scale.width()).is_some()
        {
            region.max.x = content_region.max.x;
        }

        region
    }

    /// Backgrounds can extend only from the main grid into its fractional
    /// bottom remainder. A missing boundary disables expansion. Matching
    /// the rendered edge, rather than its destination, keeps fractional or
    /// animating floats from filling rows that still belong to the grid.
    pub fn expanded_bottom_pixel_region(
        &self,
        pixel_region: PixelRect<f32>,
        content_region: Option<PixelRect<f32>>,
        grid_scale: GridScale,
        bottom_fill_y: Option<f32>,
    ) -> PixelRect<f32> {
        let (Some(content_region), Some(main_grid_bottom)) = (content_region, bottom_fill_y) else {
            return pixel_region;
        };

        let mut region = pixel_region;
        let bottom_gap = content_region.max.y - main_grid_bottom;
        if region.max.y == main_grid_bottom && bottom_gap > 0.0 && bottom_gap < grid_scale.height()
        {
            region.max.y = content_region.max.y;
        }

        region
    }

    pub fn draw_edge_background_surface(
        &self,
        canvas: &Canvas,
        pixel_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) {
        self.edge_background_fills(pixel_region, grid_scale).draw(canvas, pixel_region);
    }

    pub fn edge_background_path_and_bounds(
        &self,
        pixel_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> Option<(Path, Rect)> {
        self.edge_background_fills(pixel_region, grid_scale).path_and_bounds()
    }

    fn edge_background_fills(
        &self,
        expanded_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> BackgroundFills {
        let mut fills = self.trailing_background_fills(expanded_region, grid_scale);
        fills.extend(self.bottom_background_fills(expanded_region, grid_scale));
        fills
    }

    fn trailing_background_fills(
        &self,
        expanded_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> BackgroundFills {
        let base_region = self.pixel_region(grid_scale);
        let inner_region = self.inner_region(expanded_region, grid_scale);
        let Some(extra_width) =
            sub_cell_edge_gap(expanded_region.max.x, base_region.max.x, grid_scale.width())
        else {
            return BackgroundFills::default();
        };

        let mut fills = BackgroundFills::default();
        // The trailing fill follows the same clipping model as the normal
        // background pass. Fixed rows like border and margin rows can paint
        // across the full window region, but scrollable rows must stay inside
        // the inner viewport. Since edge fills are drawn through one shared
        // path now, we bake those separate bounds into the generated rects so
        // buffered scroll rows cannot leak into fixed UI rows.
        for (i, line) in self.iter_border_lines() {
            let line = line.borrow();
            let Some(color) = line.trailing_background else {
                continue;
            };

            fills.push(
                Rect::from_xywh(
                    base_region.max.x,
                    expanded_region.min.y + i as f32 * grid_scale.height(),
                    extra_width,
                    grid_scale.height(),
                ),
                color,
            );
        }

        // this fill is part of the rendered grid background, not a separate
        // overlay. when the window is mid-scroll, the scrollable rows can
        // sit at a fractional cell offset, so this fill has to use that
        // same pixel offset too.
        //
        // See https://github.com/neovide/neovide/pull/3387
        let scroll_offset_pixels = self.scroll_offset_pixels(grid_scale.height());
        for (i, line) in self.iter_scrollable_lines() {
            let line = line.borrow();
            let Some(color) = line.trailing_background else {
                continue;
            };

            let y = expanded_region.min.y
                + scroll_offset_pixels
                + (i + self.viewport_margins.top as isize) as f32 * grid_scale.height();
            let top = y.max(inner_region.top);
            let bottom = (y + grid_scale.height()).min(inner_region.bottom);
            if bottom <= top {
                continue;
            }

            fills.push(Rect::from_xywh(base_region.max.x, top, extra_width, bottom - top), color);
        }

        fills
    }

    fn bottom_background_fills(
        &self,
        expanded_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> BackgroundFills {
        let base_region = self.pixel_region(grid_scale);
        let Some(fill_area) = BottomFillArea::new(expanded_region, base_region, grid_scale) else {
            return BackgroundFills::default();
        };

        let Some(line) = self.line_covering_bottom_edge(base_region, grid_scale) else {
            return BackgroundFills::default();
        };

        let line = line.borrow();
        let mut fills = BackgroundFills::default();
        for run in line.background_runs.iter() {
            if let Some(rect) = fill_area.rect_for_cells(run.start_cell, run.end_cell, grid_scale) {
                fills.push(rect, run.color);
            }
        }

        if let Some(color) = line.trailing_background
            && let Some(rect) = fill_area.trailing_corner_rect()
        {
            fills.push(rect, color);
        }

        fills
    }

    fn line_covering_bottom_edge(
        &self,
        base_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> Option<&Rc<RefCell<RenderedLine>>> {
        let line_height = grid_scale.height();
        let bottom_y = base_region.max.y;

        if let Some(line) = self
            .border_line_positions(base_region, grid_scale)
            .find(|positioned_line| positioned_line.covers_y(bottom_y, line_height))
            .map(|positioned_line| positioned_line.line)
        {
            return Some(line);
        }

        let inner_region = self.inner_region(base_region, grid_scale);
        if inner_region.bottom < bottom_y - f32::EPSILON {
            return None;
        }

        self.scrollable_line_positions(base_region, grid_scale)
            .filter(|positioned_line| positioned_line.covers_y(bottom_y, line_height))
            .last()
            .map(|positioned_line| positioned_line.line)
    }

    fn border_line_positions(
        &self,
        base_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> impl Iterator<Item = PositionedRenderedLine<'_>> {
        let line_height = grid_scale.height();
        self.iter_border_lines().map(move |(row, line)| {
            PositionedRenderedLine::new(base_region.min.y + row as f32 * line_height, line)
        })
    }

    fn scrollable_line_positions(
        &self,
        base_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> impl Iterator<Item = PositionedRenderedLine<'_>> {
        let line_height = grid_scale.height();
        let scroll_offset_pixels = self.scroll_offset_pixels(line_height);
        let top_margin = self.viewport_margins.top as isize;

        self.iter_scrollable_lines().map(move |(row, line)| {
            PositionedRenderedLine::new(
                base_region.min.y + scroll_offset_pixels + (row + top_margin) as f32 * line_height,
                line,
            )
        })
    }

    fn scroll_offset_pixels(&self, line_height: f32) -> f32 {
        let scroll_offset_lines = self.scroll_animation.position.floor();
        let scroll_offset = scroll_offset_lines - self.scroll_animation.position;
        (scroll_offset * line_height).round()
    }
    fn line_for_row(&self, row: u32) -> Option<Rc<RefCell<RenderedLine>>> {
        if self.actual_lines.is_empty() {
            return None;
        }

        let row = row as isize;
        let height = self.grid_size.height as isize;
        if row < 0 || row >= height {
            return None;
        }

        let top_margin = self.viewport_margins.top as isize;
        let bottom_margin = self.viewport_margins.bottom as isize;
        let bottom_start = height.saturating_sub(bottom_margin);

        if row < top_margin || row >= bottom_start {
            return self.actual_lines[row].as_ref().cloned();
        }

        let inner_row = row - top_margin;
        let scroll_offset = self.scroll_animation.position.floor() as isize;
        self.scrollback_lines[scroll_offset + inner_row].as_ref().cloned()
    }

    pub fn line_text_range(&self, row: u32, start_col: u32, end_col: u32) -> Option<String> {
        let line = self.line_for_row(row)?;
        let line = line.borrow();
        let cells = line.line.cells()?;
        if cells.is_empty() {
            return Some(String::new());
        }

        let max_col = cells.len().saturating_sub(1) as u32;
        let start = start_col.min(max_col);
        let end = end_col.min(max_col);
        let (start, end) = if start <= end { (start, end) } else { (end, start) };

        let mut text = String::new();
        for col in start..=end {
            text.push_str(&cells[col as usize]);
        }

        let trimmed_len = text.trim_end_matches(' ').len();
        text.truncate(trimmed_len);

        Some(text)
    }

    pub fn grid_row_rect(
        &self,
        row: u32,
        col_start: u32,
        col_end: u32,
        grid_scale: GridScale,
    ) -> Option<Rect> {
        let height = self.grid_size.height;
        let width = self.grid_size.width;
        if height == 0 || width == 0 {
            return None;
        }

        let max_row = height - 1;
        let max_col = width - 1;
        let row = row.min(max_row);
        let start_col = col_start.min(max_col);
        let end_col = col_end.min(max_col);
        let (start_col, end_col) =
            if start_col <= end_col { (start_col, end_col) } else { (end_col, start_col) };

        let pixel_region = self.pixel_region(grid_scale);
        let line_height = grid_scale.height();
        let col_width = grid_scale.width();
        let base_x = pixel_region.min.x;
        let base_y = pixel_region.min.y;

        let scroll_offset_pixels =
            (self.scroll_animation.position.floor() - self.scroll_animation.position) * line_height;
        let top_margin = self.viewport_margins.top as u32;
        let bottom_margin = self.viewport_margins.bottom as u32;
        let bottom_start = height.saturating_sub(bottom_margin);

        let y = if row < top_margin || row >= bottom_start {
            base_y + row as f32 * line_height
        } else {
            base_y + scroll_offset_pixels + row as f32 * line_height
        };
        let x = base_x + start_col as f32 * col_width;
        let w = (end_col - start_col + 1) as f32 * col_width;

        Some(Rect::from_xywh(x, y, w, line_height))
    }

    pub fn handle_window_draw_command(&mut self, draw_command: WindowDrawCommand) {
        match draw_command {
            WindowDrawCommand::Position { grid_position, grid_size, anchor_info, window_type } => {
                tracy_zone!("position_cmd", 0);

                self.valid = true;

                let new_grid_size: GridSize<u32> =
                    GridSize::<u64>::from(grid_size).try_cast().unwrap();
                let grid_position: GridPos<f32> =
                    GridPos::<f64>::from(grid_position).try_cast().unwrap();

                if self.grid_destination != grid_position {
                    if self.grid_start_position.x.abs() > f32::EPSILON
                        || self.grid_start_position.y.abs() > f32::EPSILON
                    {
                        self.position_t = 0.0; // Reset animation as we have a new destination.
                        self.grid_start_position = self.grid_current_position;
                    } else {
                        // We don't want to animate since the window is animating out of the start location,
                        // so we set t to 2.0 to stop animations.
                        self.position_t = 2.0;
                        self.grid_start_position = grid_position;
                    }
                    self.grid_destination = grid_position;
                }

                let height = new_grid_size.height as usize;
                self.actual_lines.resize(height, None);
                self.grid_size = new_grid_size;

                self.scrollback_lines.resize(2 * height, None);
                self.scrollback_lines.clone_from_iter(&self.actual_lines);
                self.scroll_delta = 0;

                if height != self.actual_lines.len() {
                    self.scroll_animation.reset();
                }

                self.anchor_info = anchor_info;
                self.window_type = window_type;
            }
            WindowDrawCommand::DrawLine { row, line } => {
                tracy_zone!("draw_line_cmd", 0);

                if self.actual_lines.is_empty() || !self.valid {
                    log::warn!(
                        "Ignoring DrawLine for grid {} row {} because the window is not ready yet",
                        self.id,
                        row
                    );
                    return;
                }

                let line = RenderedLine {
                    line,
                    background_picture: None,
                    background_runs: CachedBackgroundRuns::default(),
                    foreground_picture: None,
                    boxchar_picture: None,
                    trailing_background: None,
                    has_transparency: false,
                    is_valid: false,
                };

                self.actual_lines[row] = Some(Rc::new(RefCell::new(line)));
            }
            WindowDrawCommand::Scroll { top, bottom, left, right, rows, cols } => {
                tracy_zone!("scroll_cmd", 0);
                if let Some(rows) =
                    self.full_window_vertical_scroll_rows(top, bottom, left, right, rows, cols)
                {
                    self.actual_lines.rotate(rows as isize);
                }
            }
            WindowDrawCommand::Clear => {
                tracy_zone!("clear_cmd", 0);
                self.scroll_delta = 0;
                self.scrollback_lines.iter_mut().for_each(|line| *line = None);
                self.scroll_animation.reset();
            }
            WindowDrawCommand::Show if self.hidden => {
                tracy_zone!("show_cmd", 0);
                self.hidden = false;
                self.position_t = 2.0; // We don't want to animate since the window is becoming visible,
                // so we set t to 2.0 to stop animations.
                self.grid_start_position = self.grid_destination;
                self.scroll_animation.reset();
            }
            WindowDrawCommand::Show => {
                tracy_zone!("show_cmd", 0);
            }
            WindowDrawCommand::Hide => {
                tracy_zone!("hide_cmd", 0);
                self.hidden = true;
            }
            WindowDrawCommand::Viewport { scroll_delta } => {
                log::trace!("Handling Viewport {}", self.id);
                self.scroll_delta = scroll_delta.round() as isize;
            }
            WindowDrawCommand::ViewportMargins { top, bottom, .. } => {
                self.viewport_margins = ViewportMargins { top, bottom }
            }
            WindowDrawCommand::SortOrder(sort_order) => {
                if let Some(anchor_info) = self.anchor_info.as_mut() {
                    anchor_info.sort_order = sort_order;
                }
            }
            _ => {}
        };
    }

    pub fn flush(&mut self, renderer_settings: &RendererSettings) {
        if !self.valid {
            return;
        }
        // If the borders are changed, reset the scrollback to only fit the inner view
        let inner_range = self.viewport_margins.top as isize
            ..(self.actual_lines.len() - self.viewport_margins.bottom as usize) as isize;
        let inner_size = inner_range.len();
        let inner_view = self.actual_lines.iter_range(inner_range);
        if inner_size != self.scrollback_lines.len() / 2 {
            self.scrollback_lines.resize(2 * inner_size, None);
            self.scrollback_lines.clone_from_iter(inner_view);
            self.scroll_delta = 0;
            self.scroll_animation.reset();
            return;
        }

        let scroll_delta = self.scroll_delta;
        self.scrollback_lines.rotate(scroll_delta);

        self.scrollback_lines.clone_from_iter(inner_view);

        if scroll_delta != 0 {
            let mut scroll_offset = self.scroll_animation.position;

            let max_delta =
                self.scrollback_lines.len().saturating_sub(self.grid_size.height as usize);
            log::trace!(
                "Scroll offset {scroll_offset}, delta {scroll_delta}, max_delta {max_delta}"
            );
            // Do a limited scroll with empty lines when scrolling far
            if scroll_delta.unsigned_abs() > max_delta {
                let far_lines = renderer_settings
                    .scroll_animation_far_lines
                    .min(self.actual_lines.len() as u32) as isize;

                scroll_offset = -(far_lines * scroll_delta.signum()) as f32;
                let empty_lines = if scroll_delta > 0 {
                    -far_lines..0
                } else {
                    self.actual_lines.len() as isize..self.actual_lines.len() as isize + far_lines
                };
                for i in empty_lines {
                    self.scrollback_lines[i] = None;
                }
            // And even when scrolling in steps, we can't let it drift too far, since the
            // buffer size is limited
            } else {
                scroll_offset -= scroll_delta as f32;
                scroll_offset = scroll_offset.clamp(-(max_delta as f32), max_delta as f32);
            }
            self.scroll_animation.position = scroll_offset;
            log::trace!("Current scroll {scroll_offset}");
        }
        self.scroll_delta = 0;
    }

    fn iter_border_lines(&self) -> impl Iterator<Item = (isize, &Rc<RefCell<RenderedLine>>)> {
        let top_border_indices = 0..self.viewport_margins.top as isize;
        let actual_line_count = self.actual_lines.len() as isize;
        let bottom_border_indices =
            actual_line_count - self.viewport_margins.bottom as isize..actual_line_count;

        top_border_indices
            .chain(bottom_border_indices)
            .filter_map(move |i| self.actual_lines[i].as_ref().map(|line| (i, line)))
    }

    // Iterates over the scrollable lines (excluding the viewport margins). Includes the index for
    // the given line being scrolled
    fn iter_scrollable_lines(&self) -> impl Iterator<Item = (isize, &Rc<RefCell<RenderedLine>>)> {
        let scroll_offset_lines = self.scroll_animation.position.floor();
        let scroll_offset_lines = scroll_offset_lines as isize;
        let inner_size = self.actual_lines.len() as isize
            - self.viewport_margins.top as isize
            - self.viewport_margins.bottom as isize;

        let line_indices = if inner_size > 0 { 0..inner_size + 1 } else { 0..0 };

        line_indices.filter_map(move |i| {
            self.scrollback_lines[scroll_offset_lines + i].as_ref().map(|line| (i, line))
        })
    }

    fn iter_scrollable_lines_with_transform(
        &self,
        pixel_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> impl Iterator<Item = (Matrix, &Rc<RefCell<RenderedLine>>)> {
        let scroll_offset_pixels = self.scroll_offset_pixels(grid_scale.height());

        self.iter_scrollable_lines().map(move |(i, line)| {
            let mut matrix = Matrix::new_identity();
            matrix.set_translate((
                pixel_region.min.x,
                pixel_region.min.y
                    + (scroll_offset_pixels
                        + ((i + self.viewport_margins.top as isize) as f32 * grid_scale.height())),
            ));
            (matrix, line)
        })
    }

    fn iter_border_lines_with_transform(
        &self,
        pixel_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> impl Iterator<Item = (Matrix, &Rc<RefCell<RenderedLine>>)> {
        self.iter_border_lines().map(move |(i, line)| {
            let mut matrix = Matrix::new_identity();
            matrix.set_translate((
                pixel_region.min.x,
                pixel_region.min.y + (i as f32 * grid_scale.height()),
            ));
            (matrix, line)
        })
    }

    /// Returns the rect containing the region of the window that does not have borders above and
    /// below it. Note: This does not take into account the borders on the left and the right of
    /// the window.
    pub fn inner_region(&self, pixel_region: PixelRect<f32>, grid_scale: GridScale) -> Rect {
        let line_height = grid_scale.height();

        let adjusted_region = PixelRect::new(
            pixel_region.min + PixelVec::new(0., self.viewport_margins.top as f32 * line_height),
            pixel_region.max - PixelVec::new(0., self.viewport_margins.bottom as f32 * line_height),
        );

        to_skia_rect(&adjusted_region)
    }

    pub fn prepare_lines(&mut self, grid_renderer: &mut GridRenderer, opacity: f32, force: bool) {
        let scroll_offset_lines = self.scroll_animation.position.floor() as isize;
        let height = self.grid_size.height as isize;
        if height == 0 {
            return;
        }
        let grid_scale = grid_renderer.grid_scale;

        let mut prepare_line = |line: &Rc<RefCell<RenderedLine>>| {
            let mut line = line.borrow_mut();
            let position = self.grid_destination * grid_renderer.grid_scale;
            let boxchar_moved = match line.boxchar_picture {
                None => false,
                Some((_, p)) if p == position => false,
                _ => true,
            };
            // This can be optimized, only the boxchars need to be redrawn when the window moves
            if line.is_valid && !force && !boxchar_moved {
                return;
            }

            let mut recorder = PictureRecorder::new();

            let line_size = GridSize::new(self.grid_size.width, 1) * grid_scale;
            let grid_rect = Rect::from_wh(line_size.width, line_size.height);
            let canvas = recorder.begin_recording(grid_rect, false);

            let mut has_transparency = false;
            let mut custom_background = false;
            let mut background_runs = CachedBackgroundRuns::default();

            for line_fragment in line.line.fragments() {
                let LineFragment { cells, style, .. } = line_fragment;
                let background_info = grid_renderer.draw_background(canvas, cells, style, opacity);
                custom_background |= background_info.custom_color;
                has_transparency |= background_info.transparent;
                if background_info.custom_color {
                    let color = grid_renderer.background_paint_color(style, opacity);
                    background_runs.push(cells.clone(), color);
                }
            }
            let background_picture =
                custom_background.then_some(recorder.finish_recording_as_picture(None).unwrap());

            let text_canvas = recorder.begin_recording(grid_rect, false);
            let mut boxchar_recorder = PictureRecorder::new();
            let boxchar_canvas =
                boxchar_recorder.begin_recording(grid_rect.with_offset((position.x, 0.0)), false);
            let mut text_drawn = false;
            let mut boxchar_drawn = false;
            for line_fragment in line.line.fragments() {
                let (frag_text_drawn, frag_box_drawn) = grid_renderer.draw_foreground(
                    text_canvas,
                    boxchar_canvas,
                    &line_fragment,
                    position,
                );
                text_drawn |= frag_text_drawn;
                boxchar_drawn |= frag_box_drawn;
            }
            let foreground_picture =
                text_drawn.then_some(recorder.finish_recording_as_picture(None).unwrap());
            let boxchar_picture = boxchar_drawn
                .then_some((boxchar_recorder.finish_recording_as_picture(None).unwrap(), position));

            let trailing_background = line
                .line
                .fragments()
                .filter(|fragment| fragment.cells.end == self.grid_size.width)
                .last()
                .map(|fragment| grid_renderer.background_paint_color(fragment.style, opacity));

            line.background_picture = background_picture;
            line.background_runs = background_runs;
            line.foreground_picture = foreground_picture;
            line.boxchar_picture = boxchar_picture;
            line.trailing_background = trailing_background;
            line.has_transparency = has_transparency;
            line.is_valid = true;
        };

        if !self.scrollback_lines.is_empty() {
            for line in self
                .scrollback_lines
                .iter_range_mut(scroll_offset_lines..scroll_offset_lines + height + 1)
                .flatten()
            {
                prepare_line(line)
            }
        }

        for line in
            self.actual_lines.iter_range_mut(0..self.viewport_margins.top as isize).flatten()
        {
            prepare_line(line)
        }
        let actual_line_count = self.actual_lines.len() as isize;
        for line in self
            .actual_lines
            .iter_range_mut(
                actual_line_count - self.viewport_margins.bottom as isize..actual_line_count,
            )
            .flatten()
        {
            prepare_line(line)
        }
    }
}

struct PositionedRenderedLine<'a> {
    top: f32,
    line: &'a Rc<RefCell<RenderedLine>>,
}

impl PositionedRenderedLine<'_> {
    fn new(top: f32, line: &Rc<RefCell<RenderedLine>>) -> PositionedRenderedLine<'_> {
        PositionedRenderedLine { top, line }
    }

    fn covers_y(&self, y: f32, height: f32) -> bool {
        self.top < y && self.top + height >= y - f32::EPSILON
    }
}

struct BackgroundFillRect {
    rect: Rect,
    color: Color4f,
}

/// Background rects drawn outside the grid-owned cell area.
#[derive(Default)]
struct BackgroundFills {
    rects: Vec<BackgroundFillRect>,
}

impl BackgroundFills {
    fn push(&mut self, rect: Rect, color: Color4f) {
        if rect.is_empty() {
            return;
        }

        self.rects.push(BackgroundFillRect { rect, color });
    }

    fn extend(&mut self, fills: Self) { self.rects.extend(fills.rects); }

    fn draw(&self, canvas: &Canvas, clip_region: PixelRect<f32>) {
        if self.rects.is_empty() {
            return;
        }

        let mut paint = Paint::default();
        paint.set_anti_alias(false);
        // Extend the cell background without accumulating alpha over the canvas background.
        paint.set_blend_mode(BlendMode::Src);

        canvas.save();
        canvas.clip_rect(to_skia_rect(&clip_region), None, false);

        for fill in &self.rects {
            paint.set_color4f(fill.color, None);
            canvas.draw_rect(fill.rect, &paint);
        }

        canvas.restore();
    }

    fn path_and_bounds(&self) -> Option<(Path, Rect)> {
        let mut builder = PathBuilder::new();
        let mut bounds = None;

        for fill in &self.rects {
            push_fill_rect_path(&mut builder, &mut bounds, fill.rect);
        }

        bounds.map(|bounds| (builder.detach(), bounds))
    }
}

/// Geometry for filling the fractional strip below a grid.
struct BottomFillArea {
    grid_region: PixelRect<f32>,
    bottom_gap_height: f32,
    right_gap_width: Option<f32>,
}

impl BottomFillArea {
    fn new(
        fill_region: PixelRect<f32>,
        grid_region: PixelRect<f32>,
        grid_scale: GridScale,
    ) -> Option<Self> {
        let bottom_gap_height =
            sub_cell_edge_gap(fill_region.max.y, grid_region.max.y, grid_scale.height())?;

        let right_gap_width =
            sub_cell_edge_gap(fill_region.max.x, grid_region.max.x, grid_scale.width());

        Some(Self { grid_region, bottom_gap_height, right_gap_width })
    }

    fn rect_for_cells(
        &self,
        start_cell: u32,
        end_cell: u32,
        grid_scale: GridScale,
    ) -> Option<Rect> {
        if start_cell >= end_cell {
            return None;
        }

        let left = self.grid_region.min.x + start_cell as f32 * grid_scale.width();
        let right = (self.grid_region.min.x + end_cell as f32 * grid_scale.width())
            .min(self.grid_region.max.x);

        (right > left).then_some(Rect::from_xywh(
            left,
            self.grid_region.max.y,
            right - left,
            self.bottom_gap_height,
        ))
    }

    fn trailing_corner_rect(&self) -> Option<Rect> {
        self.right_gap_width.map(|width| {
            Rect::from_xywh(
                self.grid_region.max.x,
                self.grid_region.max.y,
                width,
                self.bottom_gap_height,
            )
        })
    }
}

fn sub_cell_edge_gap(expanded_edge: f32, base_edge: f32, cell_extent: f32) -> Option<f32> {
    let extra_extent = expanded_edge - base_edge;
    if extra_extent > 0.0 && extra_extent <= cell_extent * MAX_EDGE_FILL_CELLS + f32::EPSILON {
        Some(extra_extent)
    } else {
        None
    }
}

fn push_fill_rect_path(builder: &mut PathBuilder, bounds: &mut Option<Rect>, rect: Rect) {
    if rect.is_empty() {
        return;
    }

    builder
        .move_to((rect.left, rect.top))
        .line_to((rect.right, rect.top))
        .line_to((rect.right, rect.bottom))
        .line_to((rect.left, rect.bottom))
        .close();

    *bounds = Some(match *bounds {
        Some(current) => Rect::join2(current, rect),
        None => rect,
    });
}

#[cfg(test)]
mod tests {
    use glamour::Contains;
    use skia_safe::Color4f;

    use super::*;
    use crate::renderer::rendered_layer::FloatingLayer;
    use crate::units::PixelSize;

    fn grid_scale() -> GridScale { GridScale::new(PixelSize::new(8.0, 16.0)) }

    fn rendered_window() -> RenderedWindow {
        let mut window = RenderedWindow::new(BASE_GRID_ID);
        window.grid_size = GridSize::new(80, 24);
        window
    }

    #[test]
    fn sub_cell_edge_gap_accepts_positive_gaps_up_to_one_cell() {
        assert_eq!(sub_cell_edge_gap(17.0, 10.0, 16.0), Some(7.0));
        assert_eq!(sub_cell_edge_gap(26.0, 10.0, 16.0), Some(16.0));
        assert_eq!(sub_cell_edge_gap(10.0, 10.0, 16.0), None);
        assert_eq!(sub_cell_edge_gap(27.0, 10.0, 16.0), None);
    }

    #[test]
    fn cached_background_runs_coalesce_adjacent_same_color() {
        let color = Color4f::new(0.1, 0.2, 0.3, 1.0);
        let other_color = Color4f::new(0.4, 0.5, 0.6, 1.0);
        let mut runs = CachedBackgroundRuns::default();

        runs.push(0..2, color);
        runs.push(2..4, color);
        runs.push(4..5, other_color);
        runs.push(5..6, other_color);

        assert_eq!(runs.len(), 2);
        let runs = runs.iter().collect::<Vec<_>>();
        assert_eq!(runs[0].start_cell, 0);
        assert_eq!(runs[0].end_cell, 4);
        assert_eq!(runs[0].color, color);
        assert_eq!(runs[1].start_cell, 4);
        assert_eq!(runs[1].end_cell, 6);
        assert_eq!(runs[1].color, other_color);
    }

    #[test]
    fn bottom_fill_area_rect_for_cells_uses_grid_region_and_clamps_to_grid() {
        let grid_scale = grid_scale();
        let grid_region = PixelRect::new(PixelPos::new(10.0, 20.0), PixelPos::new(90.0, 52.0));
        let fill_region = PixelRect::new(
            grid_region.min,
            PixelPos::new(grid_region.max.x, grid_region.max.y + 7.0),
        );
        let fill_area = BottomFillArea::new(fill_region, grid_region, grid_scale).unwrap();

        let rect = fill_area.rect_for_cells(8, 12, grid_scale).unwrap();

        assert_eq!(rect.left, 74.0);
        assert_eq!(rect.top, 52.0);
        assert_eq!(rect.right, 90.0);
        assert_eq!(rect.bottom, 59.0);
    }

    #[test]
    fn bottom_fill_area_trailing_corner_uses_bottom_right_gap() {
        let grid_scale = grid_scale();
        let grid_region = PixelRect::new(PixelPos::new(10.0, 20.0), PixelPos::new(90.0, 52.0));
        let fill_region = PixelRect::new(
            grid_region.min,
            PixelPos::new(grid_region.max.x + 3.0, grid_region.max.y + 7.0),
        );
        let fill_area = BottomFillArea::new(fill_region, grid_region, grid_scale).unwrap();

        let rect = fill_area.trailing_corner_rect().unwrap();

        assert_eq!(rect.left, 90.0);
        assert_eq!(rect.top, 52.0);
        assert_eq!(rect.right, 93.0);
        assert_eq!(rect.bottom, 59.0);
    }

    fn test_rendered_line() -> RenderedLine {
        RenderedLine {
            line: Line::empty(),
            background_picture: None,
            background_runs: CachedBackgroundRuns::default(),
            foreground_picture: None,
            boxchar_picture: None,
            trailing_background: None,
            has_transparency: false,
            is_valid: true,
        }
    }

    fn positioned_rendered_window(id: u64, top: f64, grid_size: (u64, u64)) -> RenderedWindow {
        let mut window = RenderedWindow::new(id);
        window.handle_window_draw_command(WindowDrawCommand::Position {
            grid_position: (0.0, top),
            grid_size,
            anchor_info: None,
            window_type: WindowType::Editor,
        });
        window.grid_current_position = GridPos::new(0.0, top as f32);
        window
    }

    #[test]
    fn bottom_edge_line_prefers_bottom_border_then_scrollable_line() {
        let grid_scale = grid_scale();
        let mut window = positioned_rendered_window(BASE_GRID_ID, 0.0, (20, 4));
        let base_region = window.pixel_region(grid_scale);

        let border_line = Rc::new(RefCell::new(test_rendered_line()));
        let scroll_line = Rc::new(RefCell::new(test_rendered_line()));
        window.actual_lines[3] = Some(Rc::clone(&border_line));
        window.scrollback_lines[3] = Some(Rc::clone(&scroll_line));

        window.viewport_margins = ViewportMargins { top: 0, bottom: 1 };
        let line = window.line_covering_bottom_edge(base_region, grid_scale).unwrap();
        assert!(Rc::ptr_eq(line, &border_line));

        window.viewport_margins = ViewportMargins { top: 0, bottom: 0 };
        let line = window.line_covering_bottom_edge(base_region, grid_scale).unwrap();
        assert!(Rc::ptr_eq(line, &scroll_line));
    }

    #[test]
    fn bottom_region_expands_from_main_grid_boundary() {
        let window = rendered_window();
        let grid_scale = grid_scale();
        let pixel_region = window.pixel_region(grid_scale);
        let content_region = PixelRect::new(
            pixel_region.min,
            PixelPos::new(pixel_region.max.x, pixel_region.max.y + 7.0),
        );

        let expanded = window.expanded_bottom_pixel_region(
            pixel_region,
            Some(content_region),
            grid_scale,
            Some(pixel_region.max.y),
        );

        assert_eq!(expanded.min, pixel_region.min);
        assert_eq!(expanded.max.x, pixel_region.max.x);
        assert_eq!(expanded.max.y, content_region.max.y);
    }

    #[test]
    fn bottom_region_does_not_expand_without_main_grid_boundary() {
        let window = rendered_window();
        let grid_scale = grid_scale();
        let pixel_region = window.pixel_region(grid_scale);
        let content_region = PixelRect::new(
            pixel_region.min,
            PixelPos::new(pixel_region.max.x, pixel_region.max.y + 7.0),
        );

        let expanded = window.expanded_bottom_pixel_region(
            pixel_region,
            Some(content_region),
            grid_scale,
            None,
        );

        assert_eq!(expanded, pixel_region);
    }

    #[test]
    fn bottom_region_does_not_expand_past_one_cell() {
        let window = rendered_window();
        let grid_scale = grid_scale();
        let pixel_region = window.pixel_region(grid_scale);
        let content_region = PixelRect::new(
            pixel_region.min,
            PixelPos::new(pixel_region.max.x, pixel_region.max.y + grid_scale.height() + 1.0),
        );

        let expanded = window.expanded_bottom_pixel_region(
            pixel_region,
            Some(content_region),
            grid_scale,
            Some(pixel_region.max.y),
        );

        assert_eq!(expanded, pixel_region);
    }

    #[test]
    fn bottom_region_does_not_expand_by_a_full_cell() {
        let window = rendered_window();
        let grid_scale = grid_scale();
        let pixel_region = window.pixel_region(grid_scale);
        let content_region = PixelRect::new(
            pixel_region.min,
            PixelPos::new(pixel_region.max.x, pixel_region.max.y + grid_scale.height()),
        );

        let expanded = window.expanded_bottom_pixel_region(
            pixel_region,
            Some(content_region),
            grid_scale,
            Some(pixel_region.max.y),
        );

        assert_eq!(expanded, pixel_region);
    }

    #[test]
    fn bottom_region_does_not_expand_without_a_remainder() {
        let window = rendered_window();
        let grid_scale = grid_scale();
        let pixel_region = window.pixel_region(grid_scale);

        let expanded = window.expanded_bottom_pixel_region(
            pixel_region,
            Some(pixel_region),
            grid_scale,
            Some(pixel_region.max.y),
        );

        assert_eq!(expanded, pixel_region);
    }

    fn paint_background_row(
        window: &mut RenderedWindow,
        row: usize,
        backgrounds: &[(Range<u32>, Color)],
    ) {
        let grid_scale = grid_scale();
        let cell_width = grid_scale.width();
        let cell_height = grid_scale.height();
        let row_width = window.grid_size.width as f32 * cell_width;
        let row_bounds = Rect::from_wh(row_width, cell_height);

        let mut line = test_rendered_line();
        let mut recorder = PictureRecorder::new();
        let canvas = recorder.begin_recording(row_bounds, false);

        for (cells, color) in backgrounds {
            let left = cells.start as f32 * cell_width;
            let width = cells.len() as f32 * cell_width;
            let rect = Rect::from_xywh(left, 0.0, width, cell_height);
            canvas.draw_rect(rect, Paint::default().set_color(*color));

            line.background_runs.push(cells.clone(), Color4f::from(*color));
            if cells.end == window.grid_size.width {
                line.trailing_background = Some(Color4f::from(*color));
            }
        }

        line.background_picture = recorder.finish_recording_as_picture(None);

        let shared_line = Rc::new(RefCell::new(line));
        window.actual_lines[row] = Some(Rc::clone(&shared_line));
        window.scrollback_lines[row] = Some(shared_line);
    }

    /// Two floating layers over a five-row main grid. The command line
    /// occupies the last row and the popup ends immediately above it.
    /// The layers draw in increasing z order, as UI2 and completion menus
    /// do. A white foreground marker replaces text to keep pixel assertions
    /// independent of installed fonts. An extra buffered foreground row
    /// checks that bottom filling does not widen the text clip.
    struct BottomFillFixture {
        command_line: RenderedWindow,
        popup: RenderedWindow,
        surface: skia_safe::Surface,
        content_region: PixelRect<f32>,
        bottom_fill_y: Option<f32>,
        regions: Vec<WindowDrawDetails>,
    }

    impl BottomFillFixture {
        fn new(bottom_gap: u32, bottom_padding: u32) -> Self {
            let main_grid_bottom = 80;
            let content_width = 163;
            let content_height = main_grid_bottom + bottom_gap;
            let content_region = PixelRect::new(
                PixelPos::ZERO,
                PixelPos::new(content_width as f32, content_height as f32),
            );
            let surface_size = (content_width, (content_height + bottom_padding) as i32);
            let surface = skia_safe::surfaces::raster_n32_premul(surface_size).unwrap();

            Self {
                command_line: Self::command_line_window(),
                popup: Self::popup_window(),
                surface,
                content_region,
                bottom_fill_y: Some(main_grid_bottom as f32),
                regions: Vec::new(),
            }
        }

        fn command_line_window() -> RenderedWindow {
            let mut command_line = positioned_rendered_window(2, 4.0, (20, 1));
            let backgrounds = [(0..10, Color::GREEN), (10..20, Color::BLUE)];
            paint_background_row(&mut command_line, 0, &backgrounds);

            let row_bounds = Rect::from_wh(160.0, 16.0);
            let foreground_marker = Rect::from_xywh(2.0, 12.0, 4.0, 2.0);
            let mut recorder = PictureRecorder::new();
            let canvas = recorder.begin_recording(row_bounds, false);
            canvas.draw_rect(foreground_marker, Paint::default().set_color(Color::WHITE));
            command_line.actual_lines[0].as_ref().unwrap().borrow_mut().foreground_picture =
                recorder.finish_recording_as_picture(None);

            let mut buffered_line = test_rendered_line();
            recorder
                .begin_recording(row_bounds, false)
                .draw_rect(row_bounds, Paint::default().set_color(Color::WHITE));
            buffered_line.foreground_picture = recorder.finish_recording_as_picture(None);
            command_line.scrollback_lines[1] = Some(Rc::new(RefCell::new(buffered_line)));

            command_line
        }

        fn popup_window() -> RenderedWindow {
            let mut popup = positioned_rendered_window(3, 2.0, (10, 2));
            paint_background_row(&mut popup, 0, &[(0..10, Color::RED)]);
            paint_background_row(&mut popup, 1, &[(0..10, Color::RED)]);
            popup
        }

        fn draw(&mut self) {
            let settings = RendererSettings {
                floating_blur: false,
                floating_shadow: false,
                floating_corner_radius: 0.0,
                ..RendererSettings::default()
            };

            let canvas = self.surface.canvas();
            canvas.clear(Color::BLACK);
            let mut command_layer = FloatingLayer { windows: vec![&mut self.command_line] };
            self.regions = command_layer.draw(
                canvas,
                &settings,
                Color::BLACK,
                grid_scale(),
                Some(self.content_region),
                self.bottom_fill_y,
            );

            let mut popup_layer = FloatingLayer { windows: vec![&mut self.popup] };
            self.regions.extend(popup_layer.draw(
                canvas,
                &settings,
                Color::BLACK,
                grid_scale(),
                Some(self.content_region),
                self.bottom_fill_y,
            ));
        }

        fn assert_pixel(&mut self, x: i32, y: i32, color: Color) {
            let pixels = self.surface.peek_pixels().unwrap();
            assert_eq!(pixels.get_color((x, y)), color, "pixel ({x}, {y})");
        }

        fn hit_window(&self, x: f32, y: f32) -> Option<u64> {
            self.regions
                .iter()
                .rfind(|details| details.region.contains(&PixelPos::new(x, y)))
                .map(|details| details.id)
        }

        fn position_popup(&mut self, destination: f64, current: f32) {
            self.popup.handle_window_draw_command(WindowDrawCommand::Position {
                grid_position: (0.0, destination),
                grid_size: (10, 2),
                anchor_info: None,
                window_type: WindowType::Editor,
            });
            self.popup.grid_current_position = GridPos::new(0.0, current);
        }

        fn assert_command_line_visible(&mut self) {
            self.assert_pixel(3, 77, Color::WHITE);
            self.assert_pixel(12, 77, Color::GREEN);
            assert_eq!(self.hit_window(3.0, 77.0), Some(self.command_line.id));
            assert_eq!(self.hit_window(12.0, 77.0), Some(self.command_line.id));
        }
    }

    #[test]
    fn popup_above_command_line_does_not_fill_a_grid_owned_row() {
        let mut fixture = BottomFillFixture::new(0, 0);

        fixture.draw();

        fixture.assert_pixel(12, 40, Color::RED);
        assert_eq!(fixture.hit_window(12.0, 40.0), Some(fixture.popup.id));
        fixture.assert_command_line_visible();
        assert_eq!(fixture.regions[1].region.max.y, 64.0);
    }

    #[test]
    fn fractional_popup_does_not_fill_the_rest_of_the_command_line() {
        let mut fixture = BottomFillFixture::new(0, 0);
        fixture.position_popup(2.5, 2.5);

        fixture.draw();

        fixture.assert_command_line_visible();
        assert_eq!(fixture.regions[1].region.max.y, 72.0);
    }

    #[test]
    fn animating_popup_does_not_fill_before_reaching_the_main_grid_bottom() {
        let mut fixture = BottomFillFixture::new(7, 0);
        fixture.position_popup(3.0, 2.5);

        fixture.draw();

        fixture.assert_command_line_visible();
        fixture.assert_pixel(12, 83, Color::GREEN);
        assert_eq!(fixture.hit_window(12.0, 83.0), Some(fixture.command_line.id));
        assert_eq!(fixture.regions[1].region.max.y, 72.0);
    }

    #[test]
    fn settled_popup_at_main_grid_bottom_can_fill_the_remainder() {
        let mut fixture = BottomFillFixture::new(7, 0);
        fixture.position_popup(3.0, 3.0);

        fixture.draw();

        fixture.assert_pixel(12, 83, Color::RED);
        assert_eq!(fixture.hit_window(12.0, 83.0), Some(fixture.popup.id));
        assert_eq!(fixture.regions[1].region.max.y, fixture.content_region.max.y);
    }

    #[test]
    fn command_line_fills_only_the_fractional_remainder_and_keeps_padding() {
        let mut fixture = BottomFillFixture::new(7, 5);

        fixture.draw();

        fixture.assert_command_line_visible();
        fixture.assert_pixel(3, 83, Color::GREEN);
        fixture.assert_pixel(148, 83, Color::BLUE);
        fixture.assert_pixel(161, 83, Color::BLUE);
        assert_eq!(fixture.hit_window(3.0, 83.0), Some(fixture.command_line.id));
        assert_eq!(fixture.hit_window(161.0, 83.0), Some(fixture.command_line.id));
        fixture.assert_pixel(12, 89, Color::BLACK);
        assert_eq!(fixture.hit_window(12.0, 89.0), None);
    }

    #[test]
    fn disabled_bottom_fill_keeps_right_edge_filling() {
        let mut fixture = BottomFillFixture::new(7, 0);
        fixture.bottom_fill_y = None;

        fixture.draw();

        fixture.assert_command_line_visible();
        fixture.assert_pixel(12, 83, Color::BLACK);
        assert_eq!(fixture.hit_window(12.0, 83.0), None);
        fixture.assert_pixel(161, 77, Color::BLUE);
        assert_eq!(fixture.hit_window(161.0, 77.0), Some(fixture.command_line.id));
    }
}