use crate::core::buffer::Buffer;
use crate::core::geom::{Rect, Size};
pub struct Surface {
pub area: Rect,
pub z: i32,
pub buf: Buffer,
}
impl Surface {
pub fn new(area: Rect, z: i32) -> Self {
Surface {
area,
z,
buf: Buffer::transparent(Size::new(area.width, area.height)),
}
}
pub fn buffer(&mut self) -> &mut Buffer {
&mut self.buf
}
}
#[derive(Default)]
pub struct Compositor {
surfaces: Vec<Surface>,
}
impl Compositor {
pub fn new() -> Self {
Compositor::default()
}
pub fn push(&mut self, surface: Surface) {
self.surfaces.push(surface);
}
pub fn layer(&mut self, area: Rect, z: i32) -> &mut Surface {
self.surfaces.push(Surface::new(area, z));
self.surfaces.last_mut().unwrap()
}
pub fn is_empty(&self) -> bool {
self.surfaces.is_empty()
}
pub fn composite(mut self, root: &mut Buffer) {
self.surfaces.sort_by_key(|s| s.z);
for s in &self.surfaces {
root.blit(s.area.x, s.area.y, &s.buf, true);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::style::{Color, Style};
#[test]
fn higher_z_wins_and_transparency_shows_through() {
let mut root = Buffer::blank(Size::new(10, 3));
root.set_str(0, 0, "..........", Style::new());
let mut comp = Compositor::new();
let low = comp.layer(Rect::new(1, 0, 3, 1), 1).buffer();
low.set(0, 0, 'A', Style::new().fg(Color::rgb(1, 1, 1)));
low.set(1, 0, 'A', Style::new());
low.set(2, 0, 'A', Style::new());
let high = comp.layer(Rect::new(2, 0, 3, 1), 5).buffer();
high.set(0, 0, 'B', Style::new());
comp.composite(&mut root);
let row: String = (0..10).map(|x| root.get(x, 0).unwrap().ch).collect();
assert_eq!(row, ".ABA......");
}
}