mkgraphic 0.4.1

A Rust port of the cycfi/elements GUI framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
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
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
//! Multi-line code editor element with tree-sitter syntax highlighting.
//!
//! Follows the same interior-mutability shape as [`super::text_box::TextBox`]
//! (RwLock-guarded state, `handle_*` methods as the real logic so this works
//! behind `Arc<dyn Element>`), extended to a multi-line buffer with a line
//! number gutter, snapshot-based undo/redo, and tree-sitter-driven color.
//!
//! Scope for this first version: single cursor + one contiguous selection
//! (no multi-cursor), whole-buffer reparse per edit (not tree-sitter's
//! incremental `Tree::edit`), and Rust highlighting only. All three are
//! straightforward to extend later without changing the element's shape.

use std::any::Any;
use std::sync::RwLock;

use streaming_iterator::StreamingIterator;

use super::context::{BasicContext, Context};
use super::{Element, FocusRequest, ViewLimits, ViewStretch};
use crate::support::color::Color;
use crate::support::point::Point;
use crate::support::rect::Rect;
use crate::support::theme::get_theme;
use crate::view::{CursorTracking, KeyCode, KeyInfo, MouseButton, MouseButtonKind, TextInfo};

/// A (line, column) position in the buffer. `column` is a char index within
/// `line`'s `String`, not a byte offset. `PartialOrd`/`Ord` compare fields in
/// declaration order (line first), giving buffer order for free -- used by
/// `find_next`/`find_prev` to locate the nearest match relative to the
/// cursor.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
struct CursorPos {
    line: usize,
    column: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
enum EditorState {
    #[default]
    Idle,
    Hover,
    Focused,
}

/// One highlighted span within the buffer, in (line, column) coordinates so
/// it survives being recomputed each draw without byte-offset bookkeeping
/// leaking into rendering.
#[derive(Debug, Clone, Copy)]
struct Highlight {
    start: CursorPos,
    end: CursorPos,
    color: Color,
}

/// Severity of a [`Diagnostic`], matching the LSP's three-level scheme
/// (LSP's `Hint` folds into `Info` here -- one more color wouldn't add
/// anything a caller couldn't already convey via `message`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
    Error,
    Warning,
    Info,
}

/// A single diagnostic (e.g. from `mkide-lsp`) attached to one line.
/// Whole-line rather than column-range, matching this editor's existing
/// preference for simplicity in its first version (see the module doc
/// comment) -- enough to show "something's wrong here," which is what the
/// gutter marker and line tint are for; the message itself carries the
/// specifics.
#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub line: usize,
    pub severity: DiagnosticSeverity,
    pub message: String,
}

pub type TextChangeCallback = Box<dyn Fn(&str) + Send + Sync>;

/// A multi-line code editor with line numbers and syntax highlighting.
pub struct CodeEditor {
    lines: RwLock<Vec<String>>,
    cursor: RwLock<CursorPos>,
    selection_anchor: RwLock<Option<CursorPos>>,
    /// `.x` = horizontal scroll in points, `.y` = vertical scroll in points
    /// (not lines -- see [`Self::visible_line_window`] for how that maps
    /// back to a first-visible-line-plus-pixel-remainder for smooth,
    /// not line-snapped, scrolling).
    scroll_offset: RwLock<Point>,
    /// Width of the widest line in the buffer, in points -- the horizontal
    /// scrollbar's extent. Only recomputed when `content_width_dirty` is
    /// set (by `reparse`, i.e. once per edit) rather than every `draw` --
    /// scanning every line's text width is a real cost for a few-hundred-
    /// line file, and doing it 60 times a second regardless of whether the
    /// buffer changed was the direct cause of scrolling feeling sluggish.
    content_width: RwLock<f32>,
    content_width_dirty: RwLock<bool>,
    state: RwLock<EditorState>,
    undo_stack: RwLock<Vec<Vec<String>>>,
    redo_stack: RwLock<Vec<Vec<String>>>,
    highlights: RwLock<Vec<Highlight>>,
    parser: RwLock<tree_sitter::Parser>,
    query: Option<tree_sitter::Query>,
    diagnostics: RwLock<Vec<Diagnostic>>,
    read_only: RwLock<bool>,
    find_query: RwLock<String>,
    find_matches: RwLock<Vec<CursorPos>>,

    background_color: Color,
    gutter_color: Color,
    gutter_text_color: Color,
    text_color: Color,
    highlight_select_color: Color,
    find_match_color: Color,
    error_color: Color,
    warning_color: Color,
    info_color: Color,
    caret_color: Color,
    scrollbar_color: Color,
    scrollbar_hover_color: Color,
    scrollbar_width: f32,
    font_size: f32,
    line_height: f32,
    gutter_width: f32,
    width: f32,
    height: RwLock<f32>,
    /// Vertical stretch factor -- see `stretch_y`'s doc comment.
    stretch_y: f32,
    enabled: bool,
    on_change: Option<TextChangeCallback>,
    dragging_v: RwLock<bool>,
    dragging_h: RwLock<bool>,
    drag_start: RwLock<Point>,
    drag_start_scroll: RwLock<Point>,
}

impl CodeEditor {
    /// Creates a new code editor with Rust syntax highlighting.
    pub fn new() -> Self {
        let theme = get_theme();
        let mut parser = tree_sitter::Parser::new();
        let query = parser
            .set_language(&tree_sitter_rust::LANGUAGE.into())
            .ok()
            .and_then(|_| {
                tree_sitter::Query::new(&tree_sitter_rust::LANGUAGE.into(), RUST_HIGHLIGHT_QUERY)
                    .map_err(|err| {
                        log::warn!("code_editor: highlight query failed to compile: {err}")
                    })
                    .ok()
            });

        let editor = Self {
            lines: RwLock::new(vec![String::new()]),
            cursor: RwLock::new(CursorPos::default()),
            selection_anchor: RwLock::new(None),
            scroll_offset: RwLock::new(Point::zero()),
            content_width: RwLock::new(0.0),
            content_width_dirty: RwLock::new(true),
            state: RwLock::new(EditorState::Idle),
            undo_stack: RwLock::new(Vec::new()),
            redo_stack: RwLock::new(Vec::new()),
            highlights: RwLock::new(Vec::new()),
            parser: RwLock::new(parser),
            query,
            diagnostics: RwLock::new(Vec::new()),
            read_only: RwLock::new(false),
            find_query: RwLock::new(String::new()),
            find_matches: RwLock::new(Vec::new()),
            background_color: theme.input_box_color,
            gutter_color: theme.input_box_color.level(0.9),
            gutter_text_color: theme.text_box_idle_color,
            text_color: theme.text_box_font_color,
            highlight_select_color: theme.text_box_hilite_color,
            find_match_color: Color::from_rgb_u32(0xffd54a).with_alpha(0.45),
            error_color: Color::from_rgb_u32(0xe5484d),
            warning_color: Color::from_rgb_u32(0xf5a623),
            info_color: Color::from_rgb_u32(0x4a9fe5),
            caret_color: theme.text_box_caret_color,
            scrollbar_color: theme.scrollbar_color,
            scrollbar_hover_color: theme.scrollbar_color.level(1.3),
            scrollbar_width: theme.scrollbar_width,
            font_size: theme.text_box_font_size,
            line_height: theme.text_box_font_size * 1.4,
            gutter_width: 48.0,
            width: 600.0,
            height: RwLock::new(400.0),
            stretch_y: 1.0,
            enabled: true,
            on_change: None,
            dragging_v: RwLock::new(false),
            dragging_h: RwLock::new(false),
            drag_start: RwLock::new(Point::zero()),
            drag_start_scroll: RwLock::new(Point::zero()),
        };
        editor.reparse();
        editor
    }

