micro_gui/core/
layer.rs

1
2use std::*;
3
4use crate::core::buffer::Buff;
5use crate::types::rect::Rect;
6use crate::graphics::{Graphics, Renderable};
7
8/// Layers combine graphics functions to provide reusable blocks for rendering
9pub struct Layer<'a, Pixel> {
10    bounds: Rect,
11    visible: bool,
12    renderer: Option<&'a mut (Renderable<Pixel> + 'a)>,
13    children: vec::Vec<&'a mut Layer<'a, Pixel>>
14}
15
16impl <'a, Pixel>Layer<'a, Pixel> {
17    /// Create a new layer with the provided bounds
18    pub fn new(bounds: Rect, renderer: Option<&'a mut (Renderable<Pixel> + 'a)>) -> Layer<'a, Pixel> {
19        return Layer{bounds: bounds, visible: true, renderer, children: Vec::new()};
20    }
21
22    /// Fetch the bounds of a given layer
23    pub fn bounds(&self) -> Rect {
24        return self.bounds;
25    }
26
27    /// Set layer visible state
28    pub fn set_visible(&mut self, visible: bool) {
29        self.visible = visible;
30    }
31}
32
33impl <'a, Pixel>Renderable<Pixel> for Layer<'a, Pixel> {
34    /// Render a layer using the provided graphics context and buffer
35    fn render(&mut self, graphics: &mut Graphics<Pixel>, buffer: &mut Buff<Pixel>) {
36
37        if !self.visible {
38            return;
39        }
40
41        // Update graphics context with new layer bounds
42        let gfx_bounds = graphics.get_bounds();
43        let mut new_bounds = gfx_bounds;
44        new_bounds.x += self.bounds.x;
45        new_bounds.y += self.bounds.y;
46        new_bounds.w = if gfx_bounds.w > self.bounds.w { self.bounds.w } else { gfx_bounds.w };
47        new_bounds.h = if gfx_bounds.h > self.bounds.h { self.bounds.h } else { gfx_bounds.h };
48        graphics.set_bounds(&new_bounds);
49
50        // Render children
51        for child in self.children.iter_mut() {
52            child.render(graphics, buffer);
53        }
54
55        // Render parent
56        match self.renderer {
57            Some(ref mut r) => r.render(graphics, buffer),
58            None => ()
59        }
60
61        // Revert graphics context
62        graphics.set_bounds(&gfx_bounds);
63
64    }
65}