tastty-driver 0.1.0

Terminal automation driver built on tastty
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
//! Style enumeration and filtering over [`Snapshot`].
//!
//! [`Snapshot::styles`] groups visible cells by [`Attrs`] with counts and a
//! text sample. [`Snapshot::style_matches`] returns cells satisfying a
//! [`StyleFilter`], coalesced into per-row spans.
//!
//! Wide-character continuation cells are skipped; one display glyph counts
//! once. Row bounds are inclusive and clamp to the visible screen.

use std::collections::HashMap;

use tastty::{Attrs, Color};

use crate::snapshot::{CellSnapshot, Snapshot};

/// Inclusive range of zero-based visible row indices.
///
/// Iteration clamps each bound to the snapshot's row count, so a range
/// that runs past the visible region returns only the rows that exist.
/// A range whose start is already past the last visible row produces
/// an empty result.
///
/// The variants cover the four shapes a typical caller threads through
/// from optional `(start, end)` inputs without ever reaching for a
/// sentinel value:
///
/// - [`RowRange::All`] -- both bounds unspecified.
/// - [`RowRange::Range`] -- both bounds specified.
/// - [`RowRange::From`] -- start specified, no upper bound.
/// - [`RowRange::UpTo`] -- end specified, start at row 0.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
pub enum RowRange {
    /// Every visible row in the snapshot.
    #[default]
    All,
    /// Inclusive range `start..=end`. Both bounds are zero-based; the
    /// upper bound clamps to the last visible row at iteration time.
    Range(u16, u16),
    /// Rows from `start` through the last visible row, inclusive.
    From(u16),
    /// Rows `0..=end`, with `end` clamped to the last visible row.
    UpTo(u16),
}

impl RowRange {
    /// Every visible row in the snapshot.
    #[must_use]
    pub const fn all() -> Self {
        Self::All
    }

    /// Inclusive range from `start` through `end`.
    #[must_use]
    pub const fn new(start: u16, end: u16) -> Self {
        Self::Range(start, end)
    }

    /// Rows from `start` through the last visible row.
    #[must_use]
    pub const fn from(start: u16) -> Self {
        Self::From(start)
    }

    /// Rows `0..=end`.
    #[must_use]
    pub const fn up_to(end: u16) -> Self {
        Self::UpTo(end)
    }

    /// A single visible row.
    #[must_use]
    pub const fn single(row: u16) -> Self {
        Self::Range(row, row)
    }
}

/// Color predicate used by [`StyleFilter`].
///
/// `Named` matches the standard ANSI color names against palette indices
/// 0 through 15. A plain name like `"red"` matches both the normal and
/// bright variants of that color (indices 1 and 9). A `bright_`-prefixed
/// name like `"bright_red"` matches only the bright variant (index 9).
/// Names other than the sixteen ANSI color names never match.
#[derive(Clone, Debug, Eq, PartialEq, Hash)]
#[non_exhaustive]
pub enum ColorFilter {
    /// Match the terminal default color slot.
    Default,
    /// Match any explicitly set color.
    NonDefault,
    /// Match a palette entry by ANSI color name.
    Named(String),
    /// Match a specific palette index in the 0 through 255 range.
    Index(u8),
    /// Match a specific true-color RGB value.
    Rgb {
        /// Red channel.
        r: u8,
        /// Green channel.
        g: u8,
        /// Blue channel.
        b: u8,
    },
}

impl ColorFilter {
    fn matches(&self, color: Color) -> bool {
        match self {
            ColorFilter::Default => color.is_default(),
            ColorFilter::NonDefault => !color.is_default(),
            ColorFilter::Named(name) => match color.as_index() {
                Some(idx) => name_matches_index(name, idx),
                None => false,
            },
            ColorFilter::Index(value) => color.as_index() == Some(*value),
            ColorFilter::Rgb { r, g, b } => color.as_rgb() == Some((*r, *g, *b)),
        }
    }
}

fn name_matches_index(name: &str, idx: u8) -> bool {
    match ansi_name_indices(name) {
        Some((primary, bright)) => idx == primary || bright == Some(idx),
        None => false,
    }
}