    /// Sets the initial text (replaces the buffer, clears undo history).
    pub fn text(mut self, text: impl Into<String>) -> Self {
        self.set_text_inner(text.into());
        *self.undo_stack.get_mut().unwrap() = Vec::new();
        *self.redo_stack.get_mut().unwrap() = Vec::new();
        self
    }

    /// Sets the width.
    pub fn width(mut self, width: f32) -> Self {
        self.width = width;
        self
    }

    /// Sets the height.
    pub fn height(mut self, height: f32) -> Self {
        self.height = RwLock::new(height);
        self
    }

    /// Returns the current height (see `set_height`).
    pub fn get_height(&self) -> f32 {
        *self.height.read().unwrap()
    }

    /// Adjusts the height at runtime, e.g. from a `Splitter`'s drag
    /// callback. Clamped to a small minimum so a drag can't collapse the
    /// editor to nothing.
    pub fn set_height(&self, height: f32) {
        *self.height.write().unwrap() = height.max(40.0);
    }

    /// Sets the vertical stretch factor (default `1.0`, matching every
    /// other stretchy element). Set this to `0.0` for an editor whose
    /// height should be driven *only* by `set_height` (e.g. a `Splitter`)
    /// and never by a `VTile` sibling competing for "extra" space --
    /// without this, a log panel with equal stretch to its stretchy
    /// neighbor only moved at half the speed of the mouse while dragging
    /// their shared splitter (both siblings split the delta), which read
    /// as the drag being broken/capped rather than just slow.
    pub fn stretch_y(mut self, stretch_y: f32) -> Self {
        self.stretch_y = stretch_y;
        self
    }

