-
Notifications
You must be signed in to change notification settings - Fork 53
/
appctx.rs
577 lines (508 loc) · 19.7 KB
/
appctx.rs
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
#[cfg(feature = "hlua")]
use std::cell::UnsafeCell;
use std::collections::HashMap;
#[cfg(not(feature = "hlua"))]
use std::marker::PhantomData;
use std::ops::DerefMut;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
use aabb_quadtree::{geom, ItemId, QuadTree};
#[cfg(feature = "hlua")]
use log::warn;
use crate::framebuffer::cgmath;
use crate::framebuffer::common::*;
use crate::framebuffer::core;
use crate::framebuffer::FramebufferDraw;
use crate::framebuffer::FramebufferRefresh;
use crate::framebuffer::PartialRefreshMode;
use crate::input::ev;
use crate::input::MultitouchEvent;
use crate::input::{InputDevice, InputEvent};
use crate::ui_extensions::element::{
ActiveRegionFunction, ActiveRegionHandler, UIConstraintRefresh, UIElementHandle,
UIElementWrapper,
};
#[cfg(feature = "hlua")]
use hlua::Lua;
#[cfg(feature = "hlua")]
use crate::ui_extensions::luaext;
unsafe impl<'a> Send for ApplicationContext<'a> {}
unsafe impl<'a> Sync for ApplicationContext<'a> {}
pub struct ApplicationContext<'a> {
framebuffer: Box<core::Framebuffer>,
yres: u32,
xres: u32,
running: AtomicBool,
#[cfg(feature = "hlua")]
lua: UnsafeCell<Lua<'a>>,
#[cfg(not(feature = "hlua"))]
lua: PhantomData<&'a ()>,
input_tx: std::sync::mpsc::Sender<InputEvent>,
input_rx: std::sync::mpsc::Receiver<InputEvent>,
button_ctx: RwLock<Option<ev::EvDevContext>>,
wacom_ctx: RwLock<Option<ev::EvDevContext>>,
touch_ctx: RwLock<Option<ev::EvDevContext>>,
active_regions: QuadTree<ActiveRegionHandler>,
ui_elements: HashMap<String, UIElementHandle>,
}
impl Default for ApplicationContext<'static> {
fn default() -> ApplicationContext<'static> {
let framebuffer = Box::new(core::Framebuffer::new());
let yres = framebuffer.var_screen_info.yres;
let xres = framebuffer.var_screen_info.xres;
let (input_tx, input_rx) = std::sync::mpsc::channel();
#[allow(unused_mut)] // Some features require this to be mut, some not
let mut res = ApplicationContext {
wacom_ctx: RwLock::new(None),
button_ctx: RwLock::new(None),
touch_ctx: RwLock::new(None),
framebuffer,
xres,
yres,
running: AtomicBool::new(false),
#[cfg(feature = "hlua")]
lua: UnsafeCell::new(Lua::new()),
#[cfg(not(feature = "hlua"))]
lua: PhantomData::default(),
input_rx,
input_tx,
ui_elements: HashMap::new(),
active_regions: QuadTree::default(geom::Rect::from_points(
&geom::Point { x: 0.0, y: 0.0 },
&geom::Point {
x: xres as f32,
y: yres as f32,
},
)),
};
// Enable all std lib
#[cfg(feature = "hlua")]
{
let lua = res.get_lua_ref();
lua.openlibs();
// Reluctantly resort to using a static global to associate the lua context with the
// one and only framebuffer that's going to be used
unsafe { luaext::G_FB = res.framebuffer.deref_mut() as *mut core::Framebuffer };
let mut nms = lua.empty_array("fb");
// Clears and refreshes the entire screen
nms.set("clear", hlua::function0(luaext::lua_clear));
// Refreshes the provided rectangle. Here we are exposing a predefined set of the
// flags to the Lua API to simplify its use for building interfaces.
nms.set("refresh", hlua::function6(luaext::lua_refresh));
// Draws text with rusttype
nms.set("draw_text", hlua::function5(luaext::lua_draw_text));
// Sets the pixel to the u8 color value, does no refresh. Refresh done explicitly via calling `refresh`
nms.set("set_pixel", hlua::function3(luaext::lua_set_pixel));
}
res
}
}
impl<'a> ApplicationContext<'a> {
pub fn get_framebuffer_ref(&mut self) -> &'static mut core::Framebuffer {
unsafe {
std::mem::transmute::<_, &'static mut core::Framebuffer>(self.framebuffer.deref_mut())
}
}
/// Perhaps this is bad practice but we know that the ApplicationContext,
/// just like the Framebuffer will have a static lifetime. We are doing this
/// so that we can have the event handlers call into the ApplicationContext.
pub fn upgrade_ref(&mut self) -> &'static mut ApplicationContext<'static> {
unsafe { std::mem::transmute(self) }
}
#[cfg(feature = "hlua")]
pub fn get_lua_ref(&mut self) -> &'a mut Lua<'static> {
#[allow(clippy::transmute_ptr_to_ref)]
unsafe {
std::mem::transmute::<_, &'a mut Lua<'static>>(self.lua.get())
}
}
pub fn get_dimensions(&self) -> (u32, u32) {
(self.yres, self.xres)
}
#[cfg(feature = "hlua")]
pub fn execute_lua(&mut self, code: &str) {
let lua = self.get_lua_ref();
if let Err(e) = lua.execute::<hlua::AnyLuaValue>(code) {
warn!("Error in Lua Context: {:?}", e);
}
}
#[allow(clippy::too_many_arguments)]
pub fn display_text(
&mut self,
position: cgmath::Point2<f32>,
c: color,
scale: f32,
border_px: u32,
border_padding: u32,
text: &str,
refresh: UIConstraintRefresh,
) -> mxcfb_rect {
let framebuffer = self.get_framebuffer_ref();
let mut draw_area: mxcfb_rect = framebuffer.draw_text(position, text, scale, c, false);
// Draw the border if border_px is set to a non-default value
if border_px > 0 {
draw_area = draw_area.expand(border_padding);
framebuffer.draw_rect(
draw_area.top_left().cast().unwrap(),
draw_area.size(),
border_px,
c,
);
}
let marker = match refresh {
UIConstraintRefresh::Refresh | UIConstraintRefresh::RefreshAndWait => framebuffer
.partial_refresh(
&draw_area,
PartialRefreshMode::Async,
waveform_mode::WAVEFORM_MODE_GC16_FAST,
display_temp::TEMP_USE_REMARKABLE_DRAW,
dither_mode::EPDC_FLAG_USE_DITHERING_PASSTHROUGH,
0,
false,
),
_ => return draw_area,
};
if let UIConstraintRefresh::RefreshAndWait = refresh {
framebuffer.wait_refresh_complete(marker);
}
draw_area.expand(border_px)
}
pub fn display_rect(
&mut self,
position: cgmath::Point2<i32>,
size: cgmath::Vector2<u32>,
border_px: u32,
border_color: color,
refresh: UIConstraintRefresh,
) -> mxcfb_rect {
let framebuffer = self.get_framebuffer_ref();
framebuffer.draw_rect(position, size, border_px, border_color);
let draw_area = mxcfb_rect::from(position.cast().unwrap(), size);
let marker = match refresh {
UIConstraintRefresh::Refresh | UIConstraintRefresh::RefreshAndWait => framebuffer
.partial_refresh(
&draw_area,
PartialRefreshMode::Async,
waveform_mode::WAVEFORM_MODE_GC16_FAST,
display_temp::TEMP_USE_REMARKABLE_DRAW,
dither_mode::EPDC_FLAG_USE_DITHERING_PASSTHROUGH,
0,
false,
),
_ => return draw_area,
};
if let UIConstraintRefresh::RefreshAndWait = refresh {
framebuffer.wait_refresh_complete(marker);
}
draw_area
}
pub fn display_image(
&mut self,
img: &image::DynamicImage,
position: cgmath::Point2<i32>,
refresh: UIConstraintRefresh,
) -> mxcfb_rect {
let framebuffer = self.get_framebuffer_ref();
let draw_area = match img {
image::DynamicImage::ImageRgb8(ref rgb) => framebuffer.draw_image(rgb, position),
other => framebuffer.draw_image(&other.to_rgb8(), position),
};
let marker = match refresh {
UIConstraintRefresh::Refresh | UIConstraintRefresh::RefreshAndWait => framebuffer
.partial_refresh(
&draw_area,
PartialRefreshMode::Async,
waveform_mode::WAVEFORM_MODE_GC16_FAST,
display_temp::TEMP_USE_REMARKABLE_DRAW,
dither_mode::EPDC_FLAG_USE_DITHERING_PASSTHROUGH,
0,
false,
),
_ => return draw_area,
};
if let UIConstraintRefresh::RefreshAndWait = refresh {
framebuffer.wait_refresh_complete(marker);
}
draw_area
}
pub fn add_element(
&mut self,
name: &str,
element: UIElementWrapper,
) -> Option<UIElementHandle> {
if self.ui_elements.contains_key(name) {
return None;
}
let elem = UIElementHandle::new(element);
self.ui_elements.insert(name.to_owned(), elem.clone());
Some(elem)
}
pub fn remove_element(&mut self, name: &str) -> bool {
self.ui_elements.remove(name).is_some()
}
pub fn remove_elements(&mut self) {
self.ui_elements.clear();
}
pub fn draw_element(&mut self, name: &str) -> bool {
let appref = self.upgrade_ref();
match self.ui_elements.get(name) {
None => false,
Some(element) => {
let handler = element.read().onclick.map(|handler| ActiveRegionHandler {
handler,
element: element.clone(),
});
element.write().draw(appref, &handler);
true
}
}
}
pub fn get_element_by_name(&mut self, name: &str) -> Option<UIElementHandle> {
self.ui_elements.get(name).cloned()
}
pub fn draw_elements(&mut self) {
start_bench!(stopwatch, draw_elements);
let mut elems: Vec<_> = self.ui_elements.values().cloned().collect();
for element in &mut elems {
let handler = element.read().onclick.map(|handler| ActiveRegionHandler {
handler,
element: element.clone(),
});
element.write().draw(self, &handler);
}
end_bench!(draw_elements);
}
/// Briefly flash the element's `last_drawn_rect`
pub fn flash_element(&mut self, name: &str) {
let framebuffer = self.get_framebuffer_ref();
if let Some(locked_element) = self.get_element_by_name(name) {
let mut element = locked_element.write();
if let Some(rect) = element.last_drawn_rect {
framebuffer.fill_rect(rect.top_left().cast().unwrap(), rect.size(), color::BLACK);
framebuffer.partial_refresh(
&rect,
PartialRefreshMode::Wait,
waveform_mode::WAVEFORM_MODE_DU,
display_temp::TEMP_USE_AMBIENT,
dither_mode::EPDC_FLAG_USE_DITHERING_PASSTHROUGH,
0,
false,
);
// We can pass None as the `handler` here as we know this flashing is not
// changing the positioning of the `UIElementWrapper`.
element.draw(self, &None);
}
}
}
pub fn clear(&mut self, deep: bool) {
let framebuffer = self.get_framebuffer_ref();
let (yres, xres) = (
framebuffer.var_screen_info.yres,
framebuffer.var_screen_info.xres,
);
framebuffer.clear();
if deep {
framebuffer.full_refresh(
waveform_mode::WAVEFORM_MODE_INIT,
display_temp::TEMP_USE_AMBIENT,
dither_mode::EPDC_FLAG_USE_DITHERING_PASSTHROUGH,
0,
true,
);
} else {
framebuffer.partial_refresh(
&mxcfb_rect {
top: 0,
left: 0,
height: yres,
width: xres,
},
PartialRefreshMode::Wait,
waveform_mode::WAVEFORM_MODE_GC16_FAST,
display_temp::TEMP_USE_AMBIENT,
dither_mode::EPDC_FLAG_USE_DITHERING_PASSTHROUGH,
0,
false,
);
}
}
/// Sets an atomic flag to disable event dispatch. Exiting event dispatch loop will cause
/// dispatch_events(..) function to reach completion.
pub fn stop(&mut self) {
// Deactivate the input devices even though they may not be active.
// This will stop the production of the input events.
self.deactivate_input_device(InputDevice::Multitouch);
self.deactivate_input_device(InputDevice::GPIO);
self.deactivate_input_device(InputDevice::Wacom);
// This will make us stop consuming and dispatching the InputEvents.
self.running.store(false, Ordering::Relaxed);
}
/// Returns true if the device is now signalled to be disabled.
/// If it was disabled prior to calling this function, this function
/// will immediately return `true`.
///
/// This function does not block until teardown is completed.
/// It will simply return after signalling the epoller, which is
/// guaranteed to exit completely, and can be verified by
/// calling `exited()`.
pub fn deactivate_input_device(&mut self, t: InputDevice) -> bool {
// Return true if already disabled
if !self.is_input_device_active(t) {
return true;
}
// Now we know that the device is active, we can move the context out of
// the option and stop it.
let mut dev = match t {
InputDevice::Wacom => self.wacom_ctx.write().unwrap(),
InputDevice::Multitouch => self.touch_ctx.write().unwrap(),
InputDevice::GPIO => self.button_ctx.write().unwrap(),
_ => return false,
};
let mut unwrapped = dev.take().unwrap();
unwrapped.stop();
true
}
/// Returns true if the device is now enabled. If it was enabled prior
/// to calling this function, this function will return `true`.
pub fn activate_input_device(&mut self, t: InputDevice) -> bool {
// Return true if already enabled
if self.is_input_device_active(t) {
return true;
}
// Now we know it isn't active, let's create and spawn
// the producer thread
let mut dev = match t {
InputDevice::Wacom => self.wacom_ctx.write().unwrap(),
InputDevice::Multitouch => self.touch_ctx.write().unwrap(),
InputDevice::GPIO => self.button_ctx.write().unwrap(),
_ => return false,
};
*dev = Some(ev::EvDevContext::new(t, self.input_tx.clone()));
match dev.as_mut() {
Some(ref mut device) => {
device.start();
true
}
None => false,
}
}
/// Returns true if the given `InputDevice` is active, as in
/// there is an `EvDevContext` for it and that context has a
/// currently running `epoll` thread
pub fn is_input_device_active(&self, t: InputDevice) -> bool {
let ctx = match t {
InputDevice::Unknown => return false,
InputDevice::GPIO => self.button_ctx.read().unwrap(),
InputDevice::Multitouch => self.touch_ctx.read().unwrap(),
InputDevice::Wacom => self.wacom_ctx.read().unwrap(),
};
match *ctx {
Some(ref c) => !c.exited() && !c.exit_requested(),
None => false,
}
}
pub fn event_receiver(&self) -> &std::sync::mpsc::Receiver<InputEvent> {
&self.input_rx
}
pub fn start_event_loop<F: FnMut(&mut ApplicationContext<'_>, InputEvent)>(
&mut self,
activate_wacom: bool,
activate_multitouch: bool,
activate_buttons: bool,
mut callback: F,
) {
let appref = self.upgrade_ref();
if activate_wacom {
self.activate_input_device(InputDevice::Wacom);
}
if activate_multitouch {
self.activate_input_device(InputDevice::Multitouch);
}
if activate_buttons {
self.activate_input_device(InputDevice::GPIO);
}
// Now we consume the input events
self.running.store(true, Ordering::Relaxed);
let mut last_active_region_gesture_id: i32 = -1;
while self.running.load(Ordering::Relaxed) {
let event = self.input_rx.recv();
match event {
Err(e) => println!("Error in input event consumer: {0}", e),
Ok(event) => {
if let InputEvent::MultitouchEvent { event } = event {
// Check for and notify clickable active regions for multitouch events
if let MultitouchEvent::Press { finger }
| MultitouchEvent::Move { finger } = event
{
let gseq = finger.tracking_id;
if last_active_region_gesture_id != gseq {
if let Some((h, _)) =
self.find_active_region(finger.pos.y, finger.pos.x)
{
(h.handler)(appref, h.element.clone());
}
last_active_region_gesture_id = gseq;
}
}
}
callback(appref, event);
}
};
}
}
pub fn handle_event(&mut self, event: InputEvent) {
let appref = self.upgrade_ref();
// Now we consume the input events
self.running.store(true, Ordering::Relaxed);
if self.running.load(Ordering::Relaxed) {
if let InputEvent::MultitouchEvent { event } = event {
// Check for and notify clickable active regions for multitouch events
if let MultitouchEvent::Press { finger } | MultitouchEvent::Move { finger } = event
{
if let Some((h, _)) = self.find_active_region(finger.pos.y, finger.pos.x) {
(h.handler)(appref, h.element.clone());
}
}
}
}
}
pub fn find_active_region(&self, y: u16, x: u16) -> Option<(&ActiveRegionHandler, ItemId)> {
let matches = self.active_regions.query(geom::Rect::centered_with_radius(
&geom::Point {
y: f32::from(y),
x: f32::from(x),
},
2.0,
));
matches.first().map(|res| (res.0, res.2))
}
pub fn remove_active_region_at_point(&mut self, y: u16, x: u16) -> bool {
match self.find_active_region(y, x) {
Some((_, itemid)) => self.active_regions.remove(itemid).is_some(),
_ => false,
}
}
pub fn create_active_region(
&mut self,
y: u16,
x: u16,
height: u16,
width: u16,
handler: ActiveRegionFunction,
element: UIElementHandle,
) {
self.active_regions.insert_with_box(
ActiveRegionHandler { handler, element },
geom::Rect::from_points(
&geom::Point {
x: f32::from(x),
y: f32::from(y),
},
&geom::Point {
x: f32::from(x + width),
y: f32::from(y + height),
},
),
);
}
}