fn ansi_name_indices(name: &str) -> Option<(u8, Option<u8>)> {
    match name {
        "black" => Some((0, Some(8))),
        "red" => Some((1, Some(9))),
        "green" => Some((2, Some(10))),
        "yellow" => Some((3, Some(11))),
        "blue" => Some((4, Some(12))),
        "magenta" => Some((5, Some(13))),
        "cyan" => Some((6, Some(14))),
        "white" => Some((7, Some(15))),
        "bright_black" => Some((8, None)),
        "bright_red" => Some((9, None)),
        "bright_green" => Some((10, None)),
        "bright_yellow" => Some((11, None)),
        "bright_blue" => Some((12, None)),
        "bright_magenta" => Some((13, None)),
        "bright_cyan" => Some((14, None)),
        "bright_white" => Some((15, None)),
        _ => None,
    }
}

/// Conjunctive predicate over [`Attrs`].
///
/// Every populated field must match for the filter to accept a cell. An
/// empty filter accepts every cell. Setting [`StyleFilter::negate`]
/// inverts the result after all populated predicates are evaluated, so
/// an empty negated filter rejects every cell.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct StyleFilter {
    /// Foreground color predicate.
    pub fg: Option<ColorFilter>,
    /// Background color predicate.
    pub bg: Option<ColorFilter>,
    /// Required bold state.
    pub bold: Option<bool>,
    /// Required dim intensity state.
    pub dim: Option<bool>,
    /// Required italic state.
    pub italic: Option<bool>,
    /// Required underline state.
    pub underline: Option<bool>,
    /// Required inverse-video state.
    pub inverse: Option<bool>,
    /// Invert the result after all populated predicates are evaluated.
    pub negate: bool,
}

impl StyleFilter {
    /// Return whether `attrs` satisfies the filter.
    #[must_use]
    pub fn matches(&self, attrs: &Attrs) -> bool {
        let positive = self.matches_positive(attrs);
        if self.negate { !positive } else { positive }
    }

    fn matches_positive(&self, attrs: &Attrs) -> bool {
        if let Some(ref fg) = self.fg
            && !fg.matches(attrs.fg_color)
        {
            return false;
        }
        if let Some(ref bg) = self.bg
            && !bg.matches(attrs.bg_color)
        {
            return false;
        }
        if let Some(bold) = self.bold
            && attrs.bold() != bold
        {
            return false;
        }
        if let Some(dim) = self.dim
            && attrs.dim() != dim
        {
            return false;
        }
        if let Some(italic) = self.italic
            && attrs.italic() != italic
        {
            return false;
        }
        if let Some(underline) = self.underline
            && attrs.underline() != underline
        {
            return false;
        }
        if let Some(inverse) = self.inverse
            && attrs.inverse() != inverse
        {
            return false;
        }
        true
    }
}

/// Distinct styles found within a row range with counts and samples.
///
/// Entries sort with the default [`Attrs`] first, then by descending
/// non-empty cell count.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct StyleInventory {
    /// One entry per distinct [`Attrs`] value seen in the queried range.
    pub entries: Vec<StyleInventoryEntry>,
}

/// One row in [`StyleInventory`].
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct StyleInventoryEntry {
    /// The full SGR attributes shared by this entry's cells.
    pub attrs: Attrs,
    /// Number of visible cells with non-empty content carrying this style.
    pub cell_count: u32,
    /// Number of distinct rows containing this style.
    pub row_count: u16,
    /// Zero-based row indices that contain this style, in ascending order.
    pub rows: Vec<u16>,
    /// First contiguous run of non-empty text observed with this style,
    /// truncated to 60 characters.
    pub sample: String,
}

/// Cells whose [`Attrs`] satisfy a [`StyleFilter`], grouped by row.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct StyleMatches {
    /// Total number of visible cells matching the filter.
    pub match_count: u32,
    /// Rows that contain at least one matching span.
    pub rows: Vec<StyleMatchRow>,
}

