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
use Printer;
use direction::Direction;
use event::{Event, EventResult};
use std::any::Any;
use vec::Vec2;
use view::{Selector, View};
pub trait ViewWrapper {
type V: View;
fn with_view<F, R>(&self, f: F) -> Option<R> where F: FnOnce(&Self::V) -> R;
fn with_view_mut<F, R>(&mut self, f: F) -> Option<R>
where F: FnOnce(&mut Self::V) -> R;
fn wrap_draw(&self, printer: &Printer) {
self.with_view(|v| v.draw(printer));
}
fn wrap_required_size(&mut self, req: Vec2) -> Vec2 {
self.with_view_mut(|v| v.required_size(req)).unwrap_or_else(Vec2::zero)
}
fn wrap_on_event(&mut self, ch: Event) -> EventResult {
self.with_view_mut(|v| v.on_event(ch)).unwrap_or(EventResult::Ignored)
}
fn wrap_layout(&mut self, size: Vec2) {
self.with_view_mut(|v| v.layout(size));
}
fn wrap_take_focus(&mut self, source: Direction) -> bool {
self.with_view_mut(|v| v.take_focus(source)).unwrap_or(false)
}
fn wrap_call_on_any<'a>(&mut self, selector: &Selector,
callback: Box<FnMut(&mut Any) + 'a>) {
self.with_view_mut(|v| v.call_on_any(selector, callback));
}
fn wrap_focus_view(&mut self, selector: &Selector) -> Result<(), ()> {
self.with_view_mut(|v| v.focus_view(selector)).unwrap_or(Err(()))
}
fn wrap_needs_relayout(&self) -> bool {
self.with_view(|v| v.needs_relayout()).unwrap_or(true)
}
}
impl<T: ViewWrapper> View for T {
fn draw(&self, printer: &Printer) {
self.wrap_draw(printer);
}
fn required_size(&mut self, req: Vec2) -> Vec2 {
self.wrap_required_size(req)
}
fn on_event(&mut self, ch: Event) -> EventResult {
self.wrap_on_event(ch)
}
fn layout(&mut self, size: Vec2) {
self.wrap_layout(size);
}
fn take_focus(&mut self, source: Direction) -> bool {
self.wrap_take_focus(source)
}
fn call_on_any<'a>(&mut self, selector: &Selector,
callback: Box<FnMut(&mut Any) + 'a>) {
self.wrap_call_on_any(selector, callback)
}
fn needs_relayout(&self) -> bool {
self.wrap_needs_relayout()
}
fn focus_view(&mut self, selector: &Selector) -> Result<(), ()> {
self.wrap_focus_view(selector)
}
}
#[macro_export]
macro_rules! wrap_impl {
(self.$v:ident: $t:ty) => {
type V = $t;
fn with_view<F, R>(&self, f: F) -> Option<R>
where F: FnOnce(&Self::V) -> R
{
Some(f(&self.$v))
}
fn with_view_mut<F, R>(&mut self, f: F) -> Option<R>
where F: FnOnce(&mut Self::V) -> R
{
Some(f(&mut self.$v))
}
};
}