    /// Sets the change callback, invoked with the full buffer text after
    /// every edit.
    pub fn on_change<F: Fn(&str) + Send + Sync + 'static>(mut self, callback: F) -> Self {
        self.on_change = Some(Box::new(callback));
        self
    }

    /// Makes the editor read-only from construction (builder form). Cursor
    /// movement, selection, and copying still work; typing, paste, and
    /// undo/redo do not. Needed for e.g. MKIDE's build-output/log panel,
    /// which reuses this same editor purely as a scrollable, syntax-free
    /// text view that the user shouldn't be able to accidentally edit.
    pub fn read_only(mut self, read_only: bool) -> Self {
        *self.read_only.get_mut().unwrap() = read_only;
        self
    }

    /// Toggles read-only at runtime (e.g. locking the buffer while a build
    /// is in progress).
    pub fn set_read_only(&self, read_only: bool) {
        *self.read_only.write().unwrap() = read_only;
    }

    /// Returns whether the editor is currently read-only.
    pub fn is_read_only(&self) -> bool {
        *self.read_only.read().unwrap()
    }

    /// Replaces the set of per-line diagnostics shown as gutter markers and
    /// a faint full-line tint (e.g. from `mkide-lsp`'s
    /// `LspClient::diagnostics_for`). Lines outside the current buffer are
    /// silently ignored rather than panicking, since diagnostics can arrive
    /// slightly out of sync with the buffer (the language server saw an
    /// older or newer version of the file).
    pub fn set_diagnostics(&self, diagnostics: Vec<Diagnostic>) {
        *self.diagnostics.write().unwrap() = diagnostics;
    }

    /// Clears all diagnostic markers.
    pub fn clear_diagnostics(&self) {
        self.diagnostics.write().unwrap().clear();
    }

    /// Sets the text to highlight all occurrences of, and moves the cursor
    /// to the first match at or after the current cursor position (wrapping
    /// around to the start of the buffer if none is found after it). Pass
    /// an empty string to clear highlighting. Returns whether any match was
    /// found (always `false` for an empty query).
    pub fn find(&self, query: &str) -> bool {
        *self.find_query.write().unwrap() = query.to_string();
        self.recompute_find_matches();
        if query.is_empty() {
            return false;
        }
        let cursor = *self.cursor.read().unwrap();
        self.find_next_from(cursor, true)
    }

    /// Moves to the next match after the current cursor position, wrapping
    /// around. No-op (returns `false`) if `find` hasn't been called with a
    /// non-empty query, or there are no matches.
    pub fn find_next(&self) -> bool {
        let cursor = *self.cursor.read().unwrap();
        self.find_next_from(cursor, true)
    }

    /// Moves to the previous match before the current cursor position,
    /// wrapping around.
    pub fn find_prev(&self) -> bool {
        let cursor = *self.cursor.read().unwrap();
        self.find_next_from(cursor, false)
    }

    fn find_next_from(&self, from: CursorPos, forward: bool) -> bool {
        let matches = self.find_matches.read().unwrap();
        if matches.is_empty() {
            return false;
        }
        let next = if forward {
            matches
                .iter()
                .find(|m| **m > from)
                .or_else(|| matches.first())
        } else {
            matches
                .iter()
                .rev()
                .find(|m| **m < from)
                .or_else(|| matches.last())
        };
        let Some(&pos) = next else {
            return false;
        };
        drop(matches);
        *self.cursor.write().unwrap() = pos;
        *self.selection_anchor.write().unwrap() = None;
        true
    }

    fn recompute_find_matches(&self) {
        let query = self.find_query.read().unwrap().clone();
        let mut matches = Vec::new();
        if !query.is_empty() {
            let lines = self.lines.read().unwrap();
            for (line_index, line) in lines.iter().enumerate() {
                let mut start = 0;
                while let Some(byte_offset) = line[start..].find(&query) {
                    let byte_pos = start + byte_offset;
                    let column = line[..byte_pos].chars().count();
                    matches.push(CursorPos {
                        line: line_index,
                        column,
                    });
                    start = byte_pos + query.len().max(1);
                    if start >= line.len() {
                        break;
                    }
                }
            }
        }
        *self.find_matches.write().unwrap() = matches;
    }

    /// Returns the current buffer text (lines joined with `\n`).
    pub fn get_text(&self) -> String {
        self.lines.read().unwrap().join("\n")
    }

    /// Replaces the buffer text, resetting cursor/selection/scroll.
    pub fn set_text(&self, text: impl Into<String>) {
        self.push_undo_snapshot();
        self.set_text_inner(text.into());
    }

    fn set_text_inner(&self, text: String) {
        let lines: Vec<String> = if text.is_empty() {
            vec![String::new()]
        } else {
            text.split('\n').map(str::to_string).collect()
        };
        *self.lines.write().unwrap() = lines;
        *self.cursor.write().unwrap() = CursorPos::default();
        *self.selection_anchor.write().unwrap() = None;
        *self.scroll_offset.write().unwrap() = Point::zero();
        self.reparse();
    }

    fn push_undo_snapshot(&self) {
        let snapshot = self.lines.read().unwrap().clone();
        self.undo_stack.write().unwrap().push(snapshot);
        self.redo_stack.write().unwrap().clear();
    }

    /// Appends one line to the end of the buffer, without touching the
    /// cursor, selection, or undo history -- built for read-only log
    /// panels (e.g. MKIDE's build/run/test/debug output) that get many
    /// small appends as a process streams output, rather than being edited
    /// by hand. Scrolls to the bottom afterward so newly streamed lines
    /// stay visible instead of silently landing off-screen.
    pub fn append_line(&self, line: &str) {
        {
            let mut lines = self.lines.write().unwrap();
            // The buffer starts as one empty-string line (see `new()`) --
            // replace that placeholder instead of leaving a stray blank
            // line before the first real one.
            if lines.len() == 1 && lines[0].is_empty() {
                lines[0] = line.to_string();
            } else {
                lines.push(line.to_string());
            }
        }
        self.reparse();
        self.scroll_to_bottom();
    }

    /// Scrolls to the last line. Uses the editor's own configured height
    /// as an approximation of the actual rendered viewport height (exact
    /// only when no horizontal scrollbar is showing to shave a few points
    /// off it) since no `Context` is available outside of draw/event
    /// handling -- close enough to reliably reveal the last few lines.
    pub fn scroll_to_bottom(&self) {
        let content_height = self.content_height();
        let viewport_height = *self.height.read().unwrap();
        let max_y = (content_height - viewport_height).max(0.0);
        self.scroll_offset.write().unwrap().y = max_y;
    }

    fn undo(&self) {
        if *self.read_only.read().unwrap() {
            return;
        }
        let Some(snapshot) = self.undo_stack.write().unwrap().pop() else {
            return;
        };
        let current = self.lines.read().unwrap().clone();
        self.redo_stack.write().unwrap().push(current);
        *self.lines.write().unwrap() = snapshot;
        self.clamp_cursor();
        self.reparse();
        self.notify_change();
    }

    fn redo(&self) {
        if *self.read_only.read().unwrap() {
            return;
        }
        let Some(snapshot) = self.redo_stack.write().unwrap().pop() else {
            return;
        };
        let current = self.lines.read().unwrap().clone();
        self.undo_stack.write().unwrap().push(current);
        *self.lines.write().unwrap() = snapshot;
        self.clamp_cursor();
        self.reparse();
        self.notify_change();
    }

    fn clamp_cursor(&self) {
        let lines = self.lines.read().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        cursor.line = cursor.line.min(lines.len().saturating_sub(1));
        cursor.column = cursor.column.min(lines[cursor.line].chars().count());
    }

    fn notify_change(&self) {
        if let Some(ref callback) = self.on_change {
            callback(&self.get_text());
        }
    }

    /// Re-runs the tree-sitter parser over the whole buffer and recomputes
    /// highlight spans. Whole-buffer reparse (not incremental) -- simplest
    /// correct approach for a first version; fine at editor-buffer sizes,
    /// worth revisiting with `Tree::edit` if profiling ever shows it matters.
    fn reparse(&self) {
        // Called after every edit, so this is also the one place that keeps
        // find-match positions in sync with the buffer, regardless of
        // whether tree-sitter highlighting itself is available below. Also
        // the one place that marks the cached content width stale -- see
        // `content_width`'s doc comment.
        self.recompute_find_matches();
        *self.content_width_dirty.write().unwrap() = true;

        let Some(query) = &self.query else {
            return;
        };
        let text = self.get_text();
        let mut parser = self.parser.write().unwrap();
        let Some(tree) = parser.parse(&text, None) else {
            return;
        };
        drop(parser);

        let line_starts = line_start_byte_offsets(&text);
        let mut cursor = tree_sitter::QueryCursor::new();
        let mut matches = cursor.matches(query, tree.root_node(), text.as_bytes());
        let theme_colors = HighlightColors::from_theme();
        let mut spans = Vec::new();
        while let Some(m) = matches.next() {
            for capture in m.captures {
                let name = &query.capture_names()[capture.index as usize];
                let Some(color) = theme_colors.for_capture(name) else {
                    continue;
                };
                let node = capture.node;
                let start = byte_to_cursor_pos(node.start_byte(), &line_starts);
                let end = byte_to_cursor_pos(node.end_byte(), &line_starts);
                spans.push(Highlight { start, end, color });
            }
        }
        *self.highlights.write().unwrap() = spans;
    }

    fn insert_text(&self, s: &str) {
        if *self.read_only.read().unwrap() {
            return;
        }
        self.push_undo_snapshot();
        let mut lines = self.lines.write().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        let mut anchor = self.selection_anchor.write().unwrap();

        if let Some(sel) = *anchor {
            delete_range_inner(&mut lines, sel, *cursor, &mut cursor);
            *anchor = None;
        }

        if s == "\n" {
            let line = lines[cursor.line].clone();
            let byte = char_to_byte(&line, cursor.column);
            let (before, after) = line.split_at(byte);
            lines[cursor.line] = before.to_string();
            lines.insert(cursor.line + 1, after.to_string());
            cursor.line += 1;
            cursor.column = 0;
        } else {
            let line = &mut lines[cursor.line];
            let byte = char_to_byte(line, cursor.column);
            line.insert_str(byte, s);
            cursor.column += s.chars().count();
        }

        drop(lines);
        drop(cursor);
        drop(anchor);
        self.reparse();
        self.notify_change();
    }

    fn delete_backward(&self) {
        if *self.read_only.read().unwrap() {
            return;
        }
        let mut lines = self.lines.write().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        let mut anchor = self.selection_anchor.write().unwrap();

        if let Some(sel) = anchor.take() {
            self.push_undo_snapshot_locked(&lines);
            delete_range_inner(&mut lines, sel, *cursor, &mut cursor);
        } else if cursor.column > 0 {
            self.push_undo_snapshot_locked(&lines);
            let line = &mut lines[cursor.line];
            let start = char_to_byte(line, cursor.column - 1);
            let end = char_to_byte(line, cursor.column);
            line.replace_range(start..end, "");
            cursor.column -= 1;
        } else if cursor.line > 0 {
            self.push_undo_snapshot_locked(&lines);
            let current = lines.remove(cursor.line);
            let prev_len = lines[cursor.line - 1].chars().count();
            lines[cursor.line - 1].push_str(&current);
            cursor.line -= 1;
            cursor.column = prev_len;
        }

        drop(lines);
        drop(cursor);
        drop(anchor);
        self.reparse();
        self.notify_change();
    }

    fn delete_forward(&self) {
        if *self.read_only.read().unwrap() {
            return;
        }
        let mut lines = self.lines.write().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        let mut anchor = self.selection_anchor.write().unwrap();

        if let Some(sel) = anchor.take() {
            self.push_undo_snapshot_locked(&lines);
            delete_range_inner(&mut lines, sel, *cursor, &mut cursor);
        } else {
            let line_char_count = lines[cursor.line].chars().count();
            if cursor.column < line_char_count {
                self.push_undo_snapshot_locked(&lines);
                let line = &mut lines[cursor.line];
                let start = char_to_byte(line, cursor.column);
                let end = char_to_byte(line, cursor.column + 1);
                line.replace_range(start..end, "");
            } else if cursor.line + 1 < lines.len() {
                self.push_undo_snapshot_locked(&lines);
                let next = lines.remove(cursor.line + 1);
                lines[cursor.line].push_str(&next);
            }
        }

        drop(lines);
        drop(cursor);
        drop(anchor);
        self.reparse();
        self.notify_change();
    }

    /// Same as [`Self::push_undo_snapshot`] but takes an already-held read
    /// guard on `lines` to snapshot, since the delete methods above need to
    /// record history *before* mutating but while still holding the write
    /// lock they're about to mutate through.
    fn push_undo_snapshot_locked(&self, lines: &[String]) {
        self.undo_stack.write().unwrap().push(lines.to_vec());
        self.redo_stack.write().unwrap().clear();
    }

    fn move_left(&self, select: bool) {
        let lines = self.lines.read().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        self.update_selection_anchor(select);
        if cursor.column > 0 {
            cursor.column -= 1;
        } else if cursor.line > 0 {
            cursor.line -= 1;
            cursor.column = lines[cursor.line].chars().count();
        }
    }

    fn move_right(&self, select: bool) {
        let lines = self.lines.read().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        self.update_selection_anchor(select);
        let line_len = lines[cursor.line].chars().count();
        if cursor.column < line_len {
            cursor.column += 1;
        } else if cursor.line + 1 < lines.len() {
            cursor.line += 1;
            cursor.column = 0;
        }
    }

    fn move_up(&self, select: bool) {
        let lines = self.lines.read().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        self.update_selection_anchor(select);
        if cursor.line > 0 {
            cursor.line -= 1;
            cursor.column = cursor.column.min(lines[cursor.line].chars().count());
        }
    }

    fn move_down(&self, select: bool) {
        let lines = self.lines.read().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        self.update_selection_anchor(select);
        if cursor.line + 1 < lines.len() {
            cursor.line += 1;
            cursor.column = cursor.column.min(lines[cursor.line].chars().count());
        }
    }

    fn move_home(&self, select: bool) {
        let mut cursor = self.cursor.write().unwrap();
        self.update_selection_anchor(select);
        cursor.column = 0;
    }

    fn move_end(&self, select: bool) {
        let lines = self.lines.read().unwrap();
        let mut cursor = self.cursor.write().unwrap();
        self.update_selection_anchor(select);
        cursor.column = lines[cursor.line].chars().count();
    }

    fn select_all(&self) {
        let lines = self.lines.read().unwrap();
        let last_line = lines.len() - 1;
        let last_col = lines[last_line].chars().count();
        *self.selection_anchor.write().unwrap() = Some(CursorPos { line: 0, column: 0 });
        *self.cursor.write().unwrap() = CursorPos {
            line: last_line,
            column: last_col,
        };
    }

    fn update_selection_anchor(&self, select: bool) {
        let mut anchor = self.selection_anchor.write().unwrap();
        if select {
            if anchor.is_none() {
                *anchor = Some(*self.cursor.read().unwrap());
            }
        } else {
            *anchor = None;
        }
    }

    /// Highest-severity diagnostic on `line`, if any (a line with both an
    /// error and a warning shows the error marker, since that's the more
    /// actionable of the two).
    fn diagnostic_severity_for_line(&self, line: usize) -> Option<DiagnosticSeverity> {
        self.diagnostics
            .read()
            .unwrap()
            .iter()
            .filter(|d| d.line == line)
            .map(|d| d.severity)
            .max_by_key(|s| match s {
                DiagnosticSeverity::Error => 2,
                DiagnosticSeverity::Warning => 1,
                DiagnosticSeverity::Info => 0,
            })
    }

    fn severity_color(&self, severity: DiagnosticSeverity) -> Color {
        match severity {
            DiagnosticSeverity::Error => self.error_color,
            DiagnosticSeverity::Warning => self.warning_color,
            DiagnosticSeverity::Info => self.info_color,
        }
    }

    /// Widest line in the buffer, measured with the editor's own font.
    fn measure_content_width(&self, ctx: &Context) -> f32 {
        let mut canvas = ctx.canvas.borrow_mut();
        let theme = get_theme();
        canvas.font(theme.text_box_font);
        canvas.font_size(self.font_size);
        self.lines
            .read()
            .unwrap()
            .iter()
            .map(|l| canvas.text_width(l))
            .fold(0.0, f32::max)
    }

    fn content_height(&self) -> f32 {
        self.lines.read().unwrap().len() as f32 * self.line_height
    }

    /// Whole-editor-bounds check, not the (possibly already-narrowed-by-the-
    /// other-scrollbar) viewport -- avoids the two scrollbars' visibility
    /// depending on each other, matching `ScrollView`'s equivalent tradeoff.
    fn needs_v_scrollbar(&self, ctx: &Context) -> bool {
        self.content_height() > ctx.bounds.height()
    }

    fn needs_h_scrollbar(&self, ctx: &Context) -> bool {
        *self.content_width.read().unwrap() > ctx.bounds.width() - self.gutter_width
    }

    /// Full editor area minus whichever scrollbar(s) are showing.
    fn viewport_rect(&self, ctx: &Context) -> Rect {
        let has_v = self.needs_v_scrollbar(ctx);
        let has_h = self.needs_h_scrollbar(ctx);
        Rect::new(
            ctx.bounds.left,
            ctx.bounds.top,
            ctx.bounds.right - if has_v { self.scrollbar_width } else { 0.0 },
            ctx.bounds.bottom - if has_h { self.scrollbar_width } else { 0.0 },
        )
    }

    /// Where text (not the gutter) is drawn/scrolled/clipped.
    fn text_viewport(&self, ctx: &Context) -> Rect {
        let viewport = self.viewport_rect(ctx);
        Rect::new(
            viewport.left + self.gutter_width,
            viewport.top,
            viewport.right,
            viewport.bottom,
        )
    }

    fn v_scrollbar_rect(&self, ctx: &Context) -> Rect {
        if !self.needs_v_scrollbar(ctx) {
            return Rect::zero();
        }
        let has_h = self.needs_h_scrollbar(ctx);
        Rect::new(
            ctx.bounds.right - self.scrollbar_width,
            ctx.bounds.top,
            ctx.bounds.right,
            ctx.bounds.bottom - if has_h { self.scrollbar_width } else { 0.0 },
        )
    }

    fn h_scrollbar_rect(&self, ctx: &Context) -> Rect {
        if !self.needs_h_scrollbar(ctx) {
            return Rect::zero();
        }
        let has_v = self.needs_v_scrollbar(ctx);
        Rect::new(
            ctx.bounds.left + self.gutter_width,
            ctx.bounds.bottom - self.scrollbar_width,
            ctx.bounds.right - if has_v { self.scrollbar_width } else { 0.0 },
            ctx.bounds.bottom,
        )
    }

    fn v_thumb_rect(&self, ctx: &Context) -> Rect {
        let track = self.v_scrollbar_rect(ctx);
        if track.is_empty() {
            return Rect::zero();
        }
        let content_height = self.content_height();
        let viewport = self.text_viewport(ctx);
        let scroll_y = self.scroll_offset.read().unwrap().y;

        let visible_ratio = (viewport.height() / content_height).min(1.0);
        let thumb_height = (track.height() * visible_ratio).max(20.0);
        let scroll_range = (content_height - viewport.height()).max(0.0);
        let scroll_ratio = if scroll_range > 0.0 {
            scroll_y / scroll_range
        } else {
            0.0
        };
        let thumb_y = track.top + scroll_ratio * (track.height() - thumb_height);

        Rect::new(
            track.left + 2.0,
            thumb_y,
            track.right - 2.0,
            thumb_y + thumb_height,
        )
    }

    fn h_thumb_rect(&self, ctx: &Context) -> Rect {
        let track = self.h_scrollbar_rect(ctx);
        if track.is_empty() {
            return Rect::zero();
        }
        let content_width = *self.content_width.read().unwrap();
        let viewport = self.text_viewport(ctx);
        let scroll_x = self.scroll_offset.read().unwrap().x;

        let visible_ratio = (viewport.width() / content_width).min(1.0);
        let thumb_width = (track.width() * visible_ratio).max(20.0);
        let scroll_range = (content_width - viewport.width()).max(0.0);
        let scroll_ratio = if scroll_range > 0.0 {
            scroll_x / scroll_range
        } else {
            0.0
        };
        let thumb_x = track.left + scroll_ratio * (track.width() - thumb_width);

        Rect::new(
            thumb_x,
            track.top + 2.0,
            thumb_x + thumb_width,
            track.bottom - 2.0,
        )
    }

    fn draw_scrollbars(&self, ctx: &Context) {
        let mut canvas = ctx.canvas.borrow_mut();

        if self.needs_v_scrollbar(ctx) {
            let track = self.v_scrollbar_rect(ctx);
            let thumb = self.v_thumb_rect(ctx);
            canvas.fill_style(self.scrollbar_color.with_alpha(0.2));
            canvas.fill_rect(track);
            let color = if *self.dragging_v.read().unwrap() {
                self.scrollbar_hover_color
            } else {
                self.scrollbar_color
            };
            canvas.fill_style(color);
            canvas.fill_round_rect(thumb, 3.0);
        }

        if self.needs_h_scrollbar(ctx) {
            let track = self.h_scrollbar_rect(ctx);
            let thumb = self.h_thumb_rect(ctx);
            canvas.fill_style(self.scrollbar_color.with_alpha(0.2));
            canvas.fill_rect(track);
            let color = if *self.dragging_h.read().unwrap() {
                self.scrollbar_hover_color
            } else {
                self.scrollbar_color
            };
            canvas.fill_style(color);
            canvas.fill_round_rect(thumb, 3.0);
        }

        if self.needs_v_scrollbar(ctx) && self.needs_h_scrollbar(ctx) {
            let corner = Rect::new(
                ctx.bounds.right - self.scrollbar_width,
                ctx.bounds.bottom - self.scrollbar_width,
                ctx.bounds.right,
                ctx.bounds.bottom,
            );
            canvas.fill_style(self.scrollbar_color.with_alpha(0.3));
            canvas.fill_rect(corner);
        }
    }

    /// Clamps and stores a new scroll position against the current content
    /// size -- the single place both wheel-scroll and scrollbar-thumb-drag
    /// funnel through, so neither can push the view past the buffer's
    /// actual extent.
    fn set_scroll(&self, ctx: &Context, x: f32, y: f32) {
        let content_width = *self.content_width.read().unwrap();
        let content_height = self.content_height();
        let viewport = self.text_viewport(ctx);
        let max_x = (content_width - viewport.width()).max(0.0);
        let max_y = (content_height - viewport.height()).max(0.0);
        *self.scroll_offset.write().unwrap() = Point::new(x.clamp(0.0, max_x), y.clamp(0.0, max_y));
    }

    /// Nudges scroll (both axes) just enough to bring the cursor back
    /// inside the visible viewport, without moving it more than necessary
    /// (a cursor already in view is left alone). Called after every
    /// key-driven cursor move/edit -- see `handle_key`/`handle_text`.
    fn scroll_cursor_into_view(&self, ctx: &Context) {
        let cursor = *self.cursor.read().unwrap();
        let scroll = *self.scroll_offset.read().unwrap();
        let viewport = self.text_viewport(ctx);

        let cursor_top = cursor.line as f32 * self.line_height;
        let cursor_bottom = cursor_top + self.line_height;
        let new_y = if cursor_top < scroll.y {
            cursor_top
        } else if cursor_bottom > scroll.y + viewport.height() {
            cursor_bottom - viewport.height()
        } else {
            scroll.y
        };

        let cursor_x = {
            let lines = self.lines.read().unwrap();
            let mut canvas = ctx.canvas.borrow_mut();
            let theme = get_theme();
            canvas.font(theme.text_box_font);
            canvas.font_size(self.font_size);
            canvas.text_width_to_position(&lines[cursor.line], cursor.column)
        };
        let new_x = if cursor_x < scroll.x {
            cursor_x
        } else if cursor_x > scroll.x + viewport.width() {
            cursor_x - viewport.width()
        } else {
            scroll.x
        };

        self.set_scroll(ctx, new_x, new_y);
    }

    fn draw_gutter(
        &self,
        ctx: &Context,
        first_visible_line: usize,
        visible_lines: usize,
        line_offset: f32,
    ) {
        let mut canvas = ctx.canvas.borrow_mut();
        let gutter_rect = Rect::new(
            ctx.bounds.left,
            ctx.bounds.top,
            ctx.bounds.left + self.gutter_width,
            self.viewport_rect(ctx).bottom,
        );
        canvas.fill_style(self.gutter_color);
        canvas.fill_rect(gutter_rect);

        let theme = get_theme();
        canvas.font(theme.text_box_font);
        canvas.font_size(self.font_size);

        let lines = self.lines.read().unwrap();
        for row in 0..visible_lines {
            let line_index = first_visible_line + row;
            if line_index >= lines.len() {
                break;
            }
            let y = ctx.bounds.top + (row as f32 + 1.0) * self.line_height
                - self.line_height * 0.3
                - line_offset;

            if let Some(severity) = self.diagnostic_severity_for_line(line_index) {
                canvas.fill_style(self.severity_color(severity));
                let dot_y = y - self.font_size * 0.35;
                canvas.fill_round_rect(
                    Rect::new(
                        ctx.bounds.left + 4.0,
                        dot_y - 3.0,
                        ctx.bounds.left + 10.0,
                        dot_y + 3.0,
                    ),
                    3.0,
                );
            }

            let label = (line_index + 1).to_string();
            canvas.fill_style(self.gutter_text_color);
            let x = ctx.bounds.left + self.gutter_width - 8.0 - canvas.text_width(&label);
            canvas.fill_text(&label, Point::new(x, y));
        }
    }

    fn draw_selection_and_text(
        &self,
        ctx: &Context,
        first_visible_line: usize,
        visible_lines: usize,
        line_offset: f32,
    ) {
        let text_viewport = self.text_viewport(ctx);
        let mut canvas = ctx.canvas.borrow_mut();
        let theme = get_theme();
        canvas.font(theme.text_box_font);
        canvas.font_size(self.font_size);
        canvas.save();
        canvas.clip(text_viewport);

        let lines = self.lines.read().unwrap();
        let cursor = *self.cursor.read().unwrap();
        let anchor = *self.selection_anchor.read().unwrap();
        let highlights = self.highlights.read().unwrap();
        let find_matches = self.find_matches.read().unwrap();
        let query_len = self.find_query.read().unwrap().chars().count();
        let scroll_x = self.scroll_offset.read().unwrap().x;
        let text_left = ctx.bounds.left + self.gutter_width + 6.0 - scroll_x;

        for row in 0..visible_lines {
            let line_index = first_visible_line + row;
            if line_index >= lines.len() {
                break;
            }
            let line = &lines[line_index];
            let y_top = ctx.bounds.top + row as f32 * self.line_height - line_offset;
            let y_baseline = y_top + self.line_height - self.font_size * 0.3;

            // Faint full-line tint for a diagnostic on this line, drawn
            // first so selection/find highlights and text stay legible on
            // top of it.
            if let Some(severity) = self.diagnostic_severity_for_line(line_index) {
                canvas.fill_style(self.severity_color(severity).with_alpha(0.12));
                canvas.fill_rect(Rect::new(
                    ctx.bounds.left + self.gutter_width,
                    y_top,
                    ctx.bounds.right,
                    y_top + self.line_height,
                ));
            }

            // Highlight every find match on this line.
            if query_len > 0 {
                for m in find_matches.iter().filter(|m| m.line == line_index) {
                    let x1 = text_left + canvas.text_width_to_position(line, m.column);
                    let x2 = text_left
                        + canvas.text_width_to_position(
                            line,
                            (m.column + query_len).min(line.chars().count()),
                        );
                    canvas.fill_style(self.find_match_color);
                    canvas.fill_rect(Rect::new(
                        x1,
                        y_top,
                        x2.max(x1 + 2.0),
                        y_top + self.line_height,
                    ));
                }
            }

            // Selection background for this line, if any.
            if let Some(sel) = anchor {
                if let Some((start_col, end_col)) = selection_on_line(sel, cursor, line_index) {
                    let x1 = text_left + canvas.text_width_to_position(line, start_col);
                    let x2 = text_left
                        + canvas.text_width_to_position(line, end_col.min(line.chars().count()));
                    canvas.fill_style(self.highlight_select_color);
                    canvas.fill_rect(Rect::new(
                        x1,
                        y_top,
                        x2.max(x1 + 2.0),
                        y_top + self.line_height,
                    ));
                }
            }

            // Syntax-highlighted text, drawn as colored runs.
            let segments = line_color_segments(line, line_index, &highlights, self.text_color);
            for (start_col, end_col, color) in segments {
                let start_byte = char_to_byte(line, start_col);
                let end_byte = char_to_byte(line, end_col);
                if start_byte >= end_byte {
                    continue;
                }
                canvas.fill_style(color);
                let x = text_left + canvas.text_width_to_position(line, start_col);
                canvas.fill_text(&line[start_byte..end_byte], Point::new(x, y_baseline));
            }

            // Caret.
            if line_index == cursor.line && *self.state.read().unwrap() == EditorState::Focused {
                let x = text_left + canvas.text_width_to_position(line, cursor.column);
                canvas.stroke_style(self.caret_color);
                canvas.line_width(1.5);
                canvas.begin_path();
                canvas.move_to(Point::new(x, y_top + 2.0));
                canvas.line_to(Point::new(x, y_top + self.line_height - 2.0));
                canvas.stroke();
            }
        }

        canvas.restore();
    }

    /// Returns `(first_visible_line, visible_line_count, line_offset)`.
    /// `line_offset` is the sub-line-height pixel remainder of the vertical
    /// scroll (`scroll.y - first_visible_line * line_height`), applied as a
    /// y-offset when drawing so scrolling is smooth rather than snapped to
    /// whole lines.
    fn visible_line_window(&self, ctx: &Context) -> (usize, usize, f32) {
        let scroll_y = self.scroll_offset.read().unwrap().y;
        let first = (scroll_y / self.line_height).floor().max(0.0) as usize;
        let line_offset = scroll_y - first as f32 * self.line_height;
        let visible = (self.text_viewport(ctx).height() / self.line_height).ceil() as usize + 1;
        (first, visible, line_offset)
    }

    fn cursor_pos_from_click(&self, ctx: &Context, p: Point) -> CursorPos {
        let lines = self.lines.read().unwrap();
        let scroll = *self.scroll_offset.read().unwrap();
        let row = (((p.y - ctx.bounds.top + scroll.y) / self.line_height)
            .floor()
            .max(0.0)) as usize;
        let line = row.min(lines.len().saturating_sub(1));
        let line_text = &lines[line];

        let mut canvas = ctx.canvas.borrow_mut();
        let theme = get_theme();
        canvas.font(theme.text_box_font);
        canvas.font_size(self.font_size);
        let text_left = ctx.bounds.left + self.gutter_width + 6.0 - scroll.x;
        let rel_x = p.x - text_left;

        let char_count = line_text.chars().count();
        let mut column = char_count;
        for i in 0..=char_count {
            if canvas.text_width_to_position(line_text, i) >= rel_x {
                column = i;
                break;
            }
        }
        CursorPos { line, column }
    }
}