/// One row in [`StyleMatches`].
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct StyleMatchRow {
    /// Zero-based row index.
    pub row: u16,
    /// Contiguous spans of matching cells. Adjacent cells with the same
    /// [`Attrs`] coalesce into one span.
    pub spans: Vec<StyleMatchSpan>,
}

/// One contiguous run of matching cells within a row.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct StyleMatchSpan {
    /// Starting column, inclusive.
    pub col: u16,
    /// Ending column, inclusive.
    pub end_col: u16,
    /// Concatenated text of the span's cells.
    pub text: String,
    /// Full SGR attributes shared by the span's cells.
    pub attrs: Attrs,
}

impl Snapshot {
    /// Enumerate distinct [`Attrs`] values across `range` with counts and
    /// samples.
    ///
    /// The default [`Attrs`] sorts first when present; remaining entries
    /// sort by descending non-empty cell count.
    #[must_use]
    pub fn styles(&self, range: RowRange) -> StyleInventory {
        let Some((start, end)) = clamp_range(range, self.size().rows) else {
            return StyleInventory::default();
        };

        let mut map: HashMap<Attrs, Accumulator> = HashMap::new();

        for row in start..=end {
            for (_col, cell) in row_cells(self, row) {
                let nonempty = is_nonempty_cell(&cell.contents);
                let acc = map.entry(cell.attrs).or_default();

                if nonempty {
                    acc.cell_count += 1;
                }

                if acc.rows.last() != Some(&row) {
                    acc.rows.push(row);
                }

                if !acc.sample_found {
                    if nonempty {
                        acc.sample.push_str(&cell.contents);
                    } else if !acc.sample.is_empty() {
                        acc.sample_found = true;
                    }
                }
            }
            for acc in map.values_mut() {
                if !acc.sample.is_empty() && !acc.sample_found {
                    acc.sample_found = true;
                }
            }
        }

        for acc in map.values_mut() {
            if acc.sample.chars().count() > SAMPLE_CHAR_LIMIT {
                acc.sample = acc.sample.chars().take(SAMPLE_CHAR_LIMIT).collect();
            }
        }

        let mut entries: Vec<StyleInventoryEntry> = map
            .into_iter()
            .map(|(attrs, acc)| StyleInventoryEntry {
                attrs,
                cell_count: acc.cell_count,
                row_count: acc.rows.len() as u16,
                rows: acc.rows,
                sample: acc.sample,
            })
            .collect();

        let default_attrs = Attrs::default();
        entries.sort_by(|a, b| {
            let a_default = a.attrs == default_attrs;
            let b_default = b.attrs == default_attrs;
            match (a_default, b_default) {
                (true, false) => std::cmp::Ordering::Less,
                (false, true) => std::cmp::Ordering::Greater,
                _ => b.cell_count.cmp(&a.cell_count),
            }
        });

        StyleInventory { entries }
    }

    /// Find cells whose [`Attrs`] satisfy `filter` across `range`,
    /// coalescing adjacent matches with identical attributes into spans.
    #[must_use]
    pub fn style_matches(&self, filter: &StyleFilter, range: RowRange) -> StyleMatches {
        let Some((start, end)) = clamp_range(range, self.size().rows) else {
            return StyleMatches::default();
        };

        let mut match_count: u32 = 0;
        let mut rows: Vec<StyleMatchRow> = Vec::new();

        for row in start..=end {
            let mut spans: Vec<StyleMatchSpan> = Vec::new();
            let mut current: Option<StyleMatchSpan> = None;

            for (col, cell) in row_cells(self, row) {
                if filter.matches(&cell.attrs) {
                    match_count += 1;
                    match current.as_mut() {
                        Some(span) if span.attrs == cell.attrs && col == span.end_col + 1 => {
                            span.end_col = col;
                            span.text.push_str(&cell.contents);
                        }
                        _ => {
                            if let Some(span) = current.take() {
                                spans.push(span);
                            }
                            current = Some(StyleMatchSpan {
                                col,
                                end_col: col,
                                text: cell.contents.clone(),
                                attrs: cell.attrs,
                            });
                        }
                    }
                } else if let Some(span) = current.take() {
                    spans.push(span);
                }
            }

            if let Some(span) = current.take() {
                spans.push(span);
            }
            if !spans.is_empty() {
                rows.push(StyleMatchRow { row, spans });
            }
        }

        StyleMatches { match_count, rows }
    }
}

