-
Notifications
You must be signed in to change notification settings - Fork 27
/
window.rs
554 lines (486 loc) · 19.6 KB
/
window.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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE-APACHE file or at:
// https://www.apache.org/licenses/LICENSE-2.0
//! `Window` and `WindowList` types
use kas::cast::Cast;
use kas::draw::{AnimationState, DrawIface, DrawShared, PassId};
use kas::event::{ConfigMgr, CursorIcon, EventState, UpdateId};
use kas::geom::{Coord, Rect, Size};
use kas::layout::SolveCache;
use kas::theme::{DrawMgr, SizeMgr, ThemeControl, ThemeSize};
use kas::{Layout, TkAction, WidgetCore, WidgetExt, WindowId};
use kas_theme::{Theme, Window as _};
use std::time::Instant;
use winit::dpi::PhysicalSize;
use winit::error::OsError;
use winit::event::WindowEvent;
use winit::event_loop::EventLoopWindowTarget;
use winit::window::WindowBuilder;
use crate::draw::{CustomPipe, DrawPipe, DrawWindow};
use crate::shared::{PendingAction, SharedState};
use crate::ProxyAction;
/// Per-window data
pub(crate) struct Window<C: CustomPipe, T: Theme<DrawPipe<C>>> {
pub(crate) widget: kas::RootWidget,
pub(crate) window_id: WindowId,
ev_state: EventState,
solve_cache: SolveCache,
/// The winit window
pub(crate) window: winit::window::Window,
surface: wgpu::Surface,
sc_desc: wgpu::SurfaceConfiguration,
draw: DrawWindow<C::Window>,
theme_window: T::Window,
next_avail_frame_time: Instant,
queued_frame_time: Option<Instant>,
}
// Public functions, for use by the toolkit
impl<C: CustomPipe, T: Theme<DrawPipe<C>>> Window<C, T> {
/// Construct a window
pub fn new(
shared: &mut SharedState<C, T>,
elwt: &EventLoopWindowTarget<ProxyAction>,
window_id: WindowId,
widget: Box<dyn kas::Window>,
) -> Result<Self, OsError> {
let time = Instant::now();
let mut widget = kas::RootWidget::new(widget);
// Wayland only supports windows constructed via logical size
#[allow(unused_assignments, unused_mut)]
let mut use_logical_size = false;
#[cfg(any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
))]
{
use winit::platform::unix::EventLoopWindowTargetExtUnix;
use_logical_size = elwt.is_wayland();
}
let scale_factor = if use_logical_size {
1.0
} else {
shared.scale_factor as f32
};
let mut theme_window = shared.theme.new_window(scale_factor);
let dpem = theme_window.size().dpem();
let mut ev_state = EventState::new(shared.config.clone(), scale_factor, dpem);
let mut tkw = TkWindow::new(shared, None, &mut theme_window);
ev_state.full_configure(&mut tkw, widget.as_widget_mut());
let size_mgr = SizeMgr::new(theme_window.size());
let mut solve_cache = SolveCache::find_constraints(widget.as_widget_mut(), size_mgr);
// Opening a zero-size window causes a crash, so force at least 1x1:
let ideal = solve_cache.ideal(true).max(Size(1, 1));
let ideal = match use_logical_size {
false => ideal.as_physical(),
true => ideal.as_logical(),
};
let mut builder = WindowBuilder::new().with_inner_size(ideal);
let restrict_dimensions = widget.restrict_dimensions();
if restrict_dimensions.0 {
let min = solve_cache.min(true);
let min = match use_logical_size {
false => min.as_physical(),
true => min.as_logical(),
};
builder = builder.with_min_inner_size(min);
}
if restrict_dimensions.1 {
builder = builder.with_max_inner_size(ideal);
}
let window = builder
.with_title(widget.title())
.with_window_icon(widget.icon())
.build(elwt)?;
shared.init_clipboard(&window);
let scale_factor = window.scale_factor();
shared.scale_factor = scale_factor;
let size: Size = window.inner_size().cast();
log::info!(
"new: constructed with physical size {:?}, scale factor {}",
size,
scale_factor
);
// Now that we have a scale factor, we may need to resize:
if use_logical_size && scale_factor != 1.0 {
let scale_factor = scale_factor as f32;
shared.theme.update_window(&mut theme_window, scale_factor);
let dpem = theme_window.size().dpem();
ev_state.set_scale_factor(scale_factor, dpem);
solve_cache.invalidate_rule_cache();
}
let mut draw = shared.draw.draw.new_window();
shared.draw.draw.resize(&mut draw, size);
let surface = unsafe { shared.instance.create_surface(&window) };
let sc_desc = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: crate::draw::RENDER_TEX_FORMAT,
width: size.0.cast(),
height: size.1.cast(),
present_mode: wgpu::PresentMode::Mailbox,
alpha_mode: wgpu::CompositeAlphaMode::Auto,
};
surface.configure(&shared.draw.draw.device, &sc_desc);
let mut r = Window {
widget,
window_id,
ev_state,
solve_cache,
window,
surface,
sc_desc,
draw,
theme_window,
next_avail_frame_time: time,
queued_frame_time: Some(time),
};
r.apply_size(shared, true);
log::trace!(target: "kas_perf::wgpu::window", "new: {}µs", time.elapsed().as_micros());
Ok(r)
}
/// Handle an event
pub fn handle_event(&mut self, shared: &mut SharedState<C, T>, event: WindowEvent) {
// Note: resize must be handled here to re-configure self.surface.
match event {
WindowEvent::Destroyed => (),
WindowEvent::Resized(size) => self.do_resize(shared, size),
WindowEvent::ScaleFactorChanged {
scale_factor,
new_inner_size,
} => {
// Note: API allows us to set new window size here.
shared.scale_factor = scale_factor;
let scale_factor = scale_factor as f32;
shared
.theme
.update_window(&mut self.theme_window, scale_factor);
let dpem = self.theme_window.size().dpem();
self.ev_state.set_scale_factor(scale_factor, dpem);
self.solve_cache.invalidate_rule_cache();
self.do_resize(shared, *new_inner_size);
}
event => {
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
let widget = self.widget.as_widget_mut();
self.ev_state.with(&mut tkw, |mgr| {
mgr.handle_winit(widget, event);
});
if self.ev_state.action.contains(TkAction::RECONFIGURE) {
// Reconfigure must happen before further event handling
self.reconfigure(shared);
self.ev_state.action.remove(TkAction::RECONFIGURE);
}
}
}
}
/// Update, after receiving all events
pub fn update(&mut self, shared: &mut SharedState<C, T>) -> (TkAction, Option<Instant>) {
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
let action = self.ev_state.update(&mut tkw, self.widget.as_widget_mut());
if action.contains(TkAction::CLOSE | TkAction::EXIT) {
return (action, None);
}
self.handle_action(shared, action);
let mut resume = self.ev_state.next_resume();
if let Some(time) = self.queued_frame_time {
if time <= Instant::now() {
self.window.request_redraw();
self.queued_frame_time = None;
} else {
resume = resume.map(|t| t.min(time)).or(Some(time));
}
}
(action, resume)
}
/// Handle an action (excludes handling of CLOSE and EXIT)
pub fn handle_action(&mut self, shared: &mut SharedState<C, T>, action: TkAction) {
if action.contains(TkAction::RECONFIGURE) {
self.reconfigure(shared);
}
if action.contains(TkAction::THEME_UPDATE) {
let scale_factor = self.window.scale_factor() as f32;
shared
.theme
.update_window(&mut self.theme_window, scale_factor);
}
if action.contains(TkAction::RESIZE) {
self.solve_cache.invalidate_rule_cache();
self.apply_size(shared, false);
} else if action.contains(TkAction::SET_SIZE) {
self.apply_size(shared, false);
}
/*if action.contains(TkAction::Popup) {
let widget = &mut self.widget;
self.ev_state.with(&mut tkw, |mgr| widget.resize_popups(mgr));
self.ev_state.region_moved(&mut tkw, &mut *self.widget);
} else*/
if action.contains(TkAction::REGION_MOVED) {
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
self.ev_state
.region_moved(&mut tkw, self.widget.as_widget_mut());
}
if !action.is_empty() {
self.queued_frame_time = Some(self.next_avail_frame_time);
}
}
pub fn handle_closure(mut self, shared: &mut SharedState<C, T>) -> TkAction {
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
let widget = &mut self.widget;
self.ev_state.with(&mut tkw, |mgr| {
widget.handle_closure(mgr);
});
self.ev_state.update(&mut tkw, self.widget.as_widget_mut())
}
pub fn update_timer(&mut self, shared: &mut SharedState<C, T>) -> Option<Instant> {
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
let widget = self.widget.as_widget_mut();
self.ev_state.with(&mut tkw, |mgr| mgr.update_timer(widget));
self.next_resume()
}
pub fn update_widgets(&mut self, shared: &mut SharedState<C, T>, id: UpdateId, payload: u64) {
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
let widget = self.widget.as_widget_mut();
self.ev_state
.with(&mut tkw, |mgr| mgr.update_widgets(widget, id, payload));
}
pub fn add_popup(&mut self, shared: &mut SharedState<C, T>, id: WindowId, popup: kas::Popup) {
let widget = &mut self.widget;
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
self.ev_state
.with(&mut tkw, |mgr| widget.add_popup(mgr, id, popup));
}
pub fn send_action(&mut self, action: TkAction) {
self.ev_state.send_action(action);
}
pub fn send_close(&mut self, shared: &mut SharedState<C, T>, id: WindowId) {
if id == self.window_id {
self.ev_state.send_action(TkAction::CLOSE);
} else {
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
let widget = &mut self.widget;
self.ev_state
.with(&mut tkw, |mgr| widget.remove_popup(mgr, id));
}
}
}
// Internal functions
impl<C: CustomPipe, T: Theme<DrawPipe<C>>> Window<C, T> {
/// Swap-chain size
fn sc_size(&self) -> Size {
Size::new(self.sc_desc.width.cast(), self.sc_desc.height.cast())
}
fn reconfigure(&mut self, shared: &mut SharedState<C, T>) {
let time = Instant::now();
log::debug!("reconfigure");
let mut tkw = TkWindow::new(shared, Some(&self.window), &mut self.theme_window);
self.ev_state
.full_configure(&mut tkw, self.widget.as_widget_mut());
self.solve_cache.invalidate_rule_cache();
self.apply_size(shared, false);
log::trace!(target: "kas_perf::wgpu::window", "reconfigure: {}µs", time.elapsed().as_micros());
}
fn apply_size(&mut self, shared: &mut SharedState<C, T>, first: bool) {
let time = Instant::now();
let rect = Rect::new(Coord::ZERO, self.sc_size());
log::debug!("apply_size: rect={rect:?}");
let solve_cache = &mut self.solve_cache;
let widget = &mut self.widget;
let mut mgr = ConfigMgr::new(
self.theme_window.size(),
&mut shared.draw,
&mut self.ev_state,
);
solve_cache.apply_rect(widget.as_widget_mut(), &mut mgr, rect, true, first);
widget.resize_popups(&mut mgr);
let restrict_dimensions = self.widget.restrict_dimensions();
if restrict_dimensions.0 {
let min = self.solve_cache.min(true).as_physical();
self.window.set_min_inner_size(Some(min));
};
if restrict_dimensions.1 {
let ideal = self.solve_cache.ideal(true).as_physical();
self.window.set_max_inner_size(Some(ideal));
};
self.window.request_redraw();
log::trace!(
target: "kas_perf::wgpu::window",
"apply_size: {}µs", time.elapsed().as_micros(),
);
}
fn do_resize(&mut self, shared: &mut SharedState<C, T>, size: PhysicalSize<u32>) {
let time = Instant::now();
let size = size.cast();
if size == self.sc_size() {
return;
}
shared.draw.draw.resize(&mut self.draw, size);
self.sc_desc.width = size.0.cast();
self.sc_desc.height = size.1.cast();
self.surface
.configure(&shared.draw.draw.device, &self.sc_desc);
// Note that on resize, width adjustments may affect height
// requirements; we therefore refresh size restrictions.
self.apply_size(shared, false);
log::trace!(
target: "kas_perf::wgpu::window",
"do_resize: {}µs (includes apply_size)",
time.elapsed().as_micros()
);
}
// Draw. Return true when further event processing is needed immediately.
pub(crate) fn do_draw(&mut self, shared: &mut SharedState<C, T>) -> bool {
let start = Instant::now();
self.next_avail_frame_time = start + shared.frame_dur;
{
let draw = DrawIface {
draw: &mut self.draw,
shared: &mut shared.draw,
pass: PassId::new(0),
};
let mut draw = shared
.theme
.draw(draw, &mut self.ev_state, &mut self.theme_window);
let draw_mgr = DrawMgr::new(&mut draw, self.widget.id());
self.widget.draw(draw_mgr);
}
self.queued_frame_time = match self.draw.animation {
AnimationState::None => None,
AnimationState::Animate => Some(self.next_avail_frame_time),
AnimationState::Timed(time) => Some(time.max(self.next_avail_frame_time)),
};
self.draw.animation = AnimationState::None;
self.ev_state.action -= TkAction::REDRAW; // we just drew
if !self.ev_state.action.is_empty() {
log::info!("do_draw: abort and enqueue `Self::update` due to non-empty actions");
return true;
}
let time2 = Instant::now();
let frame = match self.surface.get_current_texture() {
Ok(frame) => frame,
Err(e) => {
log::error!("do_draw: failed to get frame texture: {}", e);
// It may be possible to recover by calling surface.configure(...) then retrying
// surface.get_current_texture(), but is doing so ever useful?
return true;
}
};
// TODO: check frame.suboptimal ?
let view = frame.texture.create_view(&Default::default());
let clear_color = to_wgpu_color(shared.theme.clear_color());
shared.render(&mut self.draw, &view, clear_color);
frame.present();
let end = Instant::now();
// Explanation: 'text' is the time to prepare positioned glyphs, 'frame-
// swap' is mostly about sync, 'render' is time to feed the GPU.
log::trace!(
target: "kas_perf::wgpu::window",
"do_draw: {}µs ({}μs widgets, {}µs text, {}µs render)",
(end - start).as_micros(),
(time2 - start).as_micros(),
self.draw.text.dur_micros(),
(end - time2).as_micros()
);
false
}
pub(crate) fn next_resume(&self) -> Option<Instant> {
match (self.ev_state.next_resume(), self.queued_frame_time) {
(Some(t1), Some(t2)) => Some(t1.min(t2)),
(Some(t), None) => Some(t),
(None, Some(t)) => Some(t),
(None, None) => None,
}
}
}
fn to_wgpu_color(c: kas::draw::color::Rgba) -> wgpu::Color {
wgpu::Color {
r: c.r as f64,
g: c.g as f64,
b: c.b as f64,
a: c.a as f64,
}
}
struct TkWindow<'a, C: CustomPipe, T: Theme<DrawPipe<C>>>
where
T::Window: kas_theme::Window,
{
shared: &'a mut SharedState<C, T>,
window: Option<&'a winit::window::Window>,
theme_window: &'a mut T::Window,
}
impl<'a, C: CustomPipe, T: Theme<DrawPipe<C>>> TkWindow<'a, C, T>
where
T::Window: kas_theme::Window,
{
fn new(
shared: &'a mut SharedState<C, T>,
window: Option<&'a winit::window::Window>,
theme_window: &'a mut T::Window,
) -> Self {
TkWindow {
shared,
window,
theme_window,
}
}
}
impl<'a, C, T> kas::ShellWindow for TkWindow<'a, C, T>
where
C: CustomPipe,
T: Theme<DrawPipe<C>>,
T::Window: kas_theme::Window,
{
fn add_popup(&mut self, popup: kas::Popup) -> Option<WindowId> {
self.window.map(|w| w.id()).map(|parent_id| {
let id = self.shared.next_window_id();
self.shared
.pending
.push(PendingAction::AddPopup(parent_id, id, popup));
id
})
}
fn add_window(&mut self, widget: Box<dyn kas::Window>) -> WindowId {
// By far the simplest way to implement this is to let our call
// anscestor, event::Loop::handle, do the work.
//
// In theory we could pass the EventLoopWindowTarget for *each* event
// handled to create the winit window here or use statics to generate
// errors now, but user code can't do much with this error anyway.
let id = self.shared.next_window_id();
self.shared
.pending
.push(PendingAction::AddWindow(id, widget));
id
}
fn close_window(&mut self, id: WindowId) {
self.shared.pending.push(PendingAction::CloseWindow(id));
}
fn update_all(&mut self, id: UpdateId, payload: u64) {
self.shared.update_all(id, payload);
}
#[inline]
fn get_clipboard(&mut self) -> Option<String> {
self.shared.get_clipboard()
}
#[inline]
fn set_clipboard<'c>(&mut self, content: String) {
self.shared.set_clipboard(content);
}
fn adjust_theme(&mut self, f: &mut dyn FnMut(&mut dyn ThemeControl) -> TkAction) {
let action = f(&mut self.shared.theme);
self.shared.pending.push(PendingAction::TkAction(action));
}
fn size_and_draw_shared(&mut self, f: &mut dyn FnMut(&mut dyn ThemeSize, &mut dyn DrawShared)) {
use kas_theme::Window;
let mut size = self.theme_window.size();
f(&mut size, &mut self.shared.draw);
}
#[inline]
fn set_cursor_icon(&mut self, icon: CursorIcon) {
if let Some(window) = self.window {
window.set_cursor_icon(icon);
}
}
}