impl Default for CodeEditor {
    fn default() -> Self {
        Self::new()
    }
}

impl Element for CodeEditor {
    fn limits(&self, _ctx: &BasicContext) -> ViewLimits {
        // `min_size`, not `fixed`: `.width()`/`.height()` set a starting
        // size, not a hard cap. `ViewLimits::fixed` pins `max` to the same
        // value as `min`, and since `VTile`/`HTile` aggregate `max` across
        // children via `min()`, a single fixed-size editor in a layout caps
        // the *entire* surrounding column/row at that size forever, however
        // wide the window grows -- confirmed as the cause of MKIDE's editor
        // area never resizing past the ~700pt it was constructed with.
        ViewLimits::min_size(self.width, *self.height.read().unwrap())
    }

    fn stretch(&self) -> ViewStretch {
        ViewStretch::new(1.0, self.stretch_y)
    }

    fn draw(&self, ctx: &Context) {
        {
            let mut canvas = ctx.canvas.borrow_mut();
            canvas.fill_style(self.background_color);
            canvas.fill_rect(ctx.bounds);
        }
        if *self.content_width_dirty.read().unwrap() {
            *self.content_width.write().unwrap() = self.measure_content_width(ctx);
            *self.content_width_dirty.write().unwrap() = false;
        }
        let (first, visible, line_offset) = self.visible_line_window(ctx);
        self.draw_selection_and_text(ctx, first, visible, line_offset);
        self.draw_gutter(ctx, first, visible, line_offset);
        self.draw_scrollbars(ctx);
    }

