rust_widgets 2.7.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Data grid widget backed by incremental data source protocol.

use std::sync::Arc;

use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::Event;
use crate::impl_widget_property_hooks;
use crate::property_names_of;
use crate::render::RenderContext;
use crate::signal::{ConnectionScope, Signal1};
use crate::widget::capability::access::{column_filters_to_string, sort_specs_to_string};
use crate::widget::capability::coercion::{expect_column_filters, expect_sort_specs, expect_usize};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::metrics::ControlMetrics;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};

/// The margin a data grid leaves between its own frame and its cells: 2 px on every edge.
///
/// Named once so the first cell and the frozen-column divider are both measured from the
/// same inset. The cells used to start at the control's literal `rect.y`, which put the first
/// row's border on the frame's own stroke.
const GRID_INSET: u32 = 2;

/// The strip a data grid reserves above its first cell for column titles: 22 px, one row.
///
/// A grid reads as one whether or not a header row is supplied, so the first cell is always
/// one header below the frame rather than pinned to the top edge.
const GRID_HEADER_HEIGHT: u32 = 22;

use super::data_source::IncrementalTableDataSource;
use super::filter_expr::{FilterCondition, FilterExpr};

/// Sort descriptor for a data grid column.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SortSpec {
    /// Zero-based source column index.
    pub column: usize,
    /// Descending sort when true.
    pub descending: bool,
}

/// Contains-based text filter bound to a source column.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ColumnFilter {
    /// Zero-based source column index.
    pub column: usize,
    /// Query token applied with case-insensitive contains.
    pub query: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct GridWindowCache {
    row_start: usize,
    row_len: usize,
    column_start: usize,
    column_len: usize,
    revision: u64,
    cells: Vec<Vec<Option<String>>>,
}

/// Virtualized data grid with windowed pull from incremental table data source.
pub struct DataGrid {
    base: BaseWidget,
    data_source: Option<Arc<dyn IncrementalTableDataSource>>,
    data_source_connection_scope: ConnectionScope,
    scroll_row: usize,
    scroll_column: usize,
    row_height: u32,
    column_width: u32,
    overscan_rows: usize,
    overscan_columns: usize,
    frozen_columns: usize,
    sort_specs: Vec<SortSpec>,
    filters: Vec<ColumnFilter>,
    /// The filter as a recursive expression.
    ///
    /// This is what `apply_filter_sort` evaluates; `filters` is derived from it, so
    /// the two cannot describe different filters.
    filter_expr: FilterExpr,
    window_cache: Option<GridWindowCache>,
    /// The projected `(row, column)` of the last press, or `None` when the press missed.
    ///
    /// Set through [`Self::cell_at`], so a selection can only ever name a cell that was
    /// actually painted.
    selection: Option<(usize, usize)>,
    /// The projected `(row, column)` under the pointer, or `None` when it is elsewhere.
    ///
    /// Set through the **same** [`Self::cell_at`] the press uses, so the cell a hover points at is
    /// the cell a click would select — the two cannot disagree about where a cell begins. A grid is a
    /// matrix of independent targets, so this has to name a cell rather than light the control.
    hovered_cell: Option<(usize, usize)>,
    /// Emitted when visible row/column window changes.
    pub visible_window_changed: Signal1<(usize, usize, usize, usize)>,
}

