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
145
use Printer;
use With;
use direction::Direction;
use event::{Event, EventResult};
use vec::Vec2;
use view::View;
pub struct Canvas<T> {
state: T,
draw: Box<Fn(&Printer, &T)>,
on_event: Box<FnMut(Event, &mut T) -> EventResult>,
required_size: Box<FnMut(Vec2, &mut T) -> Vec2>,
layout: Box<FnMut(Vec2, &mut T)>,
take_focus: Box<FnMut(Direction, &mut T) -> bool>,
}
impl<T> Canvas<T> {
pub fn new(state: T) -> Self {
Canvas {
state: state,
draw: Box::new(|_, _| ()),
on_event: Box::new(|_, _| EventResult::Ignored),
required_size: Box::new(|_, _| Vec2::new(1, 1)),
layout: Box::new(|_, _| ()),
take_focus: Box::new(|_, _| false),
}
}
pub fn set_draw<F>(&mut self, f: F)
where F: 'static + Fn(&Printer, &T)
{
self.draw = Box::new(f);
}
pub fn with_draw<F>(self, f: F) -> Self
where F: 'static + Fn(&Printer, &T)
{
self.with(|s| s.set_draw(f))
}
pub fn set_on_event<F>(&mut self, f: F)
where F: 'static + FnMut(Event, &mut T) -> EventResult
{
self.on_event = Box::new(f);
}
pub fn with_on_event<F>(self, f: F) -> Self
where F: 'static + FnMut(Event, &mut T) -> EventResult
{
self.with(|s| s.set_on_event(f))
}
pub fn set_required_size<F>(&mut self, f: F)
where F: 'static + FnMut(Vec2, &mut T) -> Vec2
{
self.required_size = Box::new(f);
}
pub fn with_required_size<F>(self, f: F) -> Self
where F: 'static + FnMut(Vec2, &mut T) -> Vec2
{
self.with(|s| s.set_required_size(f))
}
pub fn set_layout<F>(&mut self, f: F)
where F: 'static + FnMut(Vec2, &mut T)
{
self.layout = Box::new(f);
}
pub fn with_layout<F>(self, f: F) -> Self
where F: 'static + FnMut(Vec2, &mut T)
{
self.with(|s| s.set_layout(f))
}
pub fn set_take_focus<F>(&mut self, f: F)
where F: 'static + FnMut(Direction, &mut T) -> bool
{
self.take_focus = Box::new(f);
}
pub fn with_take_focus<F>(self, f: F) -> Self
where F: 'static + FnMut(Direction, &mut T) -> bool
{
self.with(|s| s.set_take_focus(f))
}
}
impl <T> View for Canvas<T> {
fn draw(&self, printer: &Printer) {
(self.draw)(printer, &self.state);
}
fn on_event(&mut self, event: Event) -> EventResult {
(self.on_event)(event, &mut self.state)
}
fn required_size(&mut self, constraint: Vec2) -> Vec2 {
(self.required_size)(constraint, &mut self.state)
}
fn layout(&mut self, size: Vec2) {
(self.layout)(size, &mut self.state);
}
fn take_focus(&mut self, source: Direction) -> bool {
(self.take_focus)(source, &mut self.state)
}
}