    fn hit_test(
        &self,
        ctx: &Context,
        p: Point,
        _leaf: bool,
        _control: bool,
    ) -> Option<&dyn Element> {
        if ctx.bounds.contains(p) && self.enabled {
            Some(self)
        } else {
            None
        }
    }

    fn wants_control(&self) -> bool {
        self.enabled
    }

    fn wants_focus(&self) -> bool {
        self.enabled
    }

    fn begin_focus(&mut self, _req: FocusRequest) {
        *self.state.write().unwrap() = EditorState::Focused;
    }

    fn end_focus(&mut self) -> bool {
        *self.state.write().unwrap() = EditorState::Idle;
        true
    }

    fn clear_focus(&self) {
        let mut state = self.state.write().unwrap();
        if *state == EditorState::Focused {
            *state = EditorState::Idle;
        }
    }

    fn handle_click(&self, ctx: &Context, btn: MouseButton) -> bool {
        if !self.enabled || btn.button != MouseButtonKind::Left {
            return false;
        }
        if btn.down {
            if self.v_thumb_rect(ctx).contains(btn.pos) {
                *self.dragging_v.write().unwrap() = true;
                *self.drag_start.write().unwrap() = btn.pos;
                *self.drag_start_scroll.write().unwrap() = *self.scroll_offset.read().unwrap();
                return true;
            }
            if self.h_thumb_rect(ctx).contains(btn.pos) {
                *self.dragging_h.write().unwrap() = true;
                *self.drag_start.write().unwrap() = btn.pos;
                *self.drag_start_scroll.write().unwrap() = *self.scroll_offset.read().unwrap();
                return true;
            }
            *self.state.write().unwrap() = EditorState::Focused;
            let pos = self.cursor_pos_from_click(ctx, btn.pos);
            *self.cursor.write().unwrap() = pos;
            *self.selection_anchor.write().unwrap() = None;
        } else {
            *self.dragging_v.write().unwrap() = false;
            *self.dragging_h.write().unwrap() = false;
        }
        true
    }