const SAMPLE_CHAR_LIMIT: usize = 60;

#[derive(Default)]
struct Accumulator {
    cell_count: u32,
    rows: Vec<u16>,
    sample: String,
    sample_found: bool,
}

fn clamp_range(range: RowRange, rows: u16) -> Option<(u16, u16)> {
    if rows == 0 {
        return None;
    }
    let last = rows - 1;
    let (start, end) = match range {
        RowRange::All => (0, last),
        RowRange::Range(start, end) => (start, end),
        RowRange::From(start) => (start, last),
        RowRange::UpTo(end) => (0, end),
    };
    if start > last {
        return None;
    }
    Some((start, end.min(last)))
}

fn row_cells(snapshot: &Snapshot, row: u16) -> impl Iterator<Item = (u16, &CellSnapshot)> {
    snapshot
        .cells()
        .get(row as usize)
        .into_iter()
        .flat_map(|cells| cells.iter().enumerate())
        .map(|(col, cell)| (col as u16, cell))
        .filter(|(_, cell)| !cell.wide_continuation)
}

fn is_nonempty_cell(contents: &str) -> bool {
    !contents.is_empty() && contents != " "
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::snapshot::CellSnapshot;
    use tastty::{Position, TerminalSize};

    fn make_cell(_row: u16, _col: u16, contents: &str, attrs: Attrs) -> CellSnapshot {
        CellSnapshot {
            contents: contents.to_string(),
            attrs,
            wide: false,
            wide_continuation: false,
            hyperlink: None,
        }
    }

    fn make_wide(row: u16, col: u16, contents: &str, attrs: Attrs) -> [CellSnapshot; 2] {
        let mut head = make_cell(row, col, contents, attrs);
        head.wide = true;
        let mut tail = make_cell(row, col + 1, "", attrs);
        tail.wide_continuation = true;
        [head, tail]
    }

    fn make_snapshot(rows: u16, cols: u16, cells: Vec<Vec<CellSnapshot>>) -> Snapshot {
        Snapshot {
            size: TerminalSize { rows, cols },
            cursor: Position { row: 0, col: 0 },
            cursor_visible: true,
            alternate_screen: false,
            title: String::new(),
            icon_name: String::new(),
            cells,
        }
    }

    fn pad_row(cells: Vec<CellSnapshot>, row: u16, cols: u16) -> Vec<CellSnapshot> {
        let mut out = cells;
        let next_col = out.len() as u16;
        let default_attrs = Attrs::default();
        for col in next_col..cols {
            out.push(make_cell(row, col, " ", default_attrs));
        }
        out
    }

    fn bold() -> Attrs {
        let mut a = Attrs::default();
        a.set_bold();
        a
    }

    fn italic() -> Attrs {
        let mut a = Attrs::default();
        a.set_italic(true);
        a
    }

    #[test]
    fn empty_snapshot_yields_empty_inventory() {
        let snapshot = make_snapshot(0, 0, Vec::new());
        let inv = snapshot.styles(RowRange::all());
        assert!(inv.entries.is_empty());
    }

    #[test]
    fn single_style_inventory_counts_only_nonempty_cells() {
        let row0: Vec<CellSnapshot> = vec![
            make_cell(0, 0, "h", bold()),
            make_cell(0, 1, "i", bold()),
            make_cell(0, 2, " ", bold()),
            make_cell(0, 3, "x", bold()),
            make_cell(0, 4, "y", bold()),
        ];
        let snapshot = make_snapshot(1, 5, vec![row0]);

        let inv = snapshot.styles(RowRange::all());
        assert_eq!(inv.entries.len(), 1);
        let entry = &inv.entries[0];
        assert_eq!(entry.attrs, bold());
        assert_eq!(entry.cell_count, 4);
        assert_eq!(entry.row_count, 1);
        assert_eq!(entry.rows, vec![0]);
        assert_eq!(entry.sample, "hi");
    }

    #[test]
    fn multiple_styles_default_first_then_descending_count() {
        let row0 = pad_row(
            vec![
                make_cell(0, 0, "x", bold()),
                make_cell(0, 1, "a", Attrs::default()),
                make_cell(0, 2, "b", Attrs::default()),
                make_cell(0, 3, "c", Attrs::default()),
                make_cell(0, 4, "y", italic()),
                make_cell(0, 5, "z", italic()),
            ],
            0,
            8,
        );
        let snapshot = make_snapshot(1, 8, vec![row0]);

        let inv = snapshot.styles(RowRange::all());
        assert_eq!(inv.entries.len(), 3);
        assert_eq!(inv.entries[0].attrs, Attrs::default());
        assert_eq!(inv.entries[0].cell_count, 3);
        assert_eq!(inv.entries[1].attrs, italic());
        assert_eq!(inv.entries[1].cell_count, 2);
        assert_eq!(inv.entries[2].attrs, bold());
        assert_eq!(inv.entries[2].cell_count, 1);
    }

    #[test]
    fn wide_continuation_cells_do_not_inflate_counts() {
        let mut row0_cells: Vec<CellSnapshot> = Vec::new();
        let wide_pair = make_wide(0, 0, "W", bold());
        row0_cells.push(wide_pair[0].clone());
        row0_cells.push(wide_pair[1].clone());
        row0_cells.push(make_cell(0, 2, "x", bold()));
        let row0 = pad_row(row0_cells, 0, 5);
        let snapshot = make_snapshot(1, 5, vec![row0]);

        let inv = snapshot.styles(RowRange::all());
        let bold_entry = inv
            .entries
            .iter()
            .find(|e| e.attrs == bold())
            .expect("bold entry");
        assert_eq!(bold_entry.cell_count, 2);
        assert_eq!(bold_entry.sample, "Wx");
    }

    #[test]
    fn row_range_constructors_map_to_variants() {
        assert_eq!(RowRange::all(), RowRange::All);
        assert_eq!(RowRange::new(2, 5), RowRange::Range(2, 5));
        assert_eq!(RowRange::from(3), RowRange::From(3));
        assert_eq!(RowRange::up_to(8), RowRange::UpTo(8));
        assert_eq!(RowRange::single(7), RowRange::Range(7, 7));
        assert_eq!(RowRange::default(), RowRange::All);
    }

    #[test]
    fn row_range_from_clamps_end_to_last_row() {
        let row0 = pad_row(vec![make_cell(0, 0, "a", bold())], 0, 3);
        let row1 = pad_row(vec![make_cell(1, 0, "b", italic())], 1, 3);
        let snapshot = make_snapshot(2, 3, vec![row0, row1]);

        let inv = snapshot.styles(RowRange::from(1));
        let italic_entry = inv.entries.iter().find(|e| e.attrs == italic()).unwrap();
        assert_eq!(italic_entry.cell_count, 1);
        assert!(inv.entries.iter().all(|e| e.attrs != bold()));
    }

    #[test]
    fn row_range_up_to_caps_iteration_at_end() {
        let row0 = pad_row(vec![make_cell(0, 0, "a", bold())], 0, 3);
        let row1 = pad_row(vec![make_cell(1, 0, "b", italic())], 1, 3);
        let snapshot = make_snapshot(2, 3, vec![row0, row1]);

        let inv = snapshot.styles(RowRange::up_to(0));
        let bold_entry = inv.entries.iter().find(|e| e.attrs == bold()).unwrap();
        assert_eq!(bold_entry.cell_count, 1);
        assert!(inv.entries.iter().all(|e| e.attrs != italic()));
    }

    #[test]
    fn row_range_from_past_end_yields_empty() {
        let row0 = pad_row(vec![make_cell(0, 0, "a", bold())], 0, 3);
        let snapshot = make_snapshot(1, 3, vec![row0]);

        let inv = snapshot.styles(RowRange::from(5));
        assert!(inv.entries.is_empty());
    }

    #[test]
    fn row_range_all_variant_covers_every_row() {
        let row0 = pad_row(vec![make_cell(0, 0, "a", bold())], 0, 3);
        let row1 = pad_row(vec![make_cell(1, 0, "b", italic())], 1, 3);
        let snapshot = make_snapshot(2, 3, vec![row0, row1]);

        let inv = snapshot.styles(RowRange::All);
        let bold_entry = inv.entries.iter().find(|e| e.attrs == bold()).unwrap();
        let italic_entry = inv.entries.iter().find(|e| e.attrs == italic()).unwrap();
        assert_eq!(bold_entry.cell_count, 1);
        assert_eq!(italic_entry.cell_count, 1);
    }

    #[test]
    fn row_range_clamps_end_past_screen() {
        let row0 = pad_row(vec![make_cell(0, 0, "a", bold())], 0, 3);
        let row1 = pad_row(vec![make_cell(1, 0, "b", italic())], 1, 3);
        let snapshot = make_snapshot(2, 3, vec![row0, row1]);

        let inv = snapshot.styles(RowRange::new(0, 99));
        let bold_entry = inv.entries.iter().find(|e| e.attrs == bold()).unwrap();
        let italic_entry = inv.entries.iter().find(|e| e.attrs == italic()).unwrap();
        assert_eq!(bold_entry.cell_count, 1);
        assert_eq!(italic_entry.cell_count, 1);
    }

    #[test]
    fn row_range_start_past_screen_yields_empty() {
        let row0 = pad_row(vec![make_cell(0, 0, "a", bold())], 0, 3);
        let snapshot = make_snapshot(1, 3, vec![row0]);

        let inv = snapshot.styles(RowRange::new(5, 10));
        assert!(inv.entries.is_empty());
    }

    #[test]
    fn row_range_single_isolates_one_row() {
        let row0 = pad_row(vec![make_cell(0, 0, "a", bold())], 0, 3);
        let row1 = pad_row(vec![make_cell(1, 0, "b", italic())], 1, 3);
        let snapshot = make_snapshot(2, 3, vec![row0, row1]);

        let inv = snapshot.styles(RowRange::single(1));
        let only = inv
            .entries
            .iter()
            .find(|e| e.attrs == italic())
            .expect("italic entry from row 1");
        assert_eq!(only.cell_count, 1);
        assert!(inv.entries.iter().all(|e| e.attrs != bold()));
    }

    #[test]
    fn style_matches_coalesces_adjacent_cells() {
        let row0 = pad_row(
            vec![
                make_cell(0, 0, "a", bold()),
                make_cell(0, 1, "b", bold()),
                make_cell(0, 2, "c", Attrs::default()),
                make_cell(0, 3, "d", bold()),
            ],
            0,
            5,
        );
        let snapshot = make_snapshot(1, 5, vec![row0]);

        let filter = StyleFilter {
            bold: Some(true),
            ..StyleFilter::default()
        };
        let matches = snapshot.style_matches(&filter, RowRange::all());
        assert_eq!(matches.match_count, 3);
        assert_eq!(matches.rows.len(), 1);
        let spans = &matches.rows[0].spans;
        assert_eq!(spans.len(), 2);
        assert_eq!(spans[0].col, 0);
        assert_eq!(spans[0].end_col, 1);
        assert_eq!(spans[0].text, "ab");
        assert_eq!(spans[1].col, 3);
        assert_eq!(spans[1].end_col, 3);
        assert_eq!(spans[1].text, "d");
    }

    #[test]
    fn style_matches_filter_negate_inverts() {
        let row0 = pad_row(
            vec![
                make_cell(0, 0, "a", bold()),
                make_cell(0, 1, "b", Attrs::default()),
            ],
            0,
            3,
        );
        let snapshot = make_snapshot(1, 3, vec![row0]);

        let filter = StyleFilter {
            bold: Some(true),
            negate: true,
            ..StyleFilter::default()
        };
        let matches = snapshot.style_matches(&filter, RowRange::all());
        assert!(matches.match_count >= 1);
        let texts: String = matches
            .rows
            .iter()
            .flat_map(|r| r.spans.iter())
            .map(|s| s.text.clone())
            .collect();
        assert!(texts.contains('b'));
        assert!(!texts.contains('a'));
    }

    #[test]
    fn color_filter_named_red_matches_both_normal_and_bright_palette() {
        let mut red = Attrs::default();
        red.fg_color = Color::Index(1);
        let mut bright_red = Attrs::default();
        bright_red.fg_color = Color::Index(9);
        let mut blue = Attrs::default();
        blue.fg_color = Color::Index(4);

        let filter = StyleFilter {
            fg: Some(ColorFilter::Named("red".to_string())),
            ..StyleFilter::default()
        };
        assert!(filter.matches(&red));
        assert!(filter.matches(&bright_red));
        assert!(!filter.matches(&blue));
    }

    #[test]
    fn color_filter_bright_named_only_matches_bright_palette() {
        let mut red = Attrs::default();
        red.fg_color = Color::Index(1);
        let mut bright_red = Attrs::default();
        bright_red.fg_color = Color::Index(9);

        let filter = StyleFilter {
            fg: Some(ColorFilter::Named("bright_red".to_string())),
            ..StyleFilter::default()
        };
        assert!(!filter.matches(&red));
        assert!(filter.matches(&bright_red));
    }

    #[test]
    fn color_filter_default_and_non_default_are_complementary() {
        let plain = Attrs::default();
        let mut colored = Attrs::default();
        colored.fg_color = Color::Index(1);

        let default_filter = StyleFilter {
            fg: Some(ColorFilter::Default),
            ..StyleFilter::default()
        };
        let non_default_filter = StyleFilter {
            fg: Some(ColorFilter::NonDefault),
            ..StyleFilter::default()
        };
        assert!(default_filter.matches(&plain));
        assert!(!default_filter.matches(&colored));
        assert!(!non_default_filter.matches(&plain));
        assert!(non_default_filter.matches(&colored));
    }

    #[test]
    fn color_filter_rgb_matches_exact_channels() {
        let mut attrs = Attrs::default();
        attrs.fg_color = Color::Rgb(255, 0, 0);

        let filter = StyleFilter {
            fg: Some(ColorFilter::Rgb { r: 255, g: 0, b: 0 }),
            ..StyleFilter::default()
        };
        assert!(filter.matches(&attrs));

        let other = StyleFilter {
            fg: Some(ColorFilter::Rgb { r: 0, g: 255, b: 0 }),
            ..StyleFilter::default()
        };
        assert!(!other.matches(&attrs));
    }

    #[test]
    fn empty_filter_matches_every_cell() {
        let filter = StyleFilter::default();
        assert!(filter.matches(&Attrs::default()));
        assert!(filter.matches(&bold()));
    }

    #[test]
    fn empty_negated_filter_rejects_every_cell() {
        let filter = StyleFilter {
            negate: true,
            ..StyleFilter::default()
        };
        assert!(!filter.matches(&Attrs::default()));
        assert!(!filter.matches(&bold()));
    }

    #[test]
    fn snapshot_styles_through_parser_does_not_double_count_wide_cells() {
        // Locks the wide_continuation skip end-to-end through Parser ->
        // Screen -> snapshot_from_screen -> Snapshot::styles. The unit
        // test above exercises the aggregator on a synthesized snapshot
        // only; this one exercises the full pipeline.
        use crate::snapshot::snapshot_from_screen;
        use tastty::{Parser, TerminalSize};

        let mut parser = Parser::new(TerminalSize { rows: 1, cols: 6 }, 0);
        // Bold "AB" then "あ" (UTF-8 \xe3\x81\x82, width 2). The wide
        // glyph claims columns 2 and 3; column 3 is the continuation.
        parser.process(b"\x1b[1mAB\xe3\x81\x82");

        let snapshot = snapshot_from_screen(parser.screen());
        let inv = snapshot.styles(RowRange::all());

        let bold_entry = inv
            .entries
            .iter()
            .find(|e| e.attrs.bold())
            .expect("bold entry from styled run");
        assert_eq!(
            bold_entry.cell_count, 3,
            "wide-glyph continuation must not inflate cell_count: \
             expected 3 (A + B + wide head), got {}",
            bold_entry.cell_count,
        );
    }
}