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
use view::{View, ViewWrapper};
use Printer;
use vec::Vec2;
use theme::ColorStyle;

/// Wrapper view that adds a shadow.
///
/// It reserves a 1 pixel border on each side.
pub struct ShadowView<T: View> {
    view: T,
    top_padding: bool,
    left_padding: bool,
}

impl<T: View> ShadowView<T> {
    /// Wraps the given view.
    pub fn new(view: T) -> Self {
        ShadowView {
            view: view,
            top_padding: true,
            left_padding: true,
        }
    }

    fn padding(&self) -> Vec2 {
        Vec2::new(1 + self.left_padding as usize,
                  1 + self.top_padding as usize)
    }

    /// If set, adds an empty column to the left of the view.
    ///
    /// Default to true.
    pub fn left_padding(mut self, value: bool) -> Self {
        self.left_padding = value;
        self
    }

    /// If set, adds an empty row at the top of the view.
    ///
    /// Default to true.
    pub fn top_padding(mut self, value: bool) -> Self {
        self.top_padding = value;
        self
    }
}

impl<T: View> ViewWrapper for ShadowView<T> {
    wrap_impl!(&self.view);

    fn wrap_get_min_size(&mut self, req: Vec2) -> Vec2 {
        // Make sure req >= offset
        let offset = self.padding().or_min(req);
        self.view.get_min_size(req - offset) + offset
    }

    fn wrap_layout(&mut self, size: Vec2) {
        let offset = self.padding().or_min(size);
        self.view.layout(size - offset);
    }

    fn wrap_draw(&self, printer: &Printer) {

        if printer.size.y == 0 || printer.size.x == 0 {
            // Nothing to do if there's no place to draw.
            return;
        }

        // Skip the first row/column
        let offset = Vec2::new(self.left_padding as usize,
                               self.top_padding as usize);
        let printer = &printer.offset(offset, true);

        // Draw the view background
        for y in 0..printer.size.y - 1 {
            printer.print_hline((0, y), printer.size.x - 1, " ");
        }

        self.view.draw(&printer.sub_printer(Vec2::zero(),
                                            printer.size - (1, 1),
                                            true));

        if printer.theme.shadow {
            let h = printer.size.y;
            let w = printer.size.x;

            printer.with_color(ColorStyle::Shadow, |printer| {
                printer.print_hline((1, h - 1), w - 1, " ");
                printer.print_vline((w - 1, 1), h - 1, " ");
            });
        }
    }
}