    fn drag(&mut self, ctx: &Context, btn: MouseButton) {
        self.handle_drag(ctx, btn);
    }

    fn handle_drag(&self, ctx: &Context, btn: MouseButton) {
        let drag_start = *self.drag_start.read().unwrap();
        let start_scroll = *self.drag_start_scroll.read().unwrap();

        if *self.dragging_v.read().unwrap() {
            let track = self.v_scrollbar_rect(ctx);
            let thumb = self.v_thumb_rect(ctx);
            let viewport = self.text_viewport(ctx);
            let delta_y = btn.pos.y - drag_start.y;
            let track_range = track.height() - thumb.height();
            let scroll_range = (self.content_height() - viewport.height()).max(0.0);
            if track_range > 0.0 {
                let new_y = start_scroll.y + delta_y * scroll_range / track_range;
                self.set_scroll(ctx, start_scroll.x, new_y);
            }
        }

        if *self.dragging_h.read().unwrap() {
            let track = self.h_scrollbar_rect(ctx);
            let thumb = self.h_thumb_rect(ctx);
            let viewport = self.text_viewport(ctx);
            let content_width = *self.content_width.read().unwrap();
            let delta_x = btn.pos.x - drag_start.x;
            let track_range = track.width() - thumb.width();
            let scroll_range = (content_width - viewport.width()).max(0.0);
            if track_range > 0.0 {
                let new_x = start_scroll.x + delta_x * scroll_range / track_range;
                self.set_scroll(ctx, new_x, start_scroll.y);
            }
        }
    }

