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
use std::cell::Cell;
use std::panic;
use image::{GenericImageView, Pixel};
use instant::Instant;
use winit::window::Icon;
use abstutil::{elapsed_seconds, Timer};
use geom::Duration;
use crate::app_state::App;
use crate::assets::Assets;
use crate::tools::screenshot::screenshot_everything;
use crate::{
Canvas, CanvasSettings, Event, EventCtx, GfxCtx, Prerender, SharedAppState, Style, Text,
UpdateType, UserInput,
};
const UPDATE_FREQUENCY: std::time::Duration = std::time::Duration::from_millis(1000 / 30);
const DEBUG_PERFORMANCE: bool = false;
pub(crate) struct State<A: SharedAppState> {
pub(crate) app: App<A>,
pub(crate) canvas: Canvas,
style: Style,
focus_owned_by: Option<String>,
}
impl<A: SharedAppState> State<A> {
fn event(&mut self, mut ev: Event, prerender: &Prerender) -> (Vec<UpdateType>, bool) {
if let Event::MouseWheelScroll(dx, dy) = ev {
if self.canvas.settings.invert_scroll {
ev = Event::MouseWheelScroll(-dx, -dy);
}
}
if let Event::Update(_) = ev {
} else {
prerender
.inner
.set_cursor_icon(if self.canvas.drag_canvas_from.is_some() {
if matches!(ev, Event::LeftMouseButtonUp { .. }) {
winit::window::CursorIcon::Default
} else {
winit::window::CursorIcon::Grabbing
}
} else {
winit::window::CursorIcon::Default
});
}
let input = UserInput::new(ev, &self.canvas);
{
if let Event::WindowResized(new_size) = input.event {
let inner_size = prerender.window_size();
trace!(
"winit event says the window was resized from {}, {} to {:?}. But inner size \
is {:?}, so using that",
self.canvas.window_width,
self.canvas.window_height,
new_size,
inner_size
);
prerender.window_resized(inner_size);
self.canvas.window_width = inner_size.width;
self.canvas.window_height = inner_size.height;
}
if let Event::KeyPress(key) = input.event {
self.canvas.keys_held.insert(key);
} else if let Event::KeyRelease(key) = input.event {
self.canvas.keys_held.remove(&key);
}
if let Some(pt) = input.get_moved_mouse() {
self.canvas.cursor = pt;
}
if input.event == Event::WindowGainedCursor {
self.canvas.window_has_cursor = true;
}
if input.window_lost_cursor() {
self.canvas.window_has_cursor = false;
}
}
match panic::catch_unwind(panic::AssertUnwindSafe(|| {
let mut ctx = EventCtx {
fake_mouseover: false,
input,
canvas: &mut self.canvas,
prerender,
style: &mut self.style,
updates_requested: vec![],
canvas_movement_called: false,
focus_owned_by: self.focus_owned_by.take(),
next_focus_owned_by: None,
};
let started = Instant::now();
self.app.event(&mut ctx);
self.focus_owned_by = ctx.next_focus_owned_by.take();
if DEBUG_PERFORMANCE {
println!("- event() took {}s", elapsed_seconds(started));
}
if ctx.canvas.drag_canvas_from.is_some() && !ctx.canvas_movement_called {
ctx.canvas.drag_canvas_from = None;
}
let input_used = match ev {
Event::KeyRelease(_) => ctx.input.has_been_consumed(),
_ => true,
};
(ctx.updates_requested, input_used)
})) {
Ok(pair) => pair,
Err(err) => {
self.app.shared_app_state.dump_before_abort(&self.canvas);
panic::resume_unwind(err);
}
}
}
pub(crate) fn draw(&mut self, prerender: &Prerender, screenshot: bool) -> Option<String> {
let mut g = GfxCtx::new(prerender, &self.canvas, &self.style, screenshot);
self.canvas.start_drawing();
let started = Instant::now();
if let Err(err) = panic::catch_unwind(panic::AssertUnwindSafe(|| {
self.app.draw(&mut g);
})) {
self.app.shared_app_state.dump_before_abort(&self.canvas);
panic::resume_unwind(err);
}
let naming_hint = g.naming_hint.take();
if DEBUG_PERFORMANCE {
println!(
"----- {} uploads, {} draw calls, {} forks. draw() took {} -----",
g.get_num_uploads(),
g.num_draw_calls,
g.num_forks,
elapsed_seconds(started)
);
}
prerender.inner.draw_finished(g.inner);
naming_hint
}
pub(crate) fn free_memory(&mut self) {
self.app.shared_app_state.free_memory();
}
}
pub struct Settings {
pub(crate) window_title: String,
#[cfg(target_arch = "wasm32")]
pub(crate) root_dom_element_id: String,
pub(crate) assets_base_url: Option<String>,
pub(crate) assets_are_gzipped: bool,
dump_raw_events: bool,
pub(crate) scale_factor: Option<f64>,
require_minimum_width: Option<f64>,
window_icon: Option<String>,
loading_tips: Option<Text>,
pub(crate) read_svg: Box<dyn Fn(&str) -> Vec<u8>>,
pub(crate) canvas_settings: CanvasSettings,
}
impl Settings {
pub fn new(window_title: &str) -> Settings {
Settings {
window_title: window_title.to_string(),
#[cfg(target_arch = "wasm32")]
root_dom_element_id: "widgetry-canvas".to_string(),
assets_base_url: None,
assets_are_gzipped: false,
dump_raw_events: false,
scale_factor: None,
require_minimum_width: None,
window_icon: None,
loading_tips: None,
read_svg: Box::new(|path| {
use std::io::Read;
let mut file =
std::fs::File::open(path).unwrap_or_else(|_| panic!("Couldn't read {}", path));
let mut buffer = Vec::new();
file.read_to_end(&mut buffer)
.unwrap_or_else(|_| panic!("Couldn't read all of {}", path));
buffer
}),
canvas_settings: CanvasSettings::new(),
}
}
pub fn dump_raw_events(mut self) -> Self {
assert!(!self.dump_raw_events);
self.dump_raw_events = true;
self
}
pub fn scale_factor(mut self, scale_factor: f64) -> Self {
self.scale_factor = Some(scale_factor);
self
}
#[cfg(target_arch = "wasm32")]
pub fn root_dom_element_id(mut self, element_id: String) -> Self {
self.root_dom_element_id = element_id;
self
}
pub fn require_minimum_width(mut self, width: f64) -> Self {
self.require_minimum_width = Some(width);
self
}
pub fn window_icon(mut self, path: String) -> Self {
self.window_icon = Some(path);
self
}
pub fn loading_tips(mut self, txt: Text) -> Self {
self.loading_tips = Some(txt);
self
}
pub fn read_svg(mut self, function: Box<dyn Fn(&str) -> Vec<u8>>) -> Self {
self.read_svg = function;
self
}
pub fn assets_base_url(mut self, value: String) -> Self {
self.assets_base_url = Some(value);
self
}
pub fn assets_are_gzipped(mut self, value: bool) -> Self {
self.assets_are_gzipped = value;
self
}
pub fn canvas_settings(mut self, settings: CanvasSettings) -> Self {
self.canvas_settings = settings;
self
}
}
pub fn run<
A: 'static + SharedAppState,
F: FnOnce(&mut EventCtx) -> (A, Vec<Box<dyn crate::app_state::State<A>>>),
>(
settings: Settings,
make_app: F,
) -> ! {
let mut timer = Timer::new("setup widgetry");
let (prerender_innards, event_loop) = crate::backend::setup(&settings, &mut timer);
if let Some(ref path) = settings.window_icon {
if !cfg!(target_arch = "wasm32") {
let image = image::open(path).unwrap();
let (width, height) = image.dimensions();
let mut rgba = Vec::with_capacity((width * height) as usize * 4);
for (_, _, pixel) in image.pixels() {
rgba.extend_from_slice(&pixel.to_rgba().0);
}
let icon = Icon::from_rgba(rgba, width, height).unwrap();
prerender_innards.set_window_icon(icon);
}
}
let mut style = Style::light_bg();
style.loading_tips = settings.loading_tips.unwrap_or_else(Text::new);
let monitor_scale_factor = prerender_innards.monitor_scale_factor();
let mut prerender = Prerender {
assets: Assets::new(
style.clone(),
settings.assets_base_url,
settings.assets_are_gzipped,
settings.read_svg,
),
num_uploads: Cell::new(0),
inner: prerender_innards,
scale_factor: settings.scale_factor.unwrap_or(monitor_scale_factor),
};
if let Some(min_width) = settings.require_minimum_width {
let initial_size = prerender.window_size();
if initial_size.width < min_width && settings.scale_factor.is_none() {
warn!(
"Monitor scale factor is {}, screen window is {}, but the application requires \
{}. Overriding the scale factor to 1.",
monitor_scale_factor, initial_size.width, min_width
);
prerender.scale_factor = 1.0;
}
}
let initial_size = prerender.window_size();
let mut canvas = Canvas::new(initial_size, settings.canvas_settings);
prerender.window_resized(initial_size);
timer.start("setup app");
let (shared_app_state, states) = make_app(&mut EventCtx {
fake_mouseover: true,
input: UserInput::new(Event::NoOp, &canvas),
canvas: &mut canvas,
prerender: &prerender,
style: &mut style,
updates_requested: vec![],
canvas_movement_called: false,
focus_owned_by: None,
next_focus_owned_by: None,
});
timer.stop("setup app");
let app = App {
states,
shared_app_state,
};
timer.done();
let mut state = State {
app,
canvas,
style,
focus_owned_by: None,
};
let dump_raw_events = settings.dump_raw_events;
let mut running = true;
let mut last_update = Instant::now();
let mut previous_left_click_at = Instant::now();
event_loop.run(move |event, _, control_flow| {
if dump_raw_events {
debug!("Event: {:?}", event);
}
let ev = match event {
winit::event::Event::WindowEvent {
event: winit::event::WindowEvent::CloseRequested,
..
} => {
state.app.shared_app_state.before_quit(&state.canvas);
std::process::exit(0);
}
winit::event::Event::WindowEvent { event, .. } => {
let scale_factor = prerender.get_scale_factor();
if let Some(ev) =
Event::from_winit_event(event, scale_factor, previous_left_click_at)
{
ev
} else {
return;
}
}
winit::event::Event::RedrawRequested(_) => {
state.draw(&prerender, false);
prerender.num_uploads.set(0);
return;
}
winit::event::Event::MainEventsCleared => {
if running {
Event::Update(Duration::realtime_elapsed(last_update))
} else {
return;
}
}
_ => {
return;
}
};
match ev {
Event::Update(_) => {
last_update = Instant::now();
*control_flow =
winit::event_loop::ControlFlow::WaitUntil(Instant::now() + UPDATE_FREQUENCY);
}
Event::LeftMouseButtonUp {
is_double_click: false,
} => {
previous_left_click_at = Instant::now();
}
_ => {}
}
let (mut updates, input_used) = state.event(ev, &prerender);
if input_used {
prerender.request_redraw();
}
if updates.is_empty() {
updates.push(UpdateType::InputOnly);
}
for update in updates {
match update {
UpdateType::InputOnly => {
running = false;
*control_flow = winit::event_loop::ControlFlow::Wait;
}
UpdateType::Game => {
if !running {
last_update = Instant::now();
*control_flow = winit::event_loop::ControlFlow::WaitUntil(
Instant::now() + UPDATE_FREQUENCY,
);
}
running = true;
}
UpdateType::Pan => {}
UpdateType::ScreenCaptureEverything { dir, zoom, dims } => {
if let Err(err) =
screenshot_everything(&mut state, &dir, &prerender, zoom, dims)
{
error!("Couldn't screenshot everything: {}", err);
}
}
}
}
});
}