Skip to main content

photon_ui/
compositor.rs

1use unicode_width::UnicodeWidthChar;
2
3use crate::{
4    layer::Shadow,
5    layout::Rect,
6    renderer::{
7        ImageCommand,
8        Rendered,
9    },
10    utils::AnsiCodeTracker,
11};
12
13/// Normalized style state for a single terminal cell.
14#[derive(Debug, Clone, PartialEq, Default)]
15pub struct CellStyle {
16    /// Bold (SGR 1) is active.
17    pub bold: bool,
18    /// Faint / dim (SGR 2) is active.
19    pub faint: bool,
20    /// Italic (SGR 3) is active.
21    pub italic: bool,
22    /// Underline (SGR 4) is active.
23    pub underline: bool,
24    /// Reverse video (SGR 7) is active.
25    pub reverse: bool,
26    /// Active foreground color SGR parameter.
27    pub fg_color: Option<String>,
28    /// Active background color SGR parameter.
29    pub bg_color: Option<String>,
30    /// Active OSC 8 hyperlink, if any.
31    pub hyperlink: Option<crate::utils::ActiveHyperlink>,
32    /// Unrecognized ANSI sequences that should be emitted verbatim before this
33    /// cell's symbol.
34    pub prefix: String,
35}
36
37impl CellStyle {
38    fn from_tracker(tracker: &AnsiCodeTracker, prefix: &str) -> Self {
39        Self {
40            bold: tracker.bold,
41            faint: tracker.faint,
42            italic: tracker.italic,
43            underline: tracker.underline,
44            reverse: tracker.reverse,
45            fg_color: tracker.fg_color.clone(),
46            bg_color: tracker.bg_color.clone(),
47            hyperlink: tracker.hyperlink.clone(),
48            prefix: prefix.to_string(),
49        }
50    }
51
52    fn has_sgr(&self) -> bool {
53        self.bold ||
54            self.faint ||
55            self.italic ||
56            self.underline ||
57            self.reverse ||
58            self.fg_color.is_some() ||
59            self.bg_color.is_some() ||
60            !self.prefix.is_empty()
61    }
62
63    fn sgr_sequence(&self) -> String {
64        let mut parts = Vec::new();
65        if self.bold {
66            parts.push("1");
67        }
68        if self.faint {
69            parts.push("2");
70        }
71        if self.italic {
72            parts.push("3");
73        }
74        if self.underline {
75            parts.push("4");
76        }
77        if self.reverse {
78            parts.push("7");
79        }
80        if let Some(ref fg) = self.fg_color {
81            parts.push(fg.as_str());
82        }
83        if let Some(ref bg) = self.bg_color {
84            parts.push(bg.as_str());
85        }
86        if parts.is_empty() {
87            String::new()
88        } else {
89            format!("\x1b[{}m", parts.join(";"))
90        }
91    }
92}
93
94/// A single display cell in the compositor's internal grid.
95#[derive(Debug, Clone, PartialEq, Default)]
96pub struct Cell {
97    /// The visual symbol for this cell. Empty when this cell is the second half
98    /// of a full-width character.
99    pub symbol: String,
100    /// The normalized style for this cell.
101    pub style: CellStyle,
102    /// Display width: `0` for a continuation spacer, `1` for normal, `2` for
103    /// the first half of a full-width character.
104    pub width: u8,
105    /// Whether this cell is transparent padding beyond the line's real content.
106    pub transparent: bool,
107}
108
109fn is_opaque(cell: &Cell) -> bool {
110    cell.width > 0 && !cell.transparent
111}
112
113/// Region over which a shadow is applied to lower layers.
114#[derive(Debug, Clone, PartialEq)]
115enum ShadowRegion {
116    /// Every cell except those covered by the layer that cast the shadow.
117    Complement(Vec<Vec<bool>>),
118    /// A concrete rectangle.
119    Rect(Rect),
120}
121
122/// A shadow cast by one layer onto layers below it.
123#[derive(Debug, Clone, PartialEq)]
124struct ShadowMask {
125    region: ShadowRegion,
126    style: CellStyle,
127}
128
129impl ShadowMask {
130    fn covers(&self, row: usize, col: usize) -> bool {
131        match &self.region {
132            | ShadowRegion::Complement(covered) => {
133                if let Some(row_mask) = covered.get(row) &&
134                    let Some(cell) = row_mask.get(col)
135                {
136                    return !cell;
137                }
138                false
139            },
140            | ShadowRegion::Rect(rect) => {
141                let r = row as u16;
142                let c = col as u16;
143                r >= rect.y &&
144                    r < rect.y.saturating_add(rect.height) &&
145                    c >= rect.x &&
146                    c < rect.x.saturating_add(rect.width)
147            },
148        }
149    }
150}
151
152/// Composites multiple full-terminal-size layer buffers front-to-back.
153///
154/// Layers are added from highest index (front) to lowest index (back). Each
155/// layer is rendered independently; cells already covered by a higher layer are
156/// stripped from lower layers.
157pub struct Compositor {
158    width: usize,
159    height: usize,
160    output: Vec<Vec<Cell>>,
161    covered: Vec<Vec<bool>>,
162    shadows: Vec<ShadowMask>,
163    cursor: Option<(usize, usize)>,
164    images: Vec<ImageCommand>,
165}
166
167impl Compositor {
168    /// Create a compositor for the given terminal size.
169    pub fn new(width: u16, height: u16) -> Self {
170        let w = width as usize;
171        let h = height as usize;
172        Self {
173            width: w,
174            height: h,
175            output: vec![vec![Cell::default(); w]; h],
176            covered: vec![vec![false; w]; h],
177            shadows: Vec::new(),
178            cursor: None,
179            images: Vec::new(),
180        }
181    }
182
183    /// Add a layer's rendered buffer. Layers must be added front-to-back.
184    pub fn add_layer(&mut self, rendered: &Rendered, shadow: &Shadow) {
185        let grid = parse_rendered(rendered, self.width, self.height);
186        let mut layer_covered = vec![vec![false; self.width]; self.height];
187
188        for (r, row) in grid.iter().enumerate() {
189            let mut col = 0usize;
190            for cell in row {
191                if cell.width == 0 {
192                    continue;
193                }
194                let w = cell.width as usize;
195                let end = col + w;
196                let opaque = is_opaque(cell);
197                if opaque && end <= self.width && !self.is_covered(r, col, w) {
198                    let style = self.apply_shadows(r, col, &cell.style);
199                    self.output[r][col] = Cell {
200                        symbol: cell.symbol.clone(),
201                        style: style.clone(),
202                        width: cell.width,
203                        transparent: false,
204                    };
205                    if w == 2 {
206                        self.output[r][col + 1] = Cell {
207                            symbol: String::new(),
208                            style,
209                            width: 0,
210                            transparent: false,
211                        };
212                    }
213                    self.mark_covered(r, col, w);
214                }
215                if opaque {
216                    layer_covered[r][col] = true;
217                    if w == 2 {
218                        layer_covered[r][col + 1] = true;
219                    }
220                }
221                col += w;
222            }
223        }
224
225        if self.cursor.is_none() &&
226            let Some((r, c)) = rendered.cursor &&
227            r < self.height &&
228            c < self.width
229        {
230            self.cursor = Some((r, c));
231        }
232
233        self.images.extend(rendered.images.clone());
234        self.add_shadow(shadow, &layer_covered);
235    }
236
237    /// Consume the compositor and produce the final composite frame.
238    pub fn finalize(self) -> Rendered {
239        let mut lines = Vec::with_capacity(self.height);
240        for row in self.output {
241            lines.push(encode_cells_to_line(&row));
242        }
243        Rendered {
244            lines,
245            cursor: self.cursor,
246            images: self.images,
247        }
248    }
249
250    fn is_covered(&self, row: usize, col: usize, width: usize) -> bool {
251        if let Some(row_mask) = self.covered.get(row) {
252            for c in col..col + width {
253                if let Some(true) = row_mask.get(c) {
254                    return true;
255                }
256            }
257        }
258        false
259    }
260
261    fn mark_covered(&mut self, row: usize, col: usize, width: usize) {
262        if let Some(row_mask) = self.covered.get_mut(row) {
263            for c in col..col + width {
264                if let Some(cell) = row_mask.get_mut(c) {
265                    *cell = true;
266                }
267            }
268        }
269    }
270
271    fn apply_shadows(&self, row: usize, col: usize, style: &CellStyle) -> CellStyle {
272        let mut result = style.clone();
273        for shadow in &self.shadows {
274            if shadow.covers(row, col) {
275                result = merge_style(result, &shadow.style);
276            }
277        }
278        result
279    }
280
281    fn add_shadow(&mut self, shadow: &Shadow, layer_covered: &[Vec<bool>]) {
282        match shadow {
283            | Shadow::None => {},
284            | Shadow::Dim { style } => {
285                let cell_style = parse_style_string(style);
286                self.shadows.push(ShadowMask {
287                    region: ShadowRegion::Complement(layer_covered.to_vec()),
288                    style: cell_style,
289                });
290            },
291            | Shadow::Drop {
292                style,
293                offset_x,
294                offset_y,
295            } => {
296                let cell_style = parse_style_string(style);
297                if let Some(rect) = compute_bbox(layer_covered) {
298                    let right = (rect.x as i16).saturating_add(rect.width as i16);
299                    let bottom = (rect.y as i16).saturating_add(rect.height as i16);
300                    let ox = *offset_x;
301                    let oy = *offset_y;
302
303                    if ox > 0 {
304                        let x = right;
305                        let y = (rect.y as i16).saturating_add(oy);
306                        let shadow_rect =
307                            Rect::new(x.max(0) as u16, y.max(0) as u16, ox as u16, rect.height);
308                        self.shadows.push(ShadowMask {
309                            region: ShadowRegion::Rect(shadow_rect),
310                            style: cell_style.clone(),
311                        });
312                    } else if ox < 0 {
313                        let x = (rect.x as i16).saturating_add(ox);
314                        let y = (rect.y as i16).saturating_add(oy);
315                        let shadow_rect = Rect::new(
316                            x.max(0) as u16,
317                            y.max(0) as u16,
318                            ox.unsigned_abs(),
319                            rect.height,
320                        );
321                        self.shadows.push(ShadowMask {
322                            region: ShadowRegion::Rect(shadow_rect),
323                            style: cell_style.clone(),
324                        });
325                    }
326
327                    if oy > 0 {
328                        let x = (rect.x as i16).saturating_add(ox);
329                        let y = bottom;
330                        let shadow_rect =
331                            Rect::new(x.max(0) as u16, y.max(0) as u16, rect.width, oy as u16);
332                        self.shadows.push(ShadowMask {
333                            region: ShadowRegion::Rect(shadow_rect),
334                            style: cell_style.clone(),
335                        });
336                    } else if oy < 0 {
337                        let x = (rect.x as i16).saturating_add(ox);
338                        let y = (rect.y as i16).saturating_add(oy);
339                        let shadow_rect = Rect::new(
340                            x.max(0) as u16,
341                            y.max(0) as u16,
342                            rect.width,
343                            oy.unsigned_abs(),
344                        );
345                        self.shadows.push(ShadowMask {
346                            region: ShadowRegion::Rect(shadow_rect),
347                            style: cell_style,
348                        });
349                    }
350                }
351            },
352        }
353    }
354}
355
356fn merge_style(mut target: CellStyle, source: &CellStyle) -> CellStyle {
357    target.bold = target.bold || source.bold;
358    target.faint = target.faint || source.faint;
359    target.italic = target.italic || source.italic;
360    target.underline = target.underline || source.underline;
361    target.reverse = target.reverse || source.reverse;
362    if target.fg_color.is_none() && source.fg_color.is_some() {
363        target.fg_color = source.fg_color.clone();
364    }
365    if target.bg_color.is_none() && source.bg_color.is_some() {
366        target.bg_color = source.bg_color.clone();
367    }
368    if target.hyperlink.is_none() && source.hyperlink.is_some() {
369        target.hyperlink = source.hyperlink.clone();
370    }
371    if !source.prefix.is_empty() {
372        target.prefix.push_str(&source.prefix);
373    }
374    target
375}
376
377fn parse_style_string(style: &str) -> CellStyle {
378    let mut tracker = AnsiCodeTracker::new();
379    let mut prefix = String::new();
380    let mut chars = style.chars().peekable();
381    while let Some(ch) = chars.next() {
382        if ch == '\x1b' &&
383            let Some(seq) = extract_sequence(&mut chars)
384        {
385            let before = tracker.clone();
386            tracker.process(&seq);
387            if tracker == before {
388                prefix.push_str(&seq);
389            }
390        }
391    }
392    CellStyle::from_tracker(&tracker, &prefix)
393}
394
395fn compute_bbox(covered: &[Vec<bool>]) -> Option<Rect> {
396    let mut min_row: Option<usize> = None;
397    let mut max_row: Option<usize> = None;
398    let mut min_col: Option<usize> = None;
399    let mut max_col: Option<usize> = None;
400
401    for (r, row) in covered.iter().enumerate() {
402        for (c, cell) in row.iter().enumerate() {
403            if *cell {
404                if min_row.is_none() {
405                    min_row = Some(r);
406                }
407                max_row = Some(r);
408                if min_col.is_none_or(|m| c < m) {
409                    min_col = Some(c);
410                }
411                if max_col.is_none_or(|m| c > m) {
412                    max_col = Some(c);
413                }
414            }
415        }
416    }
417
418    match (min_row, max_row, min_col, max_col) {
419        | (Some(min_r), Some(max_r), Some(min_c), Some(max_c)) => Some(Rect::new(
420            min_c as u16,
421            min_r as u16,
422            (max_c - min_c + 1) as u16,
423            (max_r - min_r + 1) as u16,
424        )),
425        | _ => None,
426    }
427}
428
429fn parse_rendered(rendered: &Rendered, width: usize, height: usize) -> Vec<Vec<Cell>> {
430    let mut grid = vec![Vec::new(); height];
431    for (r, line) in rendered.lines.iter().enumerate() {
432        if r >= height {
433            break;
434        }
435        grid[r] = parse_line_to_cells(line, width);
436    }
437    grid
438}
439
440fn parse_line_to_cells(line: &str, max_width: usize) -> Vec<Cell> {
441    let mut cells: Vec<Cell> = Vec::new();
442    let mut tracker = AnsiCodeTracker::new();
443    let mut prefix = String::new();
444    let mut visible_width = 0usize;
445    let mut chars = line.chars().peekable();
446
447    while let Some(ch) = chars.next() {
448        if ch == '\x1b' {
449            if let Some(seq) = extract_sequence(&mut chars) {
450                let before = tracker.clone();
451                tracker.process(&seq);
452                if tracker == before {
453                    prefix.push_str(&seq);
454                }
455            }
456            continue;
457        }
458
459        let w = ch.width().unwrap_or(0);
460        if w == 0 {
461            if let Some(last) = cells.last_mut() {
462                last.symbol.push(ch);
463            }
464            continue;
465        }
466
467        if visible_width + w > max_width {
468            break;
469        }
470
471        let style = CellStyle::from_tracker(&tracker, &prefix);
472        prefix.clear();
473        cells.push(Cell {
474            symbol: ch.to_string(),
475            style,
476            width: w as u8,
477            transparent: false,
478        });
479        if w == 2 {
480            cells.push(Cell {
481                symbol: String::new(),
482                style: CellStyle::default(),
483                width: 0,
484                transparent: false,
485            });
486        }
487        visible_width += w;
488    }
489
490    // Compute the real content range: columns between the first and last
491    // non-whitespace / styled character. Plain whitespace outside this range is
492    // transparent padding; plain whitespace inside the range is intentional
493    // spacing and remains opaque.
494    let mut first_content_col: Option<usize> = None;
495    let mut last_content_col = 0usize;
496    let mut col = 0usize;
497    for cell in &cells {
498        if cell.width == 0 {
499            continue;
500        }
501        if !cell.symbol.trim().is_empty() || cell.style.has_sgr() {
502            if first_content_col.is_none() {
503                first_content_col = Some(col);
504            }
505            last_content_col = col + cell.width as usize;
506        }
507        col += cell.width as usize;
508    }
509
510    let first = first_content_col.unwrap_or(0);
511    let mut col = 0usize;
512    for cell in &mut cells {
513        if cell.width == 0 {
514            continue;
515        }
516        if (col < first || col >= last_content_col) && !cell.style.has_sgr() {
517            cell.transparent = true;
518        }
519        col += cell.width as usize;
520    }
521
522    cells
523}
524
525fn extract_sequence(chars: &mut std::iter::Peekable<std::str::Chars>) -> Option<String> {
526    let mut seq = String::from('\x1b');
527    match chars.peek() {
528        | Some(&'[') => {
529            chars.next();
530            seq.push('[');
531            while let Some(&c) = chars.peek() {
532                chars.next();
533                seq.push(c);
534                if c.is_alphabetic() {
535                    return Some(seq);
536                }
537            }
538        },
539        | Some(&']') => {
540            chars.next();
541            seq.push(']');
542            while let Some(&c) = chars.peek() {
543                chars.next();
544                seq.push(c);
545                if c == '\x07' {
546                    return Some(seq);
547                }
548                if c == '\x1b' &&
549                    let Some(&'\\') = chars.peek()
550                {
551                    chars.next();
552                    seq.push('\\');
553                    return Some(seq);
554                }
555            }
556        },
557        | _ => {},
558    }
559    None
560}
561
562fn encode_cells_to_line(cells: &[Cell]) -> String {
563    let mut line = String::new();
564    let mut current = CellStyle::default();
565
566    for cell in cells {
567        if cell.width == 0 {
568            continue;
569        }
570
571        if cell.style != current {
572            // Close hyperlink if it is changing.
573            if current.hyperlink != cell.style.hyperlink &&
574                let Some(ref link) = current.hyperlink
575            {
576                line.push_str(&format!("\x1b]8;;{}", link.terminator));
577            }
578            // Reset SGR when any parsed SGR attribute is currently active.
579            if current.has_sgr() {
580                line.push_str("\x1b[0m");
581            }
582            // Apply new SGR.
583            let sgr = cell.style.sgr_sequence();
584            if !sgr.is_empty() {
585                line.push_str(&sgr);
586            }
587            // Open new hyperlink if it differs from current.
588            if cell.style.hyperlink != current.hyperlink &&
589                let Some(ref link) = cell.style.hyperlink
590            {
591                line.push_str(&format!(
592                    "\x1b]8;{};{}{}",
593                    link.params, link.url, link.terminator
594                ));
595            }
596            // Emit any unrecognized prefix sequences.
597            if !cell.style.prefix.is_empty() {
598                line.push_str(&cell.style.prefix);
599            }
600            current = cell.style.clone();
601        }
602
603        line.push_str(&cell.symbol);
604    }
605
606    if let Some(ref link) = current.hyperlink {
607        line.push_str(&format!("\x1b]8;;{}", link.terminator));
608    }
609    if current.has_sgr() {
610        line.push_str("\x1b[0m");
611    }
612
613    line
614}
615
616#[cfg(test)]
617mod tests {
618    use super::*;
619
620    fn rendered_from(lines: &[&str]) -> Rendered {
621        Rendered {
622            lines: lines.iter().map(|s| s.to_string()).collect(),
623            cursor: None,
624            images: Vec::new(),
625        }
626    }
627
628    #[test]
629    fn cell_parse_empty_line() {
630        let cells = parse_line_to_cells("", 10);
631        assert!(cells.is_empty());
632    }
633
634    #[test]
635    fn cell_parse_plain_text() {
636        let cells = parse_line_to_cells("abc", 10);
637        assert_eq!(cells.len(), 3);
638        assert_eq!(cells[0].symbol, "a");
639        assert_eq!(cells[1].symbol, "b");
640        assert_eq!(cells[2].symbol, "c");
641        assert_eq!(cells[0].width, 1);
642    }
643
644    #[test]
645    fn cell_parse_ansi_bold() {
646        let cells = parse_line_to_cells("\x1b[1mhi\x1b[0m", 10);
647        assert_eq!(cells.len(), 2);
648        assert!(cells[0].style.bold);
649        // The reset comes after 'i', so 'i' is still bold at parse time.
650        assert!(cells[1].style.bold);
651    }
652
653    #[test]
654    fn cell_parse_ansi_colors() {
655        let cells = parse_line_to_cells("\x1b[31;44mX", 10);
656        assert_eq!(cells.len(), 1);
657        assert_eq!(cells[0].style.fg_color, Some("31".to_string()));
658        assert_eq!(cells[0].style.bg_color, Some("44".to_string()));
659    }
660
661    #[test]
662    fn cell_parse_hyperlink() {
663        let cells = parse_line_to_cells("\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\", 10);
664        assert_eq!(cells.len(), 4);
665        // The hyperlink is active for all visible characters; the close
666        // sequence follows the last character.
667        assert!(cells[0].style.hyperlink.is_some());
668        assert!(cells[3].style.hyperlink.is_some());
669    }
670
671    #[test]
672    fn cell_parse_cjk_and_emoji() {
673        let cells = parse_line_to_cells("漢a", 10);
674        assert_eq!(cells.len(), 3);
675        assert_eq!(cells[0].symbol, "漢");
676        assert_eq!(cells[0].width, 2);
677        assert_eq!(cells[1].width, 0);
678        assert_eq!(cells[2].symbol, "a");
679    }
680
681    #[test]
682    fn cell_encode_plain_text() {
683        let cells = parse_line_to_cells("abc", 10);
684        let line = encode_cells_to_line(&cells);
685        assert_eq!(line, "abc");
686    }
687
688    #[test]
689    fn cell_roundtrip_preserves_visible_width() {
690        let original = "\x1b[31mred\x1b[0m \x1b[1mbold\x1b[0m";
691        let cells = parse_line_to_cells(original, 20);
692        let encoded = encode_cells_to_line(&cells);
693        assert_eq!(
694            crate::utils::visible_width(&encoded),
695            crate::utils::visible_width(original)
696        );
697    }
698
699    #[test]
700    fn cell_encode_resets_at_line_end() {
701        let cells = parse_line_to_cells("\x1b[31mred", 10);
702        let line = encode_cells_to_line(&cells);
703        assert!(line.ends_with("\x1b[0m"));
704    }
705
706    #[test]
707    fn compositor_empty_layers() {
708        let mut comp = Compositor::new(10, 2);
709        comp.add_layer(&rendered_from(&["", ""]), &Shadow::None);
710        let out = comp.finalize();
711        assert_eq!(out.lines.len(), 2);
712        assert_eq!(out.lines[0], "");
713    }
714
715    #[test]
716    fn compositor_single_layer_passthrough() {
717        let mut comp = Compositor::new(5, 1);
718        comp.add_layer(&rendered_from(&["hello"]), &Shadow::None);
719        let out = comp.finalize();
720        assert_eq!(out.lines[0], "hello");
721    }
722
723    #[test]
724    fn compositor_two_layers_full_occlusion() {
725        let mut comp = Compositor::new(5, 1);
726        comp.add_layer(&rendered_from(&["WORLD"]), &Shadow::None);
727        comp.add_layer(&rendered_from(&["hello"]), &Shadow::None);
728        let out = comp.finalize();
729        assert_eq!(out.lines[0], "WORLD");
730    }
731
732    #[test]
733    fn compositor_three_layers_partial_occlusion() {
734        let mut comp = Compositor::new(5, 1);
735        comp.add_layer(&rendered_from(&["ABC  "]), &Shadow::None);
736        comp.add_layer(&rendered_from(&["  XYZ"]), &Shadow::None);
737        comp.add_layer(&rendered_from(&["12345"]), &Shadow::None);
738        let out = comp.finalize();
739        assert_eq!(out.lines[0], "ABCYZ");
740    }
741
742    #[test]
743    fn compositor_cursor_topmost_wins() {
744        let mut top = rendered_from(&["top"]);
745        top.cursor = Some((0, 2));
746        let mut bottom = rendered_from(&["bottom"]);
747        bottom.cursor = Some((0, 1));
748        let mut comp = Compositor::new(5, 1);
749        comp.add_layer(&top, &Shadow::None);
750        comp.add_layer(&bottom, &Shadow::None);
751        let out = comp.finalize();
752        assert_eq!(out.cursor, Some((0, 2)));
753    }
754
755    #[test]
756    fn compositor_images_merged_from_all_layers() {
757        let mut top = rendered_from(&["top"]);
758        top.images.push(ImageCommand {
759            id: 1,
760            data: "a".into(),
761            row: 0,
762            col: 0,
763        });
764        let mut bottom = rendered_from(&["bottom"]);
765        bottom.images.push(ImageCommand {
766            id: 2,
767            data: "b".into(),
768            row: 0,
769            col: 0,
770        });
771        let mut comp = Compositor::new(5, 1);
772        comp.add_layer(&top, &Shadow::None);
773        comp.add_layer(&bottom, &Shadow::None);
774        let out = comp.finalize();
775        assert_eq!(out.images.len(), 2);
776    }
777
778    #[test]
779    fn compositor_dim_shadow_applies_to_exposed_lower_cells() {
780        let mut comp = Compositor::new(5, 1);
781        comp.add_layer(
782            &rendered_from(&[" ABC "]),
783            &Shadow::Dim {
784                style: "\x1b[2m".into(),
785            },
786        );
787        comp.add_layer(&rendered_from(&["12345"]), &Shadow::None);
788        let out = comp.finalize();
789        // Columns 0 and 4 are exposed and should be dimmed.
790        assert!(out.lines[0].starts_with("\x1b[2m1"));
791        // Columns 1-3 are covered by the top layer.
792        assert!(out.lines[0].contains("ABC"));
793    }
794
795    #[test]
796    fn compositor_drop_shadow_offset_positive() {
797        let mut comp = Compositor::new(6, 3);
798        comp.add_layer(
799            &rendered_from(&["", " AB ", ""]),
800            &Shadow::Drop {
801                style: "\x1b[2m".into(),
802                offset_x: 1,
803                offset_y: 1,
804            },
805        );
806        comp.add_layer(
807            &rendered_from(&["XXXXXX", "XXXXXX", "XXXXXX"]),
808            &Shadow::None,
809        );
810        let out = comp.finalize();
811        // Drop shadow is rendered as an offset fringe. For a 2x1 object at
812        // (1, 1) with offset (1, 1), only the bottom strip at row 2 is shaded.
813        assert!(!out.lines[0].contains("\x1b[2m"));
814        assert!(!out.lines[1].contains("\x1b[2m"));
815        assert!(out.lines[2].contains("\x1b[2m"));
816    }
817
818    #[test]
819    fn compositor_shadow_none_is_identity() {
820        let mut comp = Compositor::new(5, 1);
821        comp.add_layer(&rendered_from(&["hello"]), &Shadow::None);
822        let out = comp.finalize();
823        assert_eq!(out.lines[0], "hello");
824    }
825
826    #[test]
827    fn compositor_ansi_reset_preserved_at_boundaries() {
828        let mut comp = Compositor::new(10, 1);
829        comp.add_layer(&rendered_from(&["     world"]), &Shadow::None);
830        comp.add_layer(
831            &rendered_from(&["\x1b[44mhello\x1b[0m     "]),
832            &Shadow::None,
833        );
834        let out = comp.finalize();
835        // The blue background from the bottom layer must be reset before the
836        // top layer's plain text begins.
837        assert!(out.lines[0].contains("\x1b[0m"));
838    }
839
840    #[test]
841    fn compositor_no_panic_on_oversized_layer() {
842        let mut comp = Compositor::new(3, 1);
843        comp.add_layer(&rendered_from(&["hello world"]), &Shadow::None);
844        let out = comp.finalize();
845        assert!(out.lines[0].len() <= 11);
846    }
847}