    fn cursor(&mut self, _ctx: &Context, _p: Point, status: CursorTracking) -> bool {
        if !self.enabled {
            return false;
        }
        let mut state = self.state.write().unwrap();
        if *state == EditorState::Focused {
            return true;
        }
        match status {
            CursorTracking::Entering | CursorTracking::Hovering => *state = EditorState::Hover,
            CursorTracking::Leaving => *state = EditorState::Idle,
        }
        true
    }

    fn handle_scroll(&self, ctx: &Context, dir: Point, _p: Point) -> bool {
        if !self.enabled {
            return false;
        }
        let scroll = *self.scroll_offset.read().unwrap();
        self.set_scroll(ctx, scroll.x - dir.x, scroll.y - dir.y);
        true
    }

    fn key(&mut self, ctx: &Context, k: KeyInfo) -> bool {
        self.handle_key(ctx, k)
    }

    fn handle_key(&self, ctx: &Context, k: KeyInfo) -> bool {
        if !self.enabled || *self.state.read().unwrap() != EditorState::Focused {
            return false;
        }
        if k.action != crate::view::KeyAction::Press && k.action != crate::view::KeyAction::Repeat {
            return true;
        }

        let shift = k.modifiers & crate::view::modifiers::SHIFT != 0;
        let ctrl =
            k.modifiers & (crate::view::modifiers::CONTROL | crate::view::modifiers::SUPER) != 0;

        match k.key {
            KeyCode::Left => self.move_left(shift),
            KeyCode::Right => self.move_right(shift),
            KeyCode::Up => self.move_up(shift),
            KeyCode::Down => self.move_down(shift),
            KeyCode::Home => self.move_home(shift),
            KeyCode::End => self.move_end(shift),
            KeyCode::Backspace => self.delete_backward(),
            KeyCode::Delete => self.delete_forward(),
            KeyCode::Enter => self.insert_text("\n"),
            KeyCode::Tab => self.insert_text("    "),
            KeyCode::A if ctrl => self.select_all(),
            KeyCode::Z if ctrl && shift => self.redo(),
            KeyCode::Z if ctrl => self.undo(),
            KeyCode::Y if ctrl => self.redo(),
            _ => return false,
        }
        // Without this, moving the cursor past whatever's currently
        // scrolled into view (e.g. holding Down past the bottom line, or
        // End on a line wider than the viewport) left the caret invisible
        // off-screen with nothing on screen changing -- indistinguishable
        // from arrow keys simply not working.
        self.scroll_cursor_into_view(ctx);
        true
    }

    fn text(&mut self, ctx: &Context, info: TextInfo) -> bool {
        self.handle_text(ctx, info)
    }

    fn handle_text(&self, ctx: &Context, info: TextInfo) -> bool {
        if !self.enabled || *self.state.read().unwrap() != EditorState::Focused {
            return false;
        }
        let c = info.codepoint;
        if !c.is_control() {
            self.insert_text(&c.to_string());
            self.scroll_cursor_into_view(ctx);
        }
        true
    }

    fn enable(&mut self, state: bool) {
        self.enabled = state;
    }