impl DataGrid {
    /// Creates an empty data grid.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Table, geometry, "DataGrid"),
            data_source: None,
            data_source_connection_scope: ConnectionScope::new(),
            scroll_row: 0,
            scroll_column: 0,
            row_height: 20,
            column_width: 120,
            overscan_rows: 2,
            overscan_columns: 1,
            frozen_columns: 0,
            sort_specs: Vec::new(),
            filters: Vec::new(),
            filter_expr: FilterExpr::MatchAll,
            window_cache: None,
            selection: None,
            hovered_cell: None,
            visible_window_changed: Signal1::new(),
        }
    }

    /// Binds incremental source.
    pub fn set_data_source(&mut self, data_source: Arc<dyn IncrementalTableDataSource>) {
        self.data_source_connection_scope = ConnectionScope::new();
        if let Some(changed) = data_source.data_changed_signal() {
            let redraw = self.base.redraw_requested_signal().clone();
            let layout = self.base.layout_requested_signal().clone();
            changed.connect_scoped(&self.data_source_connection_scope, move || {
                redraw.emit();
                layout.emit();
            });
        }
        self.data_source = Some(data_source);
        self.scroll_row = 0;
        self.scroll_column = 0;
        self.clear_cache();
        self.normalize_projection_state();
        self.emit_visible_window_changed();
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// Clears incremental source.
    pub fn clear_data_source(&mut self) {
        self.data_source_connection_scope = ConnectionScope::new();
        self.data_source = None;
        self.scroll_row = 0;
        self.scroll_column = 0;
        self.frozen_columns = 0;
        self.clear_cache();
        self.emit_visible_window_changed();
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// Returns whether source is bound.
    pub fn has_data_source(&self) -> bool {
        self.data_source.is_some()
    }

    /// Returns source row count.
    pub fn row_count(&self) -> usize {
        self.data_source.as_ref().map(|source| source.row_count()).unwrap_or(0)
    }

    /// Returns source column count.
    pub fn column_count(&self) -> usize {
        self.data_source.as_ref().map(|source| source.column_count()).unwrap_or(0)
    }

    /// Returns current vertical scroll row.
    pub fn scroll_row(&self) -> usize {
        self.scroll_row
    }

    /// The projected `(row, column)` of the current selection, if any.
    pub fn selection(&self) -> Option<(usize, usize)> {
        self.selection
    }

    /// Returns current horizontal scroll column.
    pub fn scroll_column(&self) -> usize {
        self.scroll_column
    }

    /// Sets vertical scroll row with clamping.
    pub fn set_scroll_row(&mut self, row: usize) {
        self.normalize_projection_state();
        let max_row = self.row_count().saturating_sub(1);
        let next = row.min(max_row);
        if next == self.scroll_row {
            return;
        }
        self.scroll_row = next;
        self.clear_cache();
        self.emit_visible_window_changed();
        self.base.request_redraw();
    }

    /// Sets horizontal scroll column with clamping.
    pub fn set_scroll_column(&mut self, column: usize) {
        self.normalize_projection_state();
        let max_column = self.column_count().saturating_sub(1);
        let next = column.min(max_column);
        if next == self.scroll_column {
            return;
        }
        self.scroll_column = next;
        self.clear_cache();
        self.emit_visible_window_changed();
        self.base.request_redraw();
    }

    /// Sets fixed row height.
    pub fn set_row_height(&mut self, row_height: u32) {
        let next = row_height.max(1);
        if self.row_height == next {
            return;
        }
        self.row_height = next;
        self.clear_cache();
        self.emit_visible_window_changed();
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// Returns row height.
    pub fn row_height(&self) -> u32 {
        self.row_height
    }

    /// Sets fixed column width.
    pub fn set_column_width(&mut self, column_width: u32) {
        let next = column_width.max(1);
        if self.column_width == next {
            return;
        }
        self.column_width = next;
        self.clear_cache();
        self.emit_visible_window_changed();
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// Returns column width.
    pub fn column_width(&self) -> u32 {
        self.column_width
    }

    /// Sets frozen leading columns, clamped to source column count.
    pub fn set_frozen_columns(&mut self, frozen_columns: usize) {
        let next = frozen_columns.min(self.column_count());
        if self.frozen_columns == next {
            return;
        }
        self.frozen_columns = next;
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// Returns frozen leading column count.
    pub fn frozen_columns(&self) -> usize {
        self.frozen_columns
    }

    /// Replaces sort spec list in priority order.
    pub fn set_sort_specs(&mut self, sort_specs: Vec<SortSpec>) {
        self.sort_specs = sort_specs;
        self.clear_cache();
        self.base.request_redraw();
    }

    /// Returns active sort specs.
    pub fn sort_specs(&self) -> &[SortSpec] {
        &self.sort_specs
    }

    /// Replaces the filter list with a flat conjunction of `contains` conditions.
    ///
    /// Kept as the simple spelling: a caller that wants "contains this text in this
    /// column" does not have to build a tree. Delegates to
    /// [`Self::set_filter_expr`] so the two spellings cannot diverge — the list is
    /// converted to one `And` of predicates, which is the semantics this method
    /// always had (an implicit AND, `apply_filter_sort`).
    pub fn set_filters(&mut self, filters: Vec<ColumnFilter>) {
        let expr = FilterExpr::from_conditions(
            filters
                .iter()
                .map(|filter| FilterCondition::contains(filter.column, filter.query.clone()))
                .collect(),
        );
        self.set_filter_expr(expr);
        // Kept in step so `filters()` reports what was set rather than what the
        // tree happens to flatten to (a caller may have set an `Or`/`Not` tree, in
        // which case the list is the predicates in reading order).
        self.filters = filters;
    }

    /// Returns the active filters as a flat list.
    ///
    /// The conditions of the **tree**, in reading order, so a grid whose filter was
    /// set through [`Self::set_filter_expr`] still reports them. Each condition's
    /// operator is dropped, because `ColumnFilter` has no operator field and
    /// inventing one here would be a second definition of the same thing.
    pub fn filters(&self) -> Vec<ColumnFilter> {
        self.filter_expr
            .conditions()
            .iter()
            .map(|condition| ColumnFilter {
                column: condition.column,
                query: condition.operand.clone(),
            })
            .collect()
    }

    /// Replaces the filter with a recursive expression.
    ///
    /// This is the model a query-builder UI produces (nested AND/OR, non-text
    /// operators), so "code sets a filter" and "a user builds one" share one
    /// evaluation path (principle #54).
    pub fn set_filter_expr(&mut self, filter_expr: FilterExpr) {
        self.filter_expr = filter_expr;
        self.clear_cache();
        self.base.request_redraw();
    }

    /// Returns the active filter expression.
    pub fn filter_expr(&self) -> &FilterExpr {
        &self.filter_expr
    }

    /// Returns `(row_start, row_len, col_start, col_len)` for visible+overscan window.
    pub fn visible_window(&self) -> (usize, usize, usize, usize) {
        let row_count = self.row_count();
        let column_count = self.column_count();
        if row_count == 0 || column_count == 0 {
            return (0, 0, 0, 0);
        }

        let row_start = self.scroll_row.saturating_sub(self.overscan_rows);
        let col_start = self.scroll_column.saturating_sub(self.overscan_columns);

        let visible_rows = self.visible_row_capacity();
        let visible_cols = self.visible_column_capacity();

        let row_fetch = visible_rows.saturating_add(self.overscan_rows.saturating_mul(2));
        let col_fetch = visible_cols.saturating_add(self.overscan_columns.saturating_mul(2));

        let row_end = row_start.saturating_add(row_fetch).min(row_count);
        let col_end = col_start.saturating_add(col_fetch).min(column_count);

        (row_start, row_end.saturating_sub(row_start), col_start, col_end.saturating_sub(col_start))
    }

    /// Fetches visible cells, applying filters and sort rules in window scope.
    pub fn fetch_visible_cells(&mut self) -> Vec<Vec<Option<String>>> {
        self.normalize_projection_state();

        let Some(source) = self.data_source.as_ref() else {
            return Vec::new();
        };

        let (row_start, row_len, col_start, col_len) = self.visible_window();
        if row_len == 0 || col_len == 0 {
            return Vec::new();
        }

        let revision = source.revision();
        if revision > 0 {
            if let Some(cache) = self.window_cache.as_ref() {
                if cache.row_start == row_start
                    && cache.row_len == row_len
                    && cache.column_start == col_start
                    && cache.column_len == col_len
                    && cache.revision == revision
                {
                    return self.apply_filter_sort(cache.cells.clone());
                }
            }
        }

        let cells = source.fetch_window(row_start, row_len, col_start, col_len);
        if revision > 0 {
            self.window_cache = Some(GridWindowCache {
                row_start,
                row_len,
                column_start: col_start,
                column_len: col_len,
                revision,
                cells: cells.clone(),
            });
        } else {
            self.window_cache = None;
        }

        self.apply_filter_sort(cells)
    }

    fn apply_filter_sort(&self, mut cells: Vec<Vec<Option<String>>>) -> Vec<Vec<Option<String>>> {
        // `is_noop` lets the whole `retain` pass be skipped when the filter cannot
        // reject anything, rather than walking every cell to conclude the same thing.
        if !self.filter_expr.is_noop() {
            cells.retain(|row| self.filter_expr.accepts(row));
        }

        if !self.sort_specs.is_empty() {
            cells.sort_by(|a, b| {
                for spec in &self.sort_specs {
                    let left = a
                        .get(spec.column)
                        .and_then(|cell| cell.as_ref())
                        .map(String::as_str)
                        .unwrap_or("");
                    let right = b
                        .get(spec.column)
                        .and_then(|cell| cell.as_ref())
                        .map(String::as_str)
                        .unwrap_or("");
                    let order = left.cmp(right);
                    if order != std::cmp::Ordering::Equal {
                        return if spec.descending { order.reverse() } else { order };
                    }
                }
                std::cmp::Ordering::Equal
            });
        }

        cells
    }

    fn visible_row_capacity(&self) -> usize {
        let height = self.base.geometry().height;
        if height == 0 {
            return 0;
        }
        ((height + self.row_height - 1) / self.row_height.max(1)) as usize
    }

    /// The area the cells may occupy: the grid's box minus the margin that keeps ink off the
    /// frame's stroke, with the column-title strip removed from the top.
    ///
    /// Both the draw pass and the hit test start here, so a cell's painted box and the box a
    /// press resolves to are the same rectangle by construction.
    fn cells_box(&self) -> Rect {
        let content = ControlMetrics::band_inset(self.base.geometry(), GRID_INSET);
        let height = content.height.saturating_sub(GRID_HEADER_HEIGHT);
        Rect::new(content.x, content.y + GRID_HEADER_HEIGHT as i32, content.width, height)
    }

    /// The box of the cell at `(row, column)` in the *projection* — the index the data source
    /// serves, including the scroll offset.
    ///
    /// This is a pure function of the indices, so the column a press lands in is the column
    /// that was painted for it. The draw loop used to advance its own `x += column_width`
    /// cursor, which made a cell's box depend on how many cells happened to precede it and
    /// left the two derivations free to disagree.
    fn cell_rect(&self, row: usize, column: usize) -> Rect {
        let cells = self.cells_box();
        let column = column.saturating_sub(self.scroll_column);
        Rect::new(
            cells.x + column as i32 * self.column_width as i32,
            cells.y + row as i32 * self.row_height as i32,
            self.column_width,
            self.row_height,
        )
    }

    /// The projected `(row, column)` a point falls in, or `None` when it misses every cell
    /// (including a press in the column-title strip or outside the grid).
    ///
    /// The inverse of [`Self::cell_rect`] and deliberately built on it: a point identifies a
    /// cell only when that cell's own box contains it, so a point in the gap left by a partial
    /// trailing column resolves to nothing rather than to a phantom cell.
    pub fn cell_at(&self, point: Point) -> Option<(usize, usize)> {
        let cells = self.cells_box();
        if !cells.contains_point(point) {
            return None;
        }
        // Integer division truncates toward zero, so a point left of the first column would
        // floor to `0` and name a cell that is not there. Compute the distance in signed
        // arithmetic and reject a negative distance instead; the alternative — offsetting by
        // `scroll_column` first — would only work because the scroll is non-negative, and
        // would silently name the wrong cell if it ever were not.
        let dx = point.x - cells.x;
        let dy = point.y - cells.y;
        if dx < 0 || dy < 0 {
            return None;
        }
        let column = self.scroll_column + dx as usize / self.column_width.max(1) as usize;
        let row = dy as usize / self.row_height.max(1) as usize;
        if column >= self.column_count() || row >= self.row_count() {
            return None;
        }
        self.cell_rect(row, column).contains_point(point).then_some((row, column))
    }

    fn visible_column_capacity(&self) -> usize {
        let width = self.base.geometry().width;
        if width == 0 {
            return 0;
        }
        ((width + self.column_width - 1) / self.column_width.max(1)) as usize
    }

    fn normalize_projection_state(&mut self) {
        let row_count = self.row_count();
        let col_count = self.column_count();
        if row_count == 0 {
            self.scroll_row = 0;
        } else if self.scroll_row >= row_count {
            self.scroll_row = row_count.saturating_sub(1);
        }
        if col_count == 0 {
            self.scroll_column = 0;
            self.frozen_columns = 0;
        } else {
            if self.scroll_column >= col_count {
                self.scroll_column = col_count.saturating_sub(1);
            }
            self.frozen_columns = self.frozen_columns.min(col_count);
        }
    }

    fn clear_cache(&mut self) {
        self.window_cache = None;
    }

    fn emit_visible_window_changed(&self) {
        self.visible_window_changed.emit(self.visible_window());
    }
}

impl Widget for DataGrid {
    fn base(&self) -> &BaseWidget {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(400, 300)
    }

    /// Reports this widget as the object that paints it.
    ///
    /// `DataGrid` implements `Draw`, so `Some(self)` is total and cannot be wrong.
    fn as_draw_mut(&mut self) -> Option<&mut dyn crate::widget::Draw> {
        Some(self)
    }

    impl_widget_property_hooks!();
}

/// `DataGrid`'s property contract.
///
/// This control is one of the fourteen the old centralised dispatch could not
/// reach. It shares `WidgetKind::Table` with `TableWidget`, so the
/// `WidgetKind::Table` arms downcast to `TableWidget` and a `DataGrid` answered
/// `UnsupportedOnWidget` for **every** property — despite
/// `DATA_GRID_PROPERTIES` describing a full contract for it. Declaring the
/// contract here makes it reachable, which is the whole point of moving the
/// contract onto the control (BLUE15 rule #67).
///
/// The property set follows `DATA_GRID_PROPERTIES`: the two counts and the two
/// item collections are derived state and therefore read-only, while the viewport
/// and sizing knobs are writable.
impl WidgetProperties for DataGrid {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "has_data_source" => Ok(CapabilityValue::Bool(self.has_data_source())),
            "row_count" => Ok(CapabilityValue::UInt(self.row_count() as u64)),
            "column_count" => Ok(CapabilityValue::UInt(self.column_count() as u64)),
            "scroll_row" => Ok(CapabilityValue::UInt(self.scroll_row() as u64)),
            "scroll_column" => Ok(CapabilityValue::UInt(self.scroll_column() as u64)),
            "row_height" => Ok(CapabilityValue::UInt(self.row_height() as u64)),
            "column_width" => Ok(CapabilityValue::UInt(self.column_width() as u64)),
            "frozen_columns" => Ok(CapabilityValue::UInt(self.frozen_columns() as u64)),
            "sort_spec_count" => Ok(CapabilityValue::UInt(self.sort_specs().len() as u64)),
            // The count is of *conditions*, not of `ColumnFilter`s: a tree with a
            // nested `And` holds more conditions than the flat list would, and the
            // number a query-builder UI shows is the condition count.
            "filter_count" => {
                Ok(CapabilityValue::UInt(self.filter_expr().condition_count() as u64))
            }
            "sort_specs" => Ok(CapabilityValue::String(sort_specs_to_string(self.sort_specs()))),
            "filters" => Ok(CapabilityValue::String(column_filters_to_string(&self.filters()))),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "scroll_row" => {
                self.set_scroll_row(expect_usize(value)?);
                Ok(())
            }
            "scroll_column" => {
                self.set_scroll_column(expect_usize(value)?);
                Ok(())
            }
            "row_height" => {
                self.set_row_height(expect_usize(value)? as u32);
                Ok(())
            }
            "column_width" => {
                self.set_column_width(expect_usize(value)? as u32);
                Ok(())
            }
            "frozen_columns" => {
                self.set_frozen_columns(expect_usize(value)?);
                Ok(())
            }
            "sort_specs" => {
                self.set_sort_specs(expect_sort_specs(value)?);
                Ok(())
            }
            "filters" => {
                self.set_filters(expect_column_filters(value)?);
                Ok(())
            }
            // Derived and structural state: presented but not settable, matching
            // `DATA_GRID_PROPERTIES`' `writable: false` entries.
            "has_data_source" | "row_count" | "column_count" | "sort_spec_count"
            | "filter_count" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "has_data_source",
            "row_count",
            "column_count",
            "scroll_row",
            "scroll_column",
            "row_height",
            "column_width",
            "frozen_columns",
            "sort_spec_count",
            "filter_count",
            "sort_specs",
            "filters",
            BASE_PROPERTY_NAMES
        ]
    }

    /// Runs one of the commands `data_grid` publishes.
    ///
    /// `clear_data_source` is payload-free and executes here. The remaining names
    /// need a payload (a source, an index, a size) and are answered through the
    /// property route.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "clear_data_source" => {
                self.clear_data_source();
                Ok(())
            }
            "set_data_source" | "set_scroll_row" | "set_scroll_column" | "set_row_height"
            | "set_column_width" | "set_frozen_columns" => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl Draw for DataGrid {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.base.geometry();

        // Chrome colours resolve explicit style first, then the theme's resolved style for
        // this control, and only then a literal. The theme step is what makes an appearance
        // switch visible; the surface, the cell fills, the borders and the text colour used
        // to be hardcoded literals, so light and dark rendered identically.
        //
        // The theme reads take and release the global manager's lock internally, so no guard
        // is held across the draw (the mutex is not re-entrant). `data_grid` reaches the
        // theme through its `table` classification, which is `Input` — an interior that
        // moves with the appearance.
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("data_grid");
        let mut surface = style
            .background_color
            .or_else(|| theme.as_ref().and_then(|t| t.background_color))
            .unwrap_or(Color::WHITE);
        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(Color::BLACK);
        // `data_grid` is absent from `WidgetRole::for_kind_name`'s table, so it classifies as
        // `Surface` and resolves to `theme.colors.background` — the window's own fill. A panel
        // painted in that colour would be byte-identical to the frame behind it, so a resolved
        // surface equal to the window fill is re-derived a visible step away from it, the same
        // distinction `Colors::input_background` draws for a field.
        let window_fill = crate::style::theme_manager()
            .current_theme()
            .map(|active| active.colors.background)
            .unwrap_or(Color::WHITE);
        if surface == window_fill {
            surface = window_fill.blend(&ink, 0.08);
        }
        let border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .filter(|resolved| *resolved != surface)
            .unwrap_or_else(|| surface.blend(&ink, 0.20));
        // Cell chrome is derived from the surface rather than picked as a second literal, so
        // the grid reads as inset in either appearance.
        let cell_border = surface.blend(&ink, 0.10);
        // The accent is the theme's `primary`: the hue a theme is expected to vary most, so
        // the frozen-column indicator follows the appearance rather than staying a literal blue.
        let accent = crate::style::theme_manager()
            .current_theme()
            .map(|active| active.colors.primary)
            .unwrap_or(Color::PRIMARY);

        context.fill_rect(rect, surface);
        context.draw_rect(rect, border);

        let rows = self.fetch_visible_cells();
        if rows.is_empty() {
            return;
        }

        // The cells are laid out from the control's inset content box, not from its literal
        // top edge. The first row used to start at `rect.y`, so its border and its glyph box
        // sat on the frame's own stroke; the inset also leaves a header row's worth of room
        // above the first cell, which is what a grid reads as its column-title strip.
        let cells = self.cells_box();
        let cells_right = cells.x + cells.width as i32;
        let cells_bottom = cells.y + cells.height as i32;

        // Every cell's box comes from `cell_rect`, the same derivation `cell_at` reads, so a
        // painted cell and the cell a press resolves to can never drift apart.
        for (row_idx, row) in rows.iter().enumerate() {
            if self.cell_rect(row_idx, 0).y >= cells_bottom {
                break;
            }

            for (col_idx, cell) in row.iter().enumerate() {
                let cell_rect = self.cell_rect(row_idx, col_idx);
                if cell_rect.x >= cells_right {
                    break;
                }
                context.draw_rect(cell_rect, cell_border);
                if let Some(text) = cell {
                    // Guarded on the text being non-empty: an unguarded draw of an empty cell
                    // emits `<text …></text>`, an element the rasteriser never produces.
                    if !text.is_empty() {
                        // The cell is the band. Centring by handing `y + row_h / 2` to
                        // `draw_text` put the glyph box's *top* edge on the cell's middle
                        // line, so every value sat half a line low; `text_line` derives the
                        // real centred box. Fitting as well keeps a long value inside its own
                        // column instead of bleeding right.
                        context.draw_text_fitted(
                            context.text_line(cell_rect, &Font::default()),
                            text,
                            &Font::default(),
                            ink,
                            HorizontalAlignment::Left,
                        );
                    }
                }
            }
        }

        // ── Selection and hover, painted **over** the cells ──
        //
        // The selection was stored and never drawn: a press set `self.selection`, re-requested a
        // redraw, and the grid came back looking exactly the same. A stored state with no consumer
        // is the same shape as a declared token with no consumer — the user cannot tell a selected
        // cell from any other. It is drawn here, over the cell borders, so the marker is not
        // overpainted by the next row's line.
        //
        // The hover is the accent at **lower** alpha: pointer position rather than a committed
        // choice, so it points at the cell a click would select without competing with the one
        // already selected. Both come from `cell_rect`, the same derivation `cell_at` reads, so a
        // highlighted cell is always a cell that can be hit.
        if let Some((row, column)) = self.hovered_cell {
            if Some((row, column)) != self.selection {
                let box_rect = self.cell_rect(row, column);
                context.draw_rect_stroke(box_rect, accent.with_alpha(120), 1);
            }
        }
        if let Some((row, column)) = self.selection {
            let box_rect = self.cell_rect(row, column);
            context.draw_rect_stroke(box_rect, accent, 2);
        }

        if self.frozen_columns > 0 {
            let split_x = cells.x + (self.frozen_columns as i32) * self.column_width as i32;
            if split_x > cells.x {
                context.draw_line(
                    Point::new(split_x, cells.y),
                    Point::new(split_x, cells.y + cells.height as i32),
                    accent,
                );
            }
        }
    }
}

impl crate::event::EventHandler for DataGrid {
    fn handle_event(&mut self, event: &Event) {
        // The base keeps the control-level hover/press facts and answers `widget_state()`. This
        // handler did not forward to it, so `"data_grid:hover"` could never fire.
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }

        if let Event::Wheel { delta, .. } = event {
            let lines = ((delta.y.abs() / 120).max(1)) as isize;
            if delta.y < 0 {
                let next = self.scroll_row.saturating_add(lines as usize);
                self.set_scroll_row(next);
            } else if delta.y > 0 {
                let up = self.scroll_row.saturating_sub(lines as usize);
                self.set_scroll_row(up);
            }
        }

        if let Event::MousePress { pos, button } = event {
            if *button != 1 {
                return;
            }
            // The press resolves through `cell_at`, which reads `cell_rect` — the same
            // derivation the draw pass uses — so a selection can only name a cell that was
            // actually painted. A press in the column-title strip or in a partial trailing
            // column resolves to nothing.
            let hit = self.cell_at(*pos);
            if hit != self.selection {
                self.selection = hit;
                self.base.request_redraw();
            }
        }

        match event {
            // Cell hover, from the same `cell_at` the press reads: the cell that is outlined is the
            // cell a click would select. A pointer that leaves the cells (into the title strip, past
            // the last column, or off the control) clears it rather than latching the last cell it
            // crossed.
            Event::MouseMove { pos } => {
                let hovered = self.cell_at(*pos);
                if hovered != self.hovered_cell {
                    self.hovered_cell = hovered;
                    self.base.request_redraw();
                }
            }
            Event::MouseLeave { .. } => {
                let had_hover = self.hovered_cell.take().is_some();
                if had_hover {
                    self.base.request_redraw();
                }
            }
            _ => { /* The wheel and press arms above already handled those. */ }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::types::EventHandler;
    use crate::signal::GenericSignal;
    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
    use std::sync::Mutex;

    struct StaticSource {
        rows: usize,
        cols: usize,
        data: Vec<Vec<String>>,
    }

    impl IncrementalTableDataSource for StaticSource {
        fn row_count(&self) -> usize {
            self.rows
        }

        fn column_count(&self) -> usize {
            self.cols
        }

        fn data(&self, row: usize, column: usize) -> Option<String> {
            self.data.get(row).and_then(|line| line.get(column)).cloned()
        }
    }

    /// A cell's box must be a pure function of its own projected indices.
    ///
    /// The draw loop used to advance its own `x += column_width` cursor, so a cell's box
    /// depended on how many cells happened to precede it in the fetched window. Both the draw
    /// pass and `cell_at` now read `cell_rect`, so this pins the closed form.
    #[test]
    fn a_cells_box_is_a_function_of_its_own_indices() {
        let grid = DataGrid::new(Rect::new(0, 0, 400, 300));
        let cells = grid.cells_box();

        assert_eq!(grid.cell_rect(0, 0), Rect::new(cells.x, cells.y, 120, 20));
        assert_eq!(grid.cell_rect(0, 2).x, cells.x + 240);
        assert_eq!(grid.cell_rect(3, 0).y, cells.y + 60);
        assert_eq!(grid.cell_rect(3, 0).width, 120);
        assert_eq!(grid.cell_rect(3, 0).height, 20);

        // Idempotent: asking twice names the same box.
        assert_eq!(grid.cell_rect(1, 1), grid.cell_rect(1, 1));

        // The cells start below the column-title strip, never on the frame's own stroke.
        assert!(grid.cells_box().y > 0, "cells must clear the column-title strip");
        assert!(grid.cells_box().height < 300, "the title strip must be removed");
    }

    /// The box a press resolves to must be the box that was painted for that cell.
    #[test]
    fn the_cell_a_press_resolves_to_is_the_cell_that_was_painted() {
        // The grid is wider than four 120 px columns so that column 3's centre falls inside
        // the control — a cell whose centre is past the right edge cannot be probed at all,
        // because nothing is painted there.
        let mut grid = DataGrid::new(Rect::new(0, 0, 900, 300));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 4,
            cols: 4,
            data: (0..4).map(|r| (0..4).map(|c| format!("{}:{}", r, c)).collect()).collect(),
        }));

        let target = grid.cell_rect(2, 3);
        let centre =
            Point::new(target.x + target.width as i32 / 2, target.y + target.height as i32 / 2);
        assert_eq!(grid.cell_at(centre), Some((2, 3)));
        assert_eq!(grid.selection(), None, "merely probing must not select");

        // The box that *was* painted is the box a press resolves to, so the same point names
        // the same cell for probing and for pressing.
        grid.handle_event(&Event::MousePress { pos: centre, button: 1 });
        assert_eq!(grid.selection(), Some((2, 3)));

        // A press in the column-title strip or outside the grid resolves to nothing rather
        // than to a phantom cell.
        assert_eq!(grid.cell_at(Point::new(centre.x, 1)), None);
        assert_eq!(grid.cell_at(Point::new(-5, -5)), None);

        let below = Point::new(centre.x, target.y + 20 * 100);
        grid.handle_event(&Event::MousePress { pos: below, button: 1 });
        assert_eq!(grid.selection(), None, "a press on empty space must clear the selection");
    }

    /// A selected cell is **painted** as selected, and a hovered cell is marked more faintly.
    ///
    /// # The defect this pins
    ///
    /// `selection` was stored and never drawn: a press set the field, re-requested a redraw, and the
    /// grid came back byte-identical. A stored state with no consumer is the same shape as a declared
    /// token with no consumer, and this one is a *user-visible* one — the user cannot tell the cell
    /// they clicked from any other.
    ///
    /// # Why the assertion counts accent strokes rather than comparing documents
    ///
    /// "The document changed" would also be satisfied by the hover outline or by the frozen-column
    /// rule. The marker is emitted as a `<rect ... stroke="..." stroke-width="2" />` in the accent
    /// colour, so counting elements carrying that stroke names exactly the element under test.
    #[test]
    #[cfg(all(device_profile, feature = "desktop"))]
    fn a_selected_cell_is_painted_as_selected() {
        let _guard = crate::style::theme_test_guard();
        crate::widget::census::install_preset_appearances();
        crate::theme::global_theme_manager().set_appearance(crate::theme::AppearanceMode::Light);

        let mut grid = DataGrid::new(Rect::new(0, 0, 400, 300));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 4,
            cols: 4,
            data: (0..4).map(|r| (0..4).map(|c| format!("{r}:{c}")).collect()).collect(),
        }));

        let target = grid.cell_rect(1, 1);
        let centre =
            Point::new(target.x + target.width as i32 / 2, target.y + target.height as i32 / 2);

        let before = width_two_strokes(&mut grid);
        assert_eq!(before, 0, "an untouched grid draws no selection marker");

        grid.handle_event(&Event::MousePress { pos: centre, button: 1 });
        assert_eq!(grid.selection(), Some((1, 1)));
        let after = width_two_strokes(&mut grid);
        assert_eq!(
            after,
            before + 1,
            "selecting a cell must paint exactly one selection marker (had {before}, now {after})"
        );
    }

    /// How many SVG `<rect>` strokes are drawn at width 2 — how the selection marker is emitted.
    #[cfg(all(device_profile, feature = "desktop"))]
    fn width_two_strokes(grid: &mut DataGrid) -> usize {
        let rect = grid.geometry();
        let svg = crate::widget::svg::render_widget_to_svg(grid, rect);
        svg.match_indices("stroke-width=\"2\"").count()
    }

    /// Scrolling moves the mapping from a point to a cell along with the cells themselves.
    ///
    /// The scroll offset is applied inside `cell_rect`, so a press at a fixed point names a
    /// later column once the grid has scrolled left; the painted box and the resolved cell
    /// move together.
    #[test]
    fn scrolling_moves_the_point_to_cell_mapping_with_the_cells() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 400, 300));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 4,
            cols: 8,
            data: (0..4).map(|r| (0..8).map(|c| format!("{}:{}", r, c)).collect()).collect(),
        }));

        let first = grid.cell_rect(0, 0);
        let probe = Point::new(first.x + 5, first.y + 5);
        assert_eq!(grid.cell_at(probe), Some((0, 0)));

        grid.set_scroll_column(2);
        // The first painted column is now projected column 2, so the same point names it.
        assert_eq!(grid.cell_at(probe), Some((0, 2)));
        assert_eq!(grid.cell_rect(0, 2), grid.cell_rect(0, 0));

        // The projected column just right of the probe is one further along, so the mapping
        // really is continuous across the column boundary rather than pinned to a single cell.
        assert_eq!(grid.cell_at(Point::new(first.x + 120 + 5, probe.y)), Some((0, 3)));

        // A point left of the cells box — the frame margin the control does not paint in —
        // resolves to nothing. This is where truncating `usize` division used to go wrong: it
        // floored a negative distance to `0` and named a phantom column.
        assert_eq!(
            grid.cell_at(Point::new(first.x - 1, probe.y)),
            None,
            "the frame margin is not a cell"
        );
    }

    #[test]
    fn visible_window_includes_overscan_and_clamps() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 240, 60));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 10,
            cols: 6,
            data: (0..10).map(|r| (0..6).map(|c| format!("{}:{}", r, c)).collect()).collect(),
        }));

        assert_eq!(grid.visible_window(), (0, 7, 0, 4));

        grid.set_scroll_row(8);
        grid.set_scroll_column(5);
        let window = grid.visible_window();
        assert_eq!(window.0, 6);
        assert_eq!(window.2, 4);
        assert!(window.1 <= 4);
        assert!(window.3 <= 2);
    }

    #[test]
    fn filter_and_sort_apply_to_window_rows() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 240, 80));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 4,
            cols: 2,
            data: vec![
                vec!["u1".to_string(), "alice".to_string()],
                vec!["u2".to_string(), "bob".to_string()],
                vec!["u3".to_string(), "bruce".to_string()],
                vec!["u4".to_string(), "zoe".to_string()],
            ],
        }));
        grid.set_filters(vec![ColumnFilter { column: 1, query: "b".to_string() }]);
        grid.set_sort_specs(vec![SortSpec { column: 1, descending: true }]);

        let rows = grid.fetch_visible_cells();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0][1], Some("bruce".to_string()));
        assert_eq!(rows[1][1], Some("bob".to_string()));
    }

    #[test]
    fn frozen_columns_clamp_to_column_count() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 200, 60));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 2,
            cols: 3,
            data: vec![
                vec!["a".to_string(), "b".to_string(), "c".to_string()],
                vec!["d".to_string(), "e".to_string(), "f".to_string()],
            ],
        }));

        grid.set_frozen_columns(99);
        assert_eq!(grid.frozen_columns(), 3);

        grid.clear_data_source();
        assert_eq!(grid.frozen_columns(), 0);
    }

    #[test]
    fn new_creates_default_state() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        assert!(!grid.has_data_source());
        assert_eq!(grid.scroll_row(), 0);
        assert_eq!(grid.scroll_column(), 0);
        assert_eq!(grid.row_height(), 20);
        assert_eq!(grid.column_width(), 120);
        assert_eq!(grid.frozen_columns(), 0);
        assert!(grid.sort_specs().is_empty());
        assert!(grid.filters().is_empty());
        assert_eq!(grid.row_count(), 0);
        assert_eq!(grid.column_count(), 0);
        assert!(grid.fetch_visible_cells().is_empty());
    }

    #[test]
    fn has_data_source_before_and_after() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        assert!(!grid.has_data_source());

        grid.set_data_source(Arc::new(StaticSource {
            rows: 3,
            cols: 3,
            data: vec![
                vec!["a".to_string(), "b".to_string(), "c".to_string()],
                vec!["d".to_string(), "e".to_string(), "f".to_string()],
                vec!["g".to_string(), "h".to_string(), "i".to_string()],
            ],
        }));
        assert!(grid.has_data_source());

        grid.clear_data_source();
        assert!(!grid.has_data_source());
    }

    #[test]
    fn row_and_column_count_queries() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        assert_eq!(grid.row_count(), 0);
        assert_eq!(grid.column_count(), 0);

        grid.set_data_source(Arc::new(StaticSource { rows: 5, cols: 4, data: vec![] }));
        assert_eq!(grid.row_count(), 5);
        assert_eq!(grid.column_count(), 4);

        grid.clear_data_source();
        assert_eq!(grid.row_count(), 0);
        assert_eq!(grid.column_count(), 0);
    }

    #[test]
    fn scroll_position_clamping() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 10,
            cols: 6,
            data: (0..10).map(|r| (0..6).map(|c| format!("{}:{}", r, c)).collect()).collect(),
        }));

        grid.set_scroll_row(5);
        assert_eq!(grid.scroll_row(), 5);

        grid.set_scroll_row(999);
        assert_eq!(grid.scroll_row(), 9);

        grid.set_scroll_column(3);
        assert_eq!(grid.scroll_column(), 3);

        grid.set_scroll_column(999);
        assert_eq!(grid.scroll_column(), 5);
    }

    #[test]
    fn clear_data_source_resets_state() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        grid.set_data_source(Arc::new(StaticSource { rows: 5, cols: 3, data: vec![] }));
        grid.set_scroll_row(2);
        grid.set_scroll_column(1);
        grid.set_frozen_columns(2);
        grid.set_sort_specs(vec![SortSpec { column: 0, descending: false }]);

        grid.clear_data_source();
        assert!(!grid.has_data_source());
        assert_eq!(grid.scroll_row(), 0);
        assert_eq!(grid.scroll_column(), 0);
        assert_eq!(grid.frozen_columns(), 0);
        assert!(grid.fetch_visible_cells().is_empty());
    }

    #[test]
    fn sort_specs_set_get_invalidate_cache() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 3,
            cols: 2,
            data: vec![
                vec!["c".to_string(), "x".to_string()],
                vec!["a".to_string(), "y".to_string()],
                vec!["b".to_string(), "z".to_string()],
            ],
        }));

        assert!(grid.sort_specs().is_empty());

        let specs = vec![SortSpec { column: 0, descending: false }];
        grid.set_sort_specs(specs.clone());
        assert_eq!(grid.sort_specs().len(), 1);
        assert_eq!(grid.sort_specs()[0].column, 0);

        // Fetch with sort applied
        let rows = grid.fetch_visible_cells();
        assert_eq!(rows.len(), 3);
        assert_eq!(rows[0][0], Some("a".to_string()));
        assert_eq!(rows[1][0], Some("b".to_string()));
        assert_eq!(rows[2][0], Some("c".to_string()));

        // Change sort - should clear cache
        grid.set_sort_specs(vec![SortSpec { column: 0, descending: true }]);
        let rows2 = grid.fetch_visible_cells();
        assert_eq!(rows2[0][0], Some("c".to_string()));
        assert_eq!(rows2[2][0], Some("a".to_string()));

        grid.set_sort_specs(Vec::new());
        assert!(grid.sort_specs().is_empty());
    }

    #[test]
    fn filters_set_get_invalidate_cache() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 4,
            cols: 2,
            data: vec![
                vec!["apple".to_string(), "red".to_string()],
                vec!["banana".to_string(), "yellow".to_string()],
                vec!["cherry".to_string(), "red".to_string()],
                vec!["date".to_string(), "brown".to_string()],
            ],
        }));

        assert!(grid.filters().is_empty());

        let filters = vec![ColumnFilter { column: 1, query: "red".to_string() }];
        grid.set_filters(filters.clone());
        assert_eq!(grid.filters().len(), 1);

        let rows = grid.fetch_visible_cells();
        assert_eq!(rows.len(), 2);
        assert_eq!(rows[0][0], Some("apple".to_string()));
        assert_eq!(rows[1][0], Some("cherry".to_string()));

        // Change filter - should recalc
        grid.set_filters(vec![ColumnFilter { column: 0, query: "b".to_string() }]);
        let rows2 = grid.fetch_visible_cells();
        assert_eq!(rows2.len(), 1);
        assert_eq!(rows2[0][0], Some("banana".to_string()));

        grid.set_filters(Vec::new());
        assert!(grid.filters().is_empty());
    }

    #[test]
    fn frozen_columns_set_get() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        grid.set_data_source(Arc::new(StaticSource { rows: 2, cols: 5, data: vec![] }));

        assert_eq!(grid.frozen_columns(), 0);

        grid.set_frozen_columns(3);
        assert_eq!(grid.frozen_columns(), 3);

        // Clamped to column count
        grid.set_frozen_columns(999);
        assert_eq!(grid.frozen_columns(), 5);
    }

    #[test]
    fn visible_window_changed_signal_emission() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 240, 60));
        grid.set_data_source(Arc::new(StaticSource {
            rows: 10,
            cols: 6,
            data: (0..10).map(|r| (0..6).map(|c| format!("{}:{}", r, c)).collect()).collect(),
        }));

        let emitted = Arc::new(Mutex::new(false));
        let sink = emitted.clone();
        grid.visible_window_changed.connect(move |_win| {
            *sink.lock().unwrap() = true;
        });

        grid.set_scroll_row(3);
        assert!(*emitted.lock().unwrap());
    }

    #[test]
    fn empty_source_returns_empty_window() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        grid.set_data_source(Arc::new(StaticSource { rows: 0, cols: 0, data: vec![] }));

        assert_eq!(grid.visible_window(), (0, 0, 0, 0));
        assert!(grid.fetch_visible_cells().is_empty());
    }

    struct RevisionSource {
        rows: usize,
        cols: usize,
        rev: AtomicU64,
        changed: GenericSignal,
        call_count: AtomicUsize,
    }

    impl RevisionSource {
        fn new(rows: usize, cols: usize) -> Self {
            Self {
                rows,
                cols,
                rev: AtomicU64::new(1),
                changed: GenericSignal::new(),
                call_count: AtomicUsize::new(0),
            }
        }

        fn bump(&self) {
            self.rev.fetch_add(1, Ordering::Relaxed);
            self.changed.emit();
        }
    }

    impl IncrementalTableDataSource for RevisionSource {
        fn row_count(&self) -> usize {
            self.rows
        }

        fn column_count(&self) -> usize {
            self.cols
        }

        fn data(&self, row: usize, column: usize) -> Option<String> {
            self.call_count.fetch_add(1, Ordering::Relaxed);
            Some(format!("{}:{}", row, column))
        }

        fn revision(&self) -> u64 {
            self.rev.load(Ordering::Relaxed)
        }

        fn data_changed_signal(&self) -> Option<&GenericSignal> {
            Some(&self.changed)
        }
    }

    #[test]
    fn cache_invalidation_on_revision_change() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 240, 60));
        let source = Arc::new(RevisionSource::new(10, 4));
        grid.set_data_source(source.clone());

        let _a = grid.fetch_visible_cells();
        let calls_after_a = source.call_count.load(Ordering::Relaxed);
        assert!(calls_after_a > 0);

        // Second fetch should hit cache
        let _b = grid.fetch_visible_cells();
        assert_eq!(source.call_count.load(Ordering::Relaxed), calls_after_a);

        // Bump revision -> cache invalidated
        source.bump();
        let _c = grid.fetch_visible_cells();
        assert!(source.call_count.load(Ordering::Relaxed) > calls_after_a);
    }

    #[test]
    fn row_height_and_column_width_minimum_clamp() {
        let mut grid = DataGrid::new(Rect::new(0, 0, 800, 600));
        grid.set_data_source(Arc::new(StaticSource { rows: 3, cols: 3, data: vec![] }));

        grid.set_row_height(0);
        assert_eq!(grid.row_height(), 1);

        grid.set_row_height(25);
        assert_eq!(grid.row_height(), 25);

        grid.set_column_width(0);
        assert_eq!(grid.column_width(), 1);

        grid.set_column_width(100);
        assert_eq!(grid.column_width(), 100);
    }
}