    fn is_enabled(&self) -> bool {
        self.enabled
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

/// Creates a code editor.
pub fn code_editor() -> CodeEditor {
    CodeEditor::new()
}

// --- helpers -----------------------------------------------------------

fn char_to_byte(line: &str, column: usize) -> usize {
    line.char_indices()
        .nth(column)
        .map(|(i, _)| i)
        .unwrap_or(line.len())
}

/// Deletes the (line, column)-addressed range `[a, b)` (order-independent)
/// from `lines` in place, and sets `*cursor` to the range's start.
fn delete_range_inner(lines: &mut Vec<String>, a: CursorPos, b: CursorPos, cursor: &mut CursorPos) {
    let (start, end) = if (a.line, a.column) <= (b.line, b.column) {
        (a, b)
    } else {
        (b, a)
    };

    if start.line == end.line {
        let line = &mut lines[start.line];
        let sb = char_to_byte(line, start.column);
        let eb = char_to_byte(line, end.column);
        line.replace_range(sb..eb, "");
    } else {
        let start_byte = char_to_byte(&lines[start.line], start.column);
        let end_byte = char_to_byte(&lines[end.line], end.column);
        let remainder = lines[end.line][end_byte..].to_string();

        lines[start.line].truncate(start_byte);
        lines[start.line].push_str(&remainder);
        lines.drain(start.line + 1..=end.line);
    }
    *cursor = start;
}

/// Returns the `(start_column, end_column)` selection extent on `line_index`,
/// if the selection `[anchor, cursor)` (order-independent) touches that line.
fn selection_on_line(
    anchor: CursorPos,
    cursor: CursorPos,
    line_index: usize,
) -> Option<(usize, usize)> {
    let (start, end) = if (anchor.line, anchor.column) <= (cursor.line, cursor.column) {
        (anchor, cursor)
    } else {
        (cursor, anchor)
    };
    if line_index < start.line || line_index > end.line {
        return None;
    }
    let start_col = if line_index == start.line {
        start.column
    } else {
        0
    };
    let end_col = if line_index == end.line {
        end.column
    } else {
        usize::MAX
    };
    Some((start_col, end_col))
}

/// Byte offset (into the whole buffer text) that each line starts at.
fn line_start_byte_offsets(text: &str) -> Vec<usize> {
    let mut offsets = vec![0usize];
    for (i, b) in text.bytes().enumerate() {
        if b == b'\n' {
            offsets.push(i + 1);
        }
    }
    offsets
}

fn byte_to_cursor_pos(byte: usize, line_starts: &[usize]) -> CursorPos {
    let line = match line_starts.binary_search(&byte) {
        Ok(i) => i,
        Err(i) => i.saturating_sub(1),
    };
    let column_bytes = byte - line_starts[line];
    // `column_bytes` is a byte offset within the line; callers only use this
    // for highlight span comparison against char-column selection math via
    // `line_color_segments`, which re-derives char columns from byte offsets
    // consistently, so this stays correct for non-ASCII content too.
    CursorPos {
        line,
        column: column_bytes,
    }
}

/// Splits `line` into `(start_col, end_col, color)` runs for drawing, given
/// the highlight spans that overlap `line_index`. Gaps between highlights
/// (and the whole line, if none overlap) use `default_color`.
fn line_color_segments(
    line: &str,
    line_index: usize,
    highlights: &[Highlight],
    default_color: Color,
) -> Vec<(usize, usize, Color)> {
    let char_count = line.chars().count();
    let mut boundaries: Vec<usize> = vec![0, char_count];
    let mut applicable: Vec<(usize, usize, Color)> = Vec::new();

    for h in highlights {
        if line_index < h.start.line || line_index > h.end.line {
            continue;
        }
        let start_col = if line_index == h.start.line {
            byte_column_to_char_column(line, h.start.column)
        } else {
            0
        };
        let end_col = if line_index == h.end.line {
            byte_column_to_char_column(line, h.end.column)
        } else {
            char_count
        };
        if start_col >= end_col {
            continue;
        }
        boundaries.push(start_col);
        boundaries.push(end_col.min(char_count));
        applicable.push((start_col, end_col.min(char_count), h.color));
    }

    boundaries.sort_unstable();
    boundaries.dedup();

    let mut segments = Vec::new();
    for window in boundaries.windows(2) {
        let (a, b) = (window[0], window[1]);
        if a >= b {
            continue;
        }
        let color = applicable
            .iter()
            .rev()
            .find(|(s, e, _)| *s <= a && b <= *e)
            .map(|(_, _, c)| *c)
            .unwrap_or(default_color);
        segments.push((a, b, color));
    }
    segments
}

/// `byte_to_cursor_pos` stores a byte offset in `CursorPos::column` for
/// highlight spans (see its doc comment); this converts that byte offset,
/// for one specific line's text, into a char column for drawing/selection
/// math, which all use char columns.
fn byte_column_to_char_column(line: &str, byte_column: usize) -> usize {
    line.char_indices()
        .position(|(i, _)| i >= byte_column)
        .unwrap_or(line.chars().count())
}

struct HighlightColors {
    keyword: Color,
    string: Color,
    comment: Color,
    number: Color,
    ty: Color,
    function: Color,
    property: Color,
}

impl HighlightColors {
    fn from_theme() -> Self {
        // A fixed, reasonably dark-theme-oriented palette for v1 -- worth
        // promoting to `Theme` fields once more than one editor consumer
        // (MKIDE) needs to customize it.
        Self {
            keyword: Color::from_rgb_u8(198, 120, 221),
            string: Color::from_rgb_u8(152, 195, 121),
            comment: Color::from_rgb_u8(110, 118, 129),
            number: Color::from_rgb_u8(209, 154, 102),
            ty: Color::from_rgb_u8(224, 175, 104),
            function: Color::from_rgb_u8(97, 175, 239),
            property: Color::from_rgb_u8(224, 108, 117),
        }
    }

    fn for_capture(&self, name: &str) -> Option<Color> {
        match name {
            "keyword" => Some(self.keyword),
            "string" => Some(self.string),
            "comment" => Some(self.comment),
            "number" => Some(self.number),
            "type" => Some(self.ty),
            "function" => Some(self.function),
            "property" => Some(self.property),
            _ => None,
        }
    }
}

const RUST_HIGHLIGHT_QUERY: &str = r#"
(line_comment) @comment
(block_comment) @comment
(string_literal) @string
(char_literal) @string
(integer_literal) @number
(float_literal) @number
(type_identifier) @type
(primitive_type) @type
(field_identifier) @property
(function_item name: (identifier) @function)
(call_expression function: (identifier) @function)
(call_expression function: (field_expression field: (field_identifier) @function))
[
  "fn" "let" "pub" "struct" "impl" "use" "mod" "if" "else" "match" "for"
  "while" "loop" "return" "mut" "const" "static" "trait" "enum" "async"
  "await" "move" "in" "as" "ref" "where" "unsafe" "extern" "crate" "super"
  "dyn" "break" "continue" "true" "false" "self" "Self"
] @keyword
"#;

#[cfg(test)]
mod editor_interaction_tests {
    use super::*;
    use crate::support::canvas::Canvas;
    use crate::view::{MouseButtonKind, TextInfo};
    use std::cell::RefCell;

    fn click_and_type(editor: &CodeEditor, click_pos: Point, text: &str) {
        let view = crate::view::View::new(crate::support::point::Extent::new(700.0, 400.0));
        let canvas = RefCell::new(Canvas::new(700, 400).unwrap());
        let bounds = Rect::new(0.0, 0.0, 700.0, 400.0);
        let ctx = Context::new(&view, &canvas, bounds);

        assert!(
            editor.hit_test(&ctx, click_pos, false, false).is_some(),
            "hit_test should find the editor at {click_pos:?}"
        );

        let down = MouseButton {
            down: true,
            click_count: 1,
            button: MouseButtonKind::Left,
            modifiers: 0,
            pos: click_pos,
        };
        assert!(
            editor.handle_click(&ctx, down),
            "mouse-down should be handled"
        );

        let up = MouseButton {
            down: false,
            ..down
        };
        editor.handle_click(&ctx, up);

        for c in text.chars() {
            let handled = editor.handle_text(
                &ctx,
                TextInfo {
                    codepoint: c,
                    modifiers: 0,
                },
            );
            assert!(handled, "handle_text should accept '{c}' once focused");
        }
    }

    #[test]
    fn click_then_type_inserts_text() {
        let editor = CodeEditor::new().text("");
        click_and_type(&editor, Point::new(60.0, 10.0), "hi");
        assert_eq!(editor.get_text(), "hi");
    }

    #[test]
    fn click_then_arrow_keys_move_cursor() {
        let editor = CodeEditor::new().text("hello");
        let view = crate::view::View::new(crate::support::point::Extent::new(700.0, 400.0));
        let canvas = RefCell::new(Canvas::new(700, 400).unwrap());
        let bounds = Rect::new(0.0, 0.0, 700.0, 400.0);
        let ctx = Context::new(&view, &canvas, bounds);

        let down = MouseButton {
            down: true,
            click_count: 1,
            button: MouseButtonKind::Left,
            modifiers: 0,
            pos: Point::new(60.0, 10.0),
        };
        editor.handle_click(&ctx, down);

        let before = *editor.cursor.read().unwrap();
        let key = KeyInfo {
            key: KeyCode::Left,
            action: crate::view::KeyAction::Press,
            modifiers: 0,
        };
        assert!(
            editor.handle_key(&ctx, key),
            "Left arrow should be handled once focused"
        );
        let after = *editor.cursor.read().unwrap();
        assert_ne!(before, after, "cursor should move after pressing Left");
    }

    /// Reproduces the "splitter drag only moves the panel at half speed"
    /// bug: an output-log `CodeEditor` sitting in a `VTile` next to a
    /// stretchy sibling, with the *default* stretch (1.0), only grows by
    /// half of whatever `set_height` sets it to -- the sibling's equal
    /// stretch claims the other half of the "extra" space MKIDE's
    /// `Splitter` is trying to hand entirely to the editor being dragged.
    /// `.stretch_y(0.0)` is the fix; this locks in that it actually works
    /// (the rendered height exactly matches `set_height`, not half of it).
    #[test]
    fn stretch_y_zero_makes_rendered_height_track_set_height_exactly() {
        use crate::element::composite::CompositeBase;
        use crate::element::tile::VTile;
        use crate::support::point::Extent;

        struct StretchySibling;
        impl Element for StretchySibling {
            fn limits(&self, _ctx: &BasicContext) -> ViewLimits {
                ViewLimits::min_size(200.0, 300.0)
            }
            fn stretch(&self) -> ViewStretch {
                ViewStretch::new(1.0, 1.0)
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
            fn as_any_mut(&mut self) -> &mut dyn Any {
                self
            }
        }

        let output =
            std::sync::Arc::new(CodeEditor::new().width(200.0).height(90.0).stretch_y(0.0));
        let vtile = VTile::from_vec(vec![
            crate::element::share(StretchySibling),
            output.clone() as crate::element::ElementPtr,
        ]);

        let view = crate::view::View::new(Extent::new(200.0, 600.0));
        let canvas = RefCell::new(Canvas::new(200, 600).unwrap());
        let bounds = Rect::new(0.0, 0.0, 200.0, 600.0);
        let ctx = Context::new(&view, &canvas, bounds);

        // 600pt window, 300pt sibling min + 90pt output min = 390pt total
        // min, 210pt "extra". With stretch_y(0.0) *none* of that extra
        // should go to `output` -- it should render at exactly its own
        // 90pt min, not 90 + 105 (half of 210).
        let initial = vtile.bounds_of(&ctx, 1);
        assert_eq!(
            initial.height(),
            90.0,
            "output should render at exactly its own min, claiming none of the extra"
        );

        // Drag the output panel's height up by 100pt (what `Splitter`'s
        // callback does) -- the window itself hasn't resized.
        output.set_height(190.0);
        let after = vtile.bounds_of(&ctx, 1);
        assert_eq!(
            after.height(),
            190.0,
            "output's rendered height should track set_height exactly (1:1), not half of the delta"
